-
Notifications
You must be signed in to change notification settings - Fork 23
/
fine_tune.txt
1260 lines (1260 loc) · 478 KB
/
fine_tune.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{"prompt": "unchecked {\nuint256 share = points * _PRECISION / pool.totalPoints * totalReward;\nuint256 daoShare = share * pool.daoTax / (100 * _DIVISOR);\nshare /= _PRECISION;\ndaoShare /= _PRECISION;\nreturn ((share - daoShare), daoShare);\n}\n}\n", "completion": "Updating a pool\u2019s total points doesn\u2019t affect existing stake positions for rewards calculation"}
{"prompt": "uint256 points = amount * 100 / 1e18 * lpPosition.multiplier / _DIVISOR;\n\n// Update the caller's LP token stake.\nlpPosition.amount -= amount;\nlpPosition.points -= points;\n\n// Update the pool point weights for rewards.\npool.totalPoints -= points;\n}\n\n", "completion": "Underflow of lpPosition.points during withdrawLP causes huge reward minting"}
{"prompt": "? calculateReward(oldProfit, fixedJackpotSize, fixedJackpotSize, ticketsSold, true, expectedPayout)\n: calculateMultiplier(calculateExcessPot(oldProfit, fixedJackpotSize), ticketsSold, expectedPayout)\n* ticketsSold * expectedPayout;\n\ncurrentNetProfit,\nticketsSold[drawFinalized],\nticketPrice,\njackpotWinners > 0,\nfixedReward(selectionSize),\nexpectedPayout\n);\nwinningTicket[drawFinalized] = _winningTicket;\nreturn LotteryMath.calculateReward(\ncurrentNetProfit,\nfixedReward(winTier),\nfixedReward(selectionSize),\nticketsSold[drawId],\nwinTier == selectionSize,\nexpectedPayout\n);\n}\n\n", "completion": "LotteryMath.calculateNewProfit returns wrong profit when there is no jackpot winner"}
{"prompt": "function claimWinningTickets(uint256[] calldata ticketIds) external override returns (uint256 claimedAmount) {\nuint256 totalTickets = ticketIds.length;\nfor (uint256 i = 0; i < totalTickets; ++i) {\n", "completion": "The buyer of the ticket could be front-runned by the ticket owner who claims the rewards before the ticket\u2019s NFT is traded"}
{"prompt": "if (block.timestamp < drawScheduledAt(currentDraw)) {\nrevert ExecutingDrawTooEarly();\n}\nif (block.timestamp > ticketRegistrationDeadline(drawId)) {\nrevert TicketRegistrationClosed(drawId);\n}\n", "completion": "Possibility to steal jackpot bypassing restrictions in the executeDraw()"}
{"prompt": "revert ExecutingDrawTooEarly();\n}\nreturnUnclaimedJackpotToThePot();\nclaimableAmount = winAmount[ticketInfo.drawId][winTier];\n}\n}\n", "completion": "Insolvency: The Lottery may incorrectly consider a year old jackpot ticket as unclaimed and increase currentNetProfit by its prize while it was actually claimed"}
{"prompt": "function claimRewards(LotteryRewardType rewardType) external override returns (uint256 claimedAmount) {\naddress beneficiary = (rewardType == LotteryRewardType.FRONTEND) ? msg.sender : stakingRewardRecipient;\nclaimedAmount = LotteryMath.calculateRewards(ticketPrice, dueTicketsSoldAndReset(beneficiary), rewardType);\nfunction rewardPerToken() public view override returns (uint256 _rewardPerToken) {\nuint256 _totalSupply = totalSupply();\nif (_totalSupply == 0) {\n", "completion": "Locking rewards tokens in Staking contract when there are no stakes"}
{"prompt": "if (rewards.length != (selectionSize) || rewards[0] != 0) {\nrevert InvalidFixedRewardSetup();\n}\nuint256 divisor = 10 ** (IERC20Metadata(address(rewardToken)).decimals() - 1);\nfor (uint8 winTier = 1; winTier < selectionSize; ++winTier) {\nuint16 reward = uint16(rewards[winTier] / divisor);\nif ((rewards[winTier] % divisor) != 0) {\nrevert InvalidFixedRewardSetup();\n}\npacked |= uint256(reward) << (winTier * 16);\n}\n}\n}\n", "completion": "Unsafe casting from uint256 to uint16 could cause ticket prizes to become much smaller than intended"}
{"prompt": "function mint(bytes[] calldata _addList) external {\n_mint(msg.sender, ++numMinted); // We do not use _safeMint here on purpose. If a contract calls this method, he expects to get an NFT back\nbytes4 addSelector = this.add.selector;\nfunction add(\nuint256 _cidNFTID,\nstring calldata _subprotocolName,\nfunction remove(\nuint256 _cidNFTID,\nstring calldata _subprotocolName,\n", "completion": "Attacker can frontrun a victim\u2019s mint+add transaction to steal NFT"}
{"prompt": "cidNFTs[msg.sender] = _cidNFTID;\nemit CIDNFTAdded(msg.sender, _cidNFTID);\n}\n", "completion": "Multiple accounts can have the same identity"}
{"prompt": "return string(abi.encodePacked(baseURI, _id, \".json\"));\n}\n\n", "completion": "CidNFT: Broken tokenURI function"}
{"prompt": "_mint(msg.sender, ++numMinted); // We do not use _safeMint here on purpose. If a contract calls this method, he expects to get an NFT back\nbytes4 addSelector = this.add.selector;\nfor (uint256 i = 0; i < _addList.length; ++i) {\n(\nbool success, /*bytes memory result*/\n\n) = address(this).delegatecall(abi.encodePacked(addSelector, _addList[i]));\nif (!success) revert AddCallAfterMintingFailed(i);\n}\n}\n\nif (\ncidNFTOwner != msg.sender &&\ngetApproved[_cidNFTID] != msg.sender &&\n!isApprovedForAll[cidNFTOwner][msg.sender]\n) revert NotAuthorizedForCIDNFT(msg.sender, _cidNFTID, cidNFTOwner);\nif (_nftIDToAdd == 0) revert NFTIDZeroDisallowedForSubprotocols(); // ID 0 is disallowed in subprotocols\n", "completion": "Griefing risk in mint"}
{"prompt": "uint256 scale0 = FullMath.mulDiv(amount0, 1e18, liquidity) * token0Scale;\nuint256 scale1 = FullMath.mulDiv(amount1, 1e18, liquidity) * token1Scale;\n\n", "completion": "Precision loss in the invariant function can lead to loss of funds"}
{"prompt": "if (balanceAfter < balanceBefore + collateral) revert InsufficientInputError();\n\nemit Mint(msg.sender, collateral, shares, liquidity, to);\n", "completion": "Fee on transfer tokens will not behave as expected"}
{"prompt": " hex\"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303\" // init code hash\n)\n )\n", "completion": "Wrong init code hash"}
{"prompt": "uint256 scale0 = FullMath.mulDiv(amount0, 1e18, liquidity) * token0Scale;\nuint256 scale1 = FullMath.mulDiv(amount1, 1e18, liquidity) * token1Scale;\n\nuint256 scale1 = FullMath.mulDiv(amount1, 1e18, liquidity) * token1Scale;\n\nif (scale1 > 2 * upperBound) revert InvariantError();\nuint256 dilutionLPRequested = (FullMath.mulDiv(borrowRate, _totalLiquidityBorrowed, 1e18) * timeElapsed) / 365 days;\nuint256 dilutionLP = dilutionLPRequested > _totalLiquidityBorrowed ? _totalLiquidityBorrowed : dilutionLPRequested;\nuint256 dilutionSpeculative = convertLiquidityToCollateral(dilutionLP);\n", "completion": "Division before multiplication incurs unnecessary precision loss"}
{"prompt": " function addLiquidity(AddLiquidityParams calldata params) external payable checkDeadline(params.deadline) {\naddress lendgine = LendgineAddress.computeAddress(\n factory, params.token0, params.token1, params.token0Exp, params.token1Exp, params.upperBound\n", "completion": "First liquidity provider will suffer from revert or fund loss"}
{"prompt": "if (squeezeStartCap < _currCycleStart()) squeezeStartCap = _currCycleStart();\nif (squeezeStartCap < squeezeEndCap) {\nsqueezedRevIdxs[squeezedNum++] = i;\namt += _squeezedAmt(userId, drips, squeezeStartCap, squeezeEndCap);\n}\n}\n", "completion": "Drips that end after the current cycle but before its creation can allow users to profit from squeezing"}
{"prompt": "historyHashes = _verifyDripsHistory(historyHash, dripsHistory, sender.dripsHistoryHash);\n// If the last update was not in the current cycle,\n// there's only the single latest history entry to squeeze in the current cycle.\nrequire(historyHash == finalHistoryHash, \"Invalid drips history\");\n}\n\n", "completion": "Squeezing drips from a sender can be front-run and prevented by the sender"}
{"prompt": "/// @param user The authorized address.\nfunction authorize(address user) public {\naddress sender = _msgSender();\nrequire(_authorized[sender].add(user), \"Address already is authorized\");\nemit Authorized(sender, user);\n}\n\n/// @notice Revokes the authorization of an address to make calls on behalf of the sender.\n/// @param user The unauthorized address.\nfunction unauthorize(address user) public {\naddress sender = _msgSender();\nrequire(_authorized[sender].remove(user), \"Address is not authorized\");\nemit Unauthorized(sender, user);\n}\n\n/// @notice Checks if an address is authorized to make calls on behalf of a sender.\n", "completion": "unauthorize() can be front-run so that the malicious authorized user would get their authority back"}
{"prompt": "msg.sender == minterAddress;\n_;\n}\n\nmsg.sender == minterAddress;\n_;\n}\n\n", "completion": "Bad implementation in minter access control for RabbitHoleReceipt and RabbitHoleTickets contracts"}
{"prompt": "IERC20(rewardToken).safeTransfer(protocolFeeRecipient, protocolFee());\n}\n}\n", "completion": "Protocol fees can be withdrawn multiple times in Erc20Quest"}
{"prompt": "Erc20Quest newQuest = new Erc20Quest(\nrewardTokenAddress_,\nendTime_,\nErc1155Quest newQuest = new Erc1155Quest(\nrewardTokenAddress_,\nendTime_,\n", "completion": "QuestFactory is suspicious of the reorg attack"}
{"prompt": "if (quests[questId_].numberMinted + 1 > quests[questId_].totalParticipants) revert OverMaxAllowedToMint();\nif (quests[questId_].addressMinted[msg.sender] == true) revert AddressAlreadyMinted();\nif (keccak256(abi.encodePacked(msg.sender, questId_)) != hash_) revert InvalidHash();\nif (recoverSigner(hash_, signature_) != claimSignerAddress) revert AddressNotSigned();\n\nquests[questId_].addressMinted[msg.sender] = true;\nquests[questId_].numberMinted++;\nemit ReceiptMinted(msg.sender, questId_);\nrabbitholeReceiptContract.mint(msg.sender, questId_);\n}\n}\nsuper.withdrawRemainingTokens(to_);\n\nuint unclaimedTokens = (receiptRedeemers() - redeemedTokens) * rewardAmountInWeiOrTokenId;\nuint256 nonClaimableTokens = IERC20(rewardToken).balanceOf(address(this)) - protocolFee() - unclaimedTokens;\nIERC20(rewardToken).safeTransfer(to_, nonClaimableTokens);\n}\n\n", "completion": "User may lose rewards if the receipt is minted after quest end time"}
{"prompt": "uint[] memory tokens = rabbitHoleReceiptContract.getOwnedTokenIdsOfQuest(questId, msg.sender);\n\nif (tokens.length == 0) revert NoTokensToClaim();\nuint tokenId = tokenOfOwnerByIndex(claimingAddress_, i);\nif (keccak256(bytes(questIdForTokenId[tokenId])) == keccak256(bytes(questId_))) {\ntokenIdsForQuest[i] = tokenId;\nfoundTokens++;\n}\n}\n\nuint[] memory filteredTokens = new uint[](foundTokens);\nuint filterTokensIndexTracker = 0;\n\nfor (uint i = 0; i < msgSenderBalance; i++) {\nif (tokenIdsForQuest[i] > 0) {\nfilteredTokens[filterTokensIndexTracker] = tokenIdsForQuest[i];\nfilterTokensIndexTracker++;\n}\n}\nreturn filteredTokens;\n", "completion": "DOS risk if enough tokens are minted in Quest.claim can lead, at least, to transaction fee lost"}
{"prompt": "IERC1155(rewardToken).balanceOf(address(this), rewardAmountInWeiOrTokenId),\n'0x00'\n);\n_transferRewards(totalRedeemableRewards);\nredeemedTokens += redeemableTokenCount;\n\nIERC1155(rewardToken).safeTransferFrom(address(this), msg.sender, rewardAmountInWeiOrTokenId, amount_, '0x00');\n}\n\n", "completion": "Users may not claim Erc1155 rewards when the Quest has ended"}
{"prompt": "_transferRewards(totalRedeemableRewards);\nredeemedTokens += redeemableTokenCount;\n\nemit Claimed(msg.sender, totalRedeemableRewards);\n", "completion": "When rewardToken is erc1155/erc777, an attacker can reenter and cause funds to be stuck in the contract forever"}
{"prompt": "IERC20(rewardToken).safeTransfer(protocolFeeRecipient, protocolFee());\n}\n}\nsuper.withdrawRemainingTokens(to_);\n\nuint unclaimedTokens = (receiptRedeemers() - redeemedTokens) * rewardAmountInWeiOrTokenId;\nuint256 nonClaimableTokens = IERC20(rewardToken).balanceOf(address(this)) - protocolFee() - unclaimedTokens;\nIERC20(rewardToken).safeTransfer(to_, nonClaimableTokens);\n}\n\n", "completion": "Funds can be stuck due to wrong order of operations"}
{"prompt": "_setClaimed(tokens);\n_transferRewards(totalRedeemableRewards);\nredeemedTokens += redeemableTokenCount;\n", "completion": "Buyer on secondary NFT market can lose fund if they buy a NFT that is already used to claim the reward"}
{"prompt": "if (quests[questId_].numberMinted + 1 > quests[questId_].totalParticipants) revert OverMaxAllowedToMint();\nif (quests[questId_].addressMinted[msg.sender] == true) revert AddressAlreadyMinted();\nif (keccak256(abi.encodePacked(msg.sender, questId_)) != hash_) revert InvalidHash();\nif (recoverSigner(hash_, signature_) != claimSignerAddress) revert AddressNotSigned();\n\nquests[questId_].addressMinted[msg.sender] = true;\nquests[questId_].numberMinted++;\nemit ReceiptMinted(msg.sender, questId_);\nrabbitholeReceiptContract.mint(msg.sender, questId_);\n}\n}\n", "completion": "Possible scenario for Signature Replay Attack"}
{"prompt": "uint256 long1AmountAdjustFees = FeeCalculation.removeFees(pool.long0Balance, transactionFee);\n\nif ((long1Amount = param.delta) == long1AmountAdjustFees) {\n", "completion": "Rebalance logic is wrong and this distorts the pool\u2019s important states"}
{"prompt": "id = totalSupply() + 1;\n_timeswapV2LiquidityTokenPositions[id] = timeswapV2LiquidityTokenPosition;\n_timeswapV2LiquidityTokenPositionIds[key] = id;\nid = totalSupply() + 1;\n_timeswapV2TokenPositions[id] = timeswapV2TokenPosition;\n_timeswapV2TokenPositionIds[key] = id;\n", "completion": "TimeswapV2LiquidityToken should not use totalSupply()+1 as tokenId"}
{"prompt": "ITimeswapV2Pool(poolPair).transferFees(param.strike, param.maturity, param.to, long0Fees, long1Fees, shortFees);\n\nuint256 id = _timeswapV2LiquidityTokenPositionIds[key];\n", "completion": "The collect() function will always TRANSFER ZERO fees, losing _feesPositions without receiving fees!"}
{"prompt": "if (to == address(0)) {\nif (_idTotalSupply[id] == 0 && _additionalConditionRemoveTokenFromAllTokensEnumeration(id)) _removeTokenFromAllTokensEnumeration(id);\n_idTotalSupply[id] -= amount;\n}\n\nif (from != address(0) && from != to) {\nif (balanceOf(from, id) == 0 && _additionalConditionRemoveTokenFromOwnerEnumeration(from, id)) _removeTokenFromOwnerEnumeration(from, id);\n}\n}\n\n_currentIndex[to] += 1;\nuint256 length = _currentIndex[to];\n_ownedTokens[to][length] = tokenId;\n_ownedTokensIndex[tokenId] = length;\n}\n\nuint256 lastTokenIndex = _currentIndex[from] - 1;\nuint256 tokenIndex = _ownedTokensIndex[tokenId];\n\nif (tokenIndex != lastTokenIndex) {\nuint256 lastTokenId = _ownedTokens[from][lastTokenIndex];\n\n_ownedTokens[from][tokenIndex] = lastTokenId;\n_ownedTokensIndex[lastTokenId] = tokenIndex;\n}\n\ndelete _ownedTokensIndex[tokenId];\ndelete _ownedTokens[from][lastTokenIndex];\n}\n\n", "completion": "_currentIndex is incorrectly updated; breaking the ERC1155 enumerable implementation"}
{"prompt": "for (uint256 i; i < ids.length; ) {\nif (amounts[i] != 0) _removeTokenEnumeration(from, to, ids[i], amounts[i]);\n\nunchecked {\n++i;\n}\n}\n}\n\n/// @dev Remove token enumeration list if necessary.\nfunction _removeTokenEnumeration(address from, address to, uint256 id, uint256 amount) internal {\nif (to == address(0)) {\nif (_idTotalSupply[id] == 0 && _additionalConditionRemoveTokenFromAllTokensEnumeration(id)) _removeTokenFromAllTokensEnumeration(id);\n_idTotalSupply[id] -= amount;\n}\n\nif (from != address(0) && from != to) {\nif (balanceOf(from, id) == 0 && _additionalConditionRemoveTokenFromOwnerEnumeration(from, id)) _removeTokenFromOwnerEnumeration(from, id);\n}\n}\n\n", "completion": "Burning a ERC1155Enumerable token doesn\u2019t remove it from the enumeration"}
{"prompt": "\n// check if the token1 balance target is achieved.\nif (token1AndLong1Amount != 0) Error.checkEnough(IERC20(token1).balanceOf(address(this)), currentProcess.balance1Target);\n\nError.checkEnough(IERC20(param.isLong0ToLong1 ? token1 : token0).balanceOf(address(this)), param.isLong0ToLong1 ? currentProcess.balance1Target : currentProcess.balance0Target);\n\nif (param.isLong0ToLong1) option.long0[msg.sender] -= token0AndLong0Amount;\n", "completion": "Fee on transfer tokens will not behave as expected"}
{"prompt": "if (value == type(uint256).max) return result = type(uint128).max;\nif (value == 0) return 0;\nunchecked {\nuint256 estimate = (value + 1) >> 1;\nresult = value;\nwhile (estimate < result) {\nresult = estimate;\nestimate = (value / estimate + estimate) >> 1;\n}\n}\n\n", "completion": "sqrtDiscriminant can be calculated wrong"}
{"prompt": "function sub512(uint256 minuend0, uint256 minuend1, uint256 subtrahend0, uint256 subtrahend1) internal pure returns (uint256 difference0, uint256 difference1) {\nassembly {\ndifference0 := sub(minuend0, subtrahend0)\n", "completion": "unexpected overflow for FullMath.add512() which can result in irregular behavior"}
{"prompt": "uint256 lastTokenIndex = _currentIndex[from] - 1;\nuint256 tokenIndex = _ownedTokensIndex[tokenId];\n\nif (tokenIndex != lastTokenIndex) {\nuint256 lastTokenId = _ownedTokens[from][lastTokenIndex];\n\n_ownedTokens[from][tokenIndex] = lastTokenId;\n_ownedTokensIndex[lastTokenId] = tokenIndex;\n}\n\ndelete _ownedTokensIndex[tokenId];\ndelete _ownedTokens[from][lastTokenIndex];\n}\n\n", "completion": "_ownedTokensIndex is SHARED by different owners, as a result, _removeTokenFromAllTokensEnumeration might remove the wrong tokenId."}
{"prompt": "LiquidityPosition storage liquidityPosition = pool.liquidityPositions[param.to];\n\nuint256 longAmount;\nliquidityPosition.long0FeeGrowth = long0FeeGrowth;\nliquidityPosition.long1FeeGrowth = long1FeeGrowth;\nliquidityPosition.shortFeeGrowth = shortFeeGrowth;\n", "completion": "Mint function does not update LiquidityPosition state of caller before minting LP tokens. This"}
{"prompt": "// next element of the destination.\nsrcLength.next().offset(headAndTailSize).copy(\ndstLength.next(),\nheadAndTailSize\n);\n\n", "completion": "Incorrect Encoding of Order Hashes"}
{"prompt": "address[] calldata redeemers,\naddress[] calldata refundees,\nuint256 collateralAmountToDist,\nuint256 epochToService,\nuint256 fees\n ) external override updateEpoch onlyRole(MANAGER_ADMIN) {\n_checkAddressesKYC(redeemers);\n_checkAddressesKYC(refundees);\nif (epochToService >= currentEpoch) {\n revert MustServicePastEpoch();\n}\n// Calculate the total quantity of shares tokens burned w/n an epoch\nuint256 refundedAmt = _processRefund(refundees, epochToService);\nuint256 quantityBurned = redemptionInfoPerEpoch[epochToService]\n .totalBurned - refundedAmt;\nuint256 amountToDist = collateralAmountToDist - fees;\n_processRedemption(redeemers, amountToDist, quantityBurned, epochToService);\ncollateral.safeTransferFrom(assetSender, feeRecipient, fees);\nemit RedemptionFeesCollected(feeRecipient, fees, epochToService);\n }\n\n", "completion": "Loss of user funds when completing CASH redemptions"}
{"prompt": " function completeRedemptions(\naddress[] calldata redeemers,\naddress[] calldata refundees,\n", "completion": "Admin should be able to refund or redeem the sanctioned users"}
{"prompt": "uint256 _epochDuration\n ) external onlyRole(MANAGER_ADMIN) {\nuint256 oldEpochDuration = epochDuration;\nepochDuration = _epochDuration;\nemit EpochDurationSet(oldEpochDuration, _epochDuration);\n }\n\n", "completion": "CashManager.setEpochDuration functions has inconsistent output"}
{"prompt": "uint256 kycRequirementGroup,\naddress user,\nuint256 deadline,\nuint8 v,\nbytes32 r,\nbytes32 s\n ) external {\nrequire(v == 27 || v == 28, \"KYCRegistry: invalid v value in signature\");\nrequire(\n !kycState[kycRequirementGroup][user],\n \"KYCRegistry: user already verified\"\n);\nrequire(block.timestamp <= deadline, \"KYCRegistry: signature expired\");\nbytes32 structHash = keccak256(\n abi.encode(_APPROVAL_TYPEHASH, kycRequirementGroup, user, deadline)\n);\n// https://eips.ethereum.org/EIPS/eip-712 compliant\nbytes32 expectedMessage = _hashTypedDataV4(structHash);\n\n// `ECDSA.recover` reverts if signer is address(0)\naddress signer = ECDSA.recover(expectedMessage, v, r, s);\n_checkRole(kycGroupRoles[kycRequirementGroup], signer);\n\nkycState[kycRequirementGroup][user] = true;\n\nemit KYCAddressAddViaSignature(\n msg.sender,\n user,\n signer,\n kycRequirementGroup,\n deadline\n);\n }\n\n", "completion": "KYCRegistry is susceptible to signature replay attack."}
{"prompt": "address user,\nuint256 epoch,\nuint256 balance\n ) external updateEpoch onlyRole(MANAGER_ADMIN) {\nif (epoch > currentEpoch) {\n revert CannotServiceFutureEpoch();\n}\nuint256 previousBalance = redemptionInfoPerEpoch[epoch].addressToBurnAmt[\n user\n];\n// Increment or decrement total burned for the epoch based on whether we\n// are increasing or decreasing the balance.\nif (balance < previousBalance) {\n redemptionInfoPerEpoch[epoch].totalBurned -= previousBalance - balance;\n} else if (balance > previousBalance) {\n redemptionInfoPerEpoch[epoch].totalBurned += balance - previousBalance;\n}\nredemptionInfoPerEpoch[epoch].addressToBurnAmt[user] = balance;\nemit PendingRedemptionBalanceSet(\n user,\n epoch,\n balance,\n redemptionInfoPerEpoch[epoch].totalBurned\n);\n }\n\n", "completion": "setPendingRedemptionBalance() may cause the user\u2019s cash token to be lost"}
{"prompt": "# Ondo Finance Contest Details\n\n- Total Prize Pool: $60,500 USDC\n", "completion": "First Deposit Bug"}
{"prompt": "function init(address _owner, address _entryPointAddress, address _handler) public override initializer { \nrequire(owner == address(0), \"Already initialized\");\nrequire(address(_entryPoint) == address(0), \"Already initialized\");\nfunction execTransaction(\nTransaction memory _tx,\nuint256 batchId,\nsuccess = execute(_tx.to, _tx.value, _tx.data, _tx.operation, refundInfo.gasPrice == 0 ? (gasleft() - 2500) : _tx.targetTxGas);\n// If no targetTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful\n// This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert\nsuccess := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0)\n}\n} else {\n", "completion": "Destruction of the SmartAccount implementation"}
{"prompt": "uint256 startGas = gasleft() + 21000 + msg.data.length * 8;\n//console.log(\"init %s\", 21000 + msg.data.length * 8);\nbytes32 txHash;\npayment = handlePayment(startGas - gasleft(), refundInfo.baseGas, refundInfo.gasPrice, refundInfo.tokenGasPriceFactor, refundInfo.gasToken, refundInfo.refundReceiver);\nemit WalletHandlePayment(txHash, payment);\n}\nuint256 gasUsed,\nuint256 baseGas,\nuint256 gasPrice,\n", "completion": "Theft of funds under relaying the transaction"}
{"prompt": "bytes32 salt = keccak256(abi.encodePacked(_owner, address(uint160(_index))));\nbytes memory deploymentData = abi.encodePacked(type(Proxy).creationCode, uint(uint160(_defaultImpl)));\n// solhint-disable-next-line no-inline-assembly\nassembly {\nproxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)\n}\nrequire(address(proxy) != address(0), \"Create2 call failed\");\n// EOA + Version tracking\nemit SmartAccountCreated(proxy,_defaultImpl,_owner, VERSION, _index);\nBaseSmartAccount(proxy).init(_owner, _entryPoint, _handler);\nisAccountExist[proxy] = true;\n}\n\n", "completion": "Attacker can gain control of counterfactual wallet"}
{"prompt": "require(ISignatureValidator(_signer).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, \"BSA024\");\n}\nelse if(v > 30) {\n", "completion": "Arbitrary transactions possible due to insufficient signature validation"}
{"prompt": "external view override returns (bytes memory context, uint256 deadline) {\n(requiredPreFund);\nbytes32 hash = getHash(userOp);\n\nPaymasterData memory paymasterData = userOp.decodePaymasterData();\nuint256 sigLength = paymasterData.signatureLength;\n\n//ECDSA library supports both 64 and 65-byte long signatures.\n// we only \"require\" it here so that the revert reason on invalid signature will be of \"VerifyingPaymaster\", and not \"ECDSA\"\nrequire(sigLength == 64 || sigLength == 65, \"VerifyingPaymaster: invalid signature length in paymasterAndData\");\nrequire(verifyingSigner == hash.toEthSignedMessageHash().recover(paymasterData.signature), \"VerifyingPaymaster: wrong signature\");\nrequire(requiredPreFund <= paymasterIdBalances[paymasterData.paymasterId], \"Insufficient balance for paymaster id\");\nreturn (userOp.paymasterContext(paymasterData), 0);\n}\n\n", "completion": "Paymaster ETH can be drained with malicious sender"}
{"prompt": "payment = (gasUsed + baseGas) * (gasPrice) / (tokenGasPriceFactor);\nrequire(transferToken(gasToken, receiver, payment), \"BSA012\");\n}\nkeccak256(\nabi.encode(\nACCOUNT_TX_TYPEHASH,\n_tx.to,\n_tx.value,\nkeccak256(_tx.data),\n_tx.operation,\n_tx.targetTxGas,\nrefundInfo.baseGas,\nrefundInfo.gasPrice,\nrefundInfo.gasToken,\nrefundInfo.refundReceiver,\n_nonce\n)\n);\nreturn abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash);\n", "completion": "FeeRefund.tokenGasPriceFactor is not included in signed transaction data allowing the submitter to steal funds"}
{"prompt": "nonces[batchId]\n);\n// Increase nonce and execute transaction.\n", "completion": "Replay attack (EIP712 signed transaction)"}
{"prompt": "function handleOps(UserOperation[] calldata ops, address payable beneficiary) public {\n\nuint256 opslen = ops.length;\nfunction multiSend(bytes memory transactions) public payable {\nrequire(address(this) != multisendSingleton, \"MultiSend should only be called via delegatecall\");\n// solhint-disable-next-line no-inline-assembly\n", "completion": "Griefing attacks on handleOps and multiSend logic"}
{"prompt": "external override virtual returns (uint256 deadline) {\n_requireFromEntryPoint();\ndeadline = _validateSignature(userOp, userOpHash, aggregator);\nif (userOp.initCode.length == 0) {\n_validateAndUpdateNonce(userOp);\n}\n_payPrefund(missingAccountFunds);\n}\n\n// solhint-disable-next-line not-rely-on-time\nif (_deadline != 0 && _deadline < block.timestamp) {\nrevert FailedOp(opIndex, address(0), \"AA22 expired\");\n}\ndeadline = _deadline;\n} catch Error(string memory revertReason) {\nrevert FailedOp(opIndex, address(0), revertReason);\n} catch {\nrevert FailedOp(opIndex, address(0), \"AA23 reverted (or OOG)\");\n}\nif (paymaster == address(0)) {\nexternal override virtual returns (uint256 deadline) {\n_requireFromEntryPoint();\ndeadline = _validateSignature(userOp, userOpHash, aggregator);\nif (userOp.initCode.length == 0) {\n_validateAndUpdateNonce(userOp);\n}\n_payPrefund(missingAccountFunds);\n}\n\n", "completion": "Non-compliance with EIP-4337"}
{"prompt": "public pure returns (bytes32) {\n//can't use userOp.hash(), since it contains also the paymasterAndData itself.\nreturn keccak256(abi.encode(\nuserOp.getSender(),\nuserOp.nonce,\nkeccak256(userOp.initCode),\nkeccak256(userOp.callData),\nuserOp.callGasLimit,\nuserOp.verificationGasLimit,\nuserOp.preVerificationGas,\nuserOp.maxFeePerGas,\nuserOp.maxPriorityFeePerGas\n));\n}\n", "completion": "Cross-Chain Signature Replay Attack"}
{"prompt": "bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b;\n}\n\nfunction isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4);\n}\n\nrequire(ISignatureValidator(_signer).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, \"BSA024\");\n}\nelse if(v > 30) {\n", "completion": "Doesn\u2019t Follow ERC1271 Standard"}
{"prompt": "mapping(address => address) internal modules;\n\nfunction setupModules(address to, bytes memory data) internal {\n", "completion": "SmartAccount.sol is intended to be upgradable but inherits from contracts that contain storage and no gaps"}
{"prompt": "nonces[batchId]++;\ntxHash = keccak256(txHashData);\ncheckSignatures(txHash, txHashData, signatures);\n", "completion": "Transaction can fail due to batchId collision"}
{"prompt": "_requireFromEntryPointOrOwner();\n_call(dest, value, func);\n_requireFromEntryPointOrOwner();\nrequire(dest.length == func.length, \"wrong array lengths\");\n", "completion": "Methods used by EntryPoint has onlyOwner modifier"}
{"prompt": "collateral.addr.safeTransferFrom(address(this), sendTo, collateral.id);\n\nuint256 debt = _vaultInfo[msg.sender][collateral.addr].debt;\n", "completion": "Stealing fund by applying reentrancy attack on removeCollateral, startLiquidationAuction, and purchaseLiquidationAuctionNFT"}
{"prompt": "function onERC721Received(address from, address, uint256 _id, bytes calldata data)\nexternal\noverride\n", "completion": "Collateral NFT deposited to a wrong address, when transferred directly to PaprController"}
{"prompt": "function buyAndReduceDebt(address account, ERC721 collateralAsset, IPaprController.SwapParams calldata params)\nexternal\noverride\nfunction increaseDebtAndSell(\naddress proceedsTo,\nERC721 collateralAsset,\n", "completion": "Missing deadline checks allow pending transactions to be maliciously executed"}
{"prompt": "function setAllowedCollateral(IPaprController.CollateralAllowedConfig[] calldata collateralConfigs)\nexternal\noverride\nfunction increaseDebt(\naddress mintTo,\nERC721 asset,\n", "completion": "Disabled NFT collateral should not be used to mint debt"}
{"prompt": "function _reduceDebtWithoutBurn(address account, ERC721 asset, uint256 amount) internal {\n_vaultInfo[account][asset].debt = uint200(_vaultInfo[account][asset].debt - amount);\nemit ReduceDebt(account, asset, amount);\n", "completion": "Grieving attack by failing user\u2019s transactions"}
{"prompt": "papr.safeTransferFrom(address(this), to, amount);\n}\n\n", "completion": "Incorrect usage of safeTransferFrom traps fees in Papr Controller"}
{"prompt": "underlying.transfer(params.swapFeeTo, amountIn * params.swapFeeBips / BIPS_ONE);\n}\n\n", "completion": "PaprController pays swap fee in buyAndReduceDebt, not user"}
{"prompt": "bool isLastCollateral = collateralValueCached == 0;\n\nuint256 debtCached = _vaultInfo[auction.nftOwner][auction.auctionAssetContract].debt;\n", "completion": "Last collateral check is not safe"}
{"prompt": "if (newDebt > max) revert IPaprController.ExceedsMaxDebt(newDebt, max);\n\nif (newDebt >= 1 << 200) revert IPaprController.DebtAmountExceedsUint200();\nif (info.debt < _maxDebt(oraclePrice * info.count, cachedTarget)) {\nrevert IPaprController.NotLiquidatable();\n}\n", "completion": "Users may be liquidated right after taking maximal debt"}
{"prompt": "payable(msg.sender).call{value: contribution}(\"\");\n\n// Withdraws pending balance of caller if available\npayable(msg.sender).call{value: balance}(\"\");\n}\n\n", "completion": "GroupBuy does not check return value of call"}
{"prompt": "uint256 reservePrice = minReservePrices[_poolId];\nuint256[] memory bidIds = getOwnerToBidIds(_poolId, msg.sender);\nuint256 length = bidIds.length;\n", "completion": "GroupBuy: Lost ETH when the NFT is bought for less than the minimum reserve price"}
{"prompt": "if (pool.success || block.timestamp > pool.terminationPeriod) revert InvalidState();\nreturn (\npool.nftContract,\nif (!pool.success && block.timestamp < pool.terminationPeriod) revert InvalidState();\nreturn (\npool.nftContract,\n", "completion": "Groupbuy:_verifyUnsuccessfulState and _verifySuccessfulState both can return true when block.timestamp == pool.terminationPeriod"}
{"prompt": "pendingBalances[_vault][proposedListing.proposer] += proposedListing.collateral;\n\n// Transfers new collateral amount from caller to this contract\n", "completion": "OptimisticListingSeaport.propose sets pendingBalances of newly added proposer instead of previous one"}
{"prompt": "if (\n_pricePerToken >= proposedListing.pricePerToken ||\n_pricePerToken >= activeListings[_vault].pricePerToken\n) revert NotLower();\n\n", "completion": "Attacker can DOS OptimisticListing with very low cost"}
{"prompt": "vaultOrderHash[_vault] = _getOrderHash(orderParams, counter);\n}\n\n", "completion": "Funds are permanently stuck in OptimisticListingSeaport.sol contract if active proposal is executed after new proposal is pending."}
{"prompt": "pendingBalances[_vault][activeListing.proposer] = collateral;\n}\n// Reverts if token balance is insufficient\npendingBalances[_vault][activeListing.proposer] = activeListing.collateral;\n\n// Calculates new listing price\n", "completion": "User loses collateral converted to pendingBalance when cash() or list() is called"}
{"prompt": "address vault = IMarketBuyer(_market).execute{value: _price}(_purchaseOrder);\n\n// Checks if NFT contract supports ERC165 and interface ID of ERC721 tokens\n", "completion": "Attacker can steal the amount collected so far in the GroupBuy for NFT purchase."}
{"prompt": "\n// Checks if NFT contract supports ERC165 and interface ID of ERC721 tokens\nif (ERC165Checker.supportsInterface(_nftContract, _INTERFACE_ID_ERC721)) {\n// Verifes vault is owner of ERC-721 token\nif (IERC721(_nftContract).ownerOf(_tokenId) != vault) revert UnsuccessfulPurchase();\n} else {\n// Verifies vault is owner of CryptoPunk token\nif (ICryptoPunk(_nftContract).punkIndexToAddress(_tokenId) != vault)\nrevert UnsuccessfulPurchase();\n}\n\n// Stores mapping value of poolId to newly deployed vault\npoolToVault[_poolId] = vault;\n// Sets pool state to successful\npoolInfo[_poolId].success = true;\n\n", "completion": "GroupBuy can be drained of all ETH."}
{"prompt": "// Hashes tokenId to verify merkle root if proof is empty\nif (bytes32(_tokenId) != merkleRoot) revert InvalidProof();\n} else {\n", "completion": "GroupBuy may purchase NFT not in the allowed list"}
{"prompt": "if (proposedListing.collateral < _amount) revert InsufficientCollateral();\n// Reverts if payment amount is incorrect\nif (proposedListing.pricePerToken * _amount != msg.value) revert InvalidPayment();\n", "completion": "Attacker can delay proposal rejection"}
{"prompt": "// Breaks out of while loop if given price is less than than lowest bid price\nif (_price < lowestBid.price) {\nbreak;\n}\n\nuint256 lowestBidQuantity = lowestBid.quantity;\n// Checks if lowest bid quantity amount is greater than given quantity amount\nif (lowestBidQuantity > quantity) {\n// Decrements given quantity amount from lowest bid quantity\nlowestBid.quantity -= quantity;\n// Calculates partial contribution of bid by quantity amount and price\nuint256 contribution = quantity * lowestBid.price;\n\n// Decrements partial contribution amount of lowest bid from total and user contributions\ntotalContributions[_poolId] -= contribution;\nuserContributions[_poolId][lowestBid.owner] -= contribution;\n// Increments pending balance of lowest bid owner\npendingBalances[lowestBid.owner] += contribution;\n\n// Inserts new bid with given quantity amount into proper position of queue\nbidPriorityQueues[_poolId].insert(msg.sender, _price, quantity);\n", "completion": "Priority queue min accounting breaks when nodes are split in two"}
{"prompt": "IERC20(token).approve(conduit, type(uint256).max);\n}\n}\n", "completion": "Orders may not be fillable due to missing approvals"}
{"prompt": "uint256 offerLength = _orders[i].parameters.offer.length;\nfor (uint256 j; j < offerLength; ++j) {\nOfferItem memory offer = _orders[i].parameters.offer[j];\naddress token = offer.token;\nItemType itemType = offer.itemType;\nif (itemType == ItemType.ERC721)\nIERC721(token).setApprovalForAll(conduit, true);\nif (itemType == ItemType.ERC1155)\nIERC1155(token).setApprovalForAll(conduit, true);\nif (itemType == ItemType.ERC20)\nIERC20(token).approve(conduit, type(uint256).max);\n}\n}\n}\n// Validates the order on-chain so no signature is required to fill it\nassert(ConsiderationInterface(_consideration).validate(_orders));\n}\n\n", "completion": "Only one GroupBuy can ever use USDT or similar tokens with front-running approval protections"}
{"prompt": "_sendEthOrWeth(proposer, msg.value);\n\n// Emits event for rejecting an active listing\n", "completion": "Loss of ETH for proposer when it is a contract that doesn\u2019t have fallback function."}
{"prompt": "if (_price < lowestBid.price) {\nbreak;\n}\n", "completion": "Earlier bidders get cut out of future NFT holdings by bidders specifying the same price."}
{"prompt": "minBidPrices[currentId] = _initialPrice / _totalSupply;\n\n// Initializes first bid in queue\n", "completion": "GroupBuys that are completely filled still don\u2019t raise stated target amount"}
{"prompt": "staking.increaseAVAXAssignedHighWater(owner, avaxLiquidStakerAmt);\n}\n\n", "completion": "AVAX Assigned High Water is updated incorrectly"}
{"prompt": "Vault vault = Vault(getContractAddress(\"Vault\"));\ndecreaseGGPStake(stakerAddr, ggpAmt);\nvault.transferToken(\"ProtocolDAO\", ggp, ggpAmt);\n}\n\n", "completion": "ProtocolDAO lacks a method to take out GGP"}
{"prompt": "uint256 avaxLiquidStakerAmt = getUint(keccak256(abi.encodePacked(\"minipool.item\", index, \".avaxLiquidStakerAmt\")));\nuint256 expectedAVAXRewardsAmt = getExpectedAVAXRewardsAmt(duration, avaxLiquidStakerAmt);\nuint256 slashGGPAmt = calculateGGPSlashAmt(expectedAVAXRewardsAmt);\n", "completion": "Node operator is getting slashed for full duration even though rewards are distributed based on a 14 day cycle"}
{"prompt": "requireValidStateTransition(minipoolIndex, MinipoolStatus.Prelaunch);\nresetMinipoolData(minipoolIndex);\n// Also reset initialStartTime as we are starting a whole new validation\n", "completion": "Hijacking of node operators minipool causes loss of staked funds"}
{"prompt": "return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n}\n\n", "completion": "Inflation of ggAVAX share price by first depositor"}
{"prompt": "address newAddr,\nstring memory newName,\naddress existingAddr\n) external onlyGuardian {\nregisterContract(newAddr, newName);\nunregisterContract(existingAddr);\n}\n}\n", "completion": "Coding logic of the contract upgrading renders upgrading contracts impractical"}
{"prompt": "function recordStakingError(address nodeID, bytes32 errorCode) external payable {\nint256 minipoolIndex = onlyValidMultisig(nodeID);\nrequireValidStateTransition(minipoolIndex, MinipoolStatus.Error);\nfunction finishFailedMinipoolByMultisig(address nodeID) external {\nint256 minipoolIndex = onlyValidMultisig(nodeID);\nrequireValidStateTransition(minipoolIndex, MinipoolStatus.Finished);\nfunction withdrawMinipoolFunds(address nodeID) external nonReentrant {\nint256 minipoolIndex = requireValidMinipool(nodeID);\naddress owner = onlyOwner(minipoolIndex);\n", "completion": "NodeOp funds may be trapped by a invalid state transition"}
{"prompt": "uint256 total = getUint(keccak256(\"multisig.count\"));\naddress addr;\nbool enabled;\nfor (uint256 i = 0; i < total; i++) {\n(addr, enabled) = getMultisig(i);\nif (enabled) {\nreturn addr;\n}\n}\nrevert NoEnabledMultisigFound();\n}\n\n", "completion": "requireNextActiveMultisig will always return the first enabled multisig which increases the probability of stuck minipools"}
{"prompt": "addUint(keccak256(\"RewardsPool.InflationIntervalStartTime\"), inflationIntervalElapsedSeconds);\nsetUint(keccak256(\"RewardsPool.RewardsCycleTotalAmt\"), newTokens);\n}\n", "completion": "Inflation rate can be reduced by half at most if it gets called every 1.99 interval"}
{"prompt": "owner.safeTransferETH(avaxNodeOpAmt);\n}\n\n", "completion": "Rialto may not be able to cancel minipools created by contracts that cannot receive AVAX"}
{"prompt": "uint256 compoundedAvaxNodeOpAmt = mp.avaxNodeOpAmt + mp.avaxNodeOpRewardAmt;\nsetUint(keccak256(abi.encodePacked(\"minipool.item\", minipoolIndex, \".avaxNodeOpAmt\")), compoundedAvaxNodeOpAmt);\nsetUint(keccak256(abi.encodePacked(\"minipool.item\", minipoolIndex, \".avaxLiquidStakerAmt\")), compoundedAvaxNodeOpAmt);\n", "completion": "Recreated pools receive a wrong AVAX amount due to miscalculated compounded liquid staker amount"}
{"prompt": "function recreateMinipool(address nodeID) external whenNotPaused {\nint256 minipoolIndex = onlyValidMultisig(nodeID);\nrequireValidStateTransition(minipoolIndex, MinipoolStatus.Prelaunch);\n", "completion": "State Transition: Minipools can be created using other operator\u2019s AVAX deposit via recreateMinipool"}
{"prompt": "staking.setRewardsStartTime(msg.sender, block.timestamp);\n}\n\nrevert CancellationTooEarly();\n}\n_cancelMinipoolAndReturnFunds(nodeID, index);\n", "completion": "Cancellation of minipool may skip MinipoolCancelMoratoriumSeconds checking if it was cancelled before"}
{"prompt": "Vault vault = Vault(getContractAddress(\"Vault\"));\ndecreaseGGPStake(stakerAddr, ggpAmt);\nvault.transferToken(\"ProtocolDAO\", ggp, ggpAmt);\n}\n\n", "completion": "Slashing fails when node operator doesn\u2019t have enough staked GGP"}
{"prompt": "function maxRedeem(address _owner) public view override returns (uint256) {\nif (getBool(keccak256(abi.encodePacked(\"contract.paused\", \"TokenggAVAX\")))) {\nreturn 0;\n}\nuint256 shares = balanceOf[_owner];\nuint256 avail = convertToShares(totalAssets() - stakingTotalAssets);\nreturn shares > avail ? avail : shares;\n}\n\nfunction maxWithdraw(address _owner) public view override returns (uint256) {\nif (getBool(keccak256(abi.encodePacked(\"contract.paused\", \"TokenggAVAX\")))) {\nreturn 0;\n}\nuint256 assets = convertToAssets(balanceOf[_owner]);\nuint256 avail = totalAssets() - stakingTotalAssets;\nreturn assets > avail ? avail : assets;\n}\n\n", "completion": "maxWithdraw() and maxRedeem() doesn\u2019t return correct value which can make other contracts fail while working with protocol"}
{"prompt": "function recordStakingError(address nodeID, bytes32 errorCode) external payable {\nint256 minipoolIndex = onlyValidMultisig(nodeID);\nrequireValidStateTransition(minipoolIndex, MinipoolStatus.Error);\nfunction calculateAndDistributeRewards(address stakerAddr, uint256 totalEligibleGGPStaked) external onlyMultisig {\nStaking staking = Staking(getContractAddress(\"Staking\"));\nstaking.requireValidStaker(stakerAddr);\nfunction claimAndRestake(uint256 claimAmt) external {\nStaking staking = Staking(getContractAddress(\"Staking\"));\nuint256 ggpRewards = staking.getGGPRewards(msg.sender);\n", "completion": "NodeOp can get rewards even if there was an error in registering the node as a validator"}
{"prompt": "function redeemAVAX(uint256 shares) public returns (uint256 assets) {\n// Check for rounding error since we round down in previewRedeem.\nif ((assets = previewRedeem(shares)) == 0) {\nfunction syncRewards() public {\nuint32 timestamp = block.timestamp.safeCastTo32();\n\n", "completion": "Users may not be able to redeem their shares due to underflow"}
{"prompt": "return type(uint256).max;\n}\n\nfunction maxMint(address) public view virtual returns (uint256) {\nreturn type(uint256).max;\n}\n\n", "completion": "TokenggAVAX: maxDeposit and maxMint return wrong value when contract is paused"}
{"prompt": "uint256 tokensPerMultisig = allotment / enabledCount;\nfor (uint256 i = 0; i < enabledMultisigs.length; i++) {\nvault.withdrawToken(enabledMultisigs[i], ggp, tokensPerMultisig);\nfunction startRewardsCycle() external {\nif (!canStartRewardsCycle()) {\nrevert UnableToStartRewardsCycle();\n", "completion": "Division by zero error can block RewardsPool#startRewardCycle if all multisig wallet are disabled"}
{"prompt": "return (avaxAmt.mulWadDown(rate) * duration) / 365 days;\n}\n\nuint256 slashGGPAmt = calculateGGPSlashAmt(expectedAVAXRewardsAmt);\nsetUint(keccak256(abi.encodePacked(\"minipool.item\", index, \".ggpSlashAmt\")), slashGGPAmt);\n\n", "completion": "Inaccurate estimation of validation rewards from function ExpectedRewardAVA in MiniPoolManager.sol"}
{"prompt": "revert MultisigLimitReached();\n}\n\n", "completion": "MultisigManager may not be able to add a valid Multisig"}
{"prompt": "// If recoverTimelock is not setup, or if not yet occurred\nif (settings.recoverTimelock > block.timestamp) {\n// Stop the withdraw\nrevert RECOVERY_IS_NOT_YET_POSSIBLE();\n}\n\n// Send event for indexing that the owner reclaimed the NFT\nemit OwnerReclaimedNFT(owner());\n\n// Transfer token to the admin/owner.\nIERC721EnumerableUpgradeable(settings.token).transferFrom(\naddress(this),\nowner(),\nsettings.tokenId\n);\n}\n}\n", "completion": "Admin does not have to wait to call lastResortTimelockOwnerClaimNFT()"}
{"prompt": "if (_settings.drawBufferTime < HOUR_IN_SECONDS) {\nrevert REDRAW_TIMELOCK_NEEDS_TO_BE_MORE_THAN_AN_HOUR();\n}\n", "completion": "Draw organizer can rig the draw to favor certain participants such as their own account."}
{"prompt": "function startDraw() external onlyOwner returns (uint256) {\n// Only can be called on first drawing\nif (request.currentChainlinkRequestId != 0) {\nfunction lastResortTimelockOwnerClaimNFT() external onlyOwner {\n// If recoverTimelock is not setup, or if not yet occurred\nif (settings.recoverTimelock > block.timestamp) {\nIERC721EnumerableUpgradeable(_settings.token).ownerOf(\n_settings.tokenId\n)\n", "completion": "Raffle creator might not start raffle draw"}
{"prompt": "function startDraw() external onlyOwner returns (uint256) {\n// Only can be called on first drawing\nif (request.currentChainlinkRequestId != 0) {\nkeyHash: settings.keyHash,\nsubId: settings.subscriptionId,\nminimumRequestConfirmations: minimumRequestConfirmations,\ncallbackGasLimit: callbackGasLimit,\nnumWords: wordsRequested\n});\n}\n", "completion": "VRFNFTRandomDraw admin can prevent created or started raffle from taking place"}
{"prompt": "uint256 immutable MONTH_IN_SECONDS = (3600 * 24 * 7) * 30;\n\n\n", "completion": "Protocol safeguards for time durations are skewed by a factor of 7. Protocol may potentially lock NFT for period of 7 years."}
{"prompt": "ERC20(baseToken).safeTransferFrom(msg.sender, address(this), baseTokenAmount);\n}\n\nERC20(baseToken).safeTransfer(msg.sender, baseTokenOutputAmount);\n}\n\nERC20(baseToken).safeTransferFrom(msg.sender, address(this), inputAmount);\n}\n\nERC20(baseToken).safeTransfer(msg.sender, outputAmount);\n}\n\n", "completion": "Reentrancy in buy function for ERC777 tokens allows buying funds with considerable discount"}
{"prompt": "uint256 fractionalTokenShare = (fractionalTokenAmount * lpTokenSupply) / fractionalTokenReserves();\nreturn Math.min(baseTokenShare, fractionalTokenShare);\n} else {\n", "completion": "Liquidity providers may lose funds when adding liquidity"}
{"prompt": "function add(uint256 baseTokenAmount, uint256 fractionalTokenAmount, uint256 minLpTokenAmount)\npublic\npayable\n", "completion": "First depositor can break minting of shares"}
{"prompt": "/// @dev Calculated by dividing the base token reserves by the fractional token reserves.\n/// @return price The price of one fractional token in base tokens * 1e18.\nfunction price() public view returns (uint256) {\nreturn (_baseTokenReserves() * ONE) / fractionalTokenReserves();\n}\n\n", "completion": "Price will not always be 18 decimals, as expected and outlined in the comments"}
{"prompt": "return (outputAmount * 1000 * baseTokenReserves()) / ((fractionalTokenReserves() - outputAmount) * 997);\n}\n\n", "completion": "Rounding error in buyQuote might result in free tokens"}
{"prompt": "return (_baseTokenReserves() * ONE) / fractionalTokenReserves();\n}\n\n: ERC20(baseToken).balanceOf(address(this));\n}\nreturn balanceOf[address(this)];\n}\n\n", "completion": "Pair price may be manipulated by direct transfers"}
{"prompt": " lastUserPeriodReset = block.timestamp;\n userToAmountWithdrawnThisPeriod[_sender] = _amountBeforeFee;\n} else {\n require(userToAmountWithdrawnThisPeriod[_sender] + _amountBeforeFee <= userWithdrawLimitPerPeriod, \"user withdraw limit exceeded\");\n userToAmountWithdrawnThisPeriod[_sender] += _amountBeforeFee;\n}\ndepositRecord.recordWithdrawal(_amountBeforeFee);\n", "completion": "griefing / blocking / delaying users to withdraw"}
{"prompt": " globalAmountWithdrawnThisPeriod = _amountBeforeFee;\n} else {\n require(globalAmountWithdrawnThisPeriod + _amountBeforeFee <= globalWithdrawLimitPerPeriod, \"global withdraw limit exceeded\");\n userToAmountWithdrawnThisPeriod[_sender] = _amountBeforeFee;\n} else {\n require(userToAmountWithdrawnThisPeriod[_sender] + _amountBeforeFee <= userWithdrawLimitPerPeriod, \"user withdraw limit exceeded\");\n", "completion": "A whale user is able to cause freeze of funds of other users by bypassing withdraw limit"}
{"prompt": " require(userToAmountWithdrawnThisPeriod[_sender] + _amountBeforeFee <= userWithdrawLimitPerPeriod, \"user withdraw limit exceeded\");\n userToAmountWithdrawnThisPeriod[_sender] += _amountBeforeFee;\n}\n", "completion": "Bypass userWithdrawLimitPerPeriod check"}
{"prompt": "if (address(_mintHook) != address(0)) _mintHook.hook(msg.sender, _amount, _amount);\ncollateral.transferFrom(msg.sender, address(this), _amount);\nlongToken.mint(msg.sender, _amount);\n function setMintHook(IMarketHook mintHook) external override onlyOwner {\n_mintHook = mintHook;\nemit MintHookChange(address(mintHook));\n", "completion": "Frontrunning for unallowed minting of Short and Long tokens"}
{"prompt": " function setFinalLongPayout(uint256 _finalLongPayout) external override onlyOwner {\nrequire(_finalLongPayout >= floorLongPayout, \"Payout cannot be below floor\");\nrequire(_finalLongPayout <= ceilingLongPayout, \"Payout cannot exceed ceiling\");\n", "completion": "PrePOMarket.setFinalLongPayout() shouldn\u2019t be called twice."}
{"prompt": "if (outputAmount > _outputToken.balanceOf(address(this))) return;\n_outputToken.transfer(recipient, outputAmount);\n }\n", "completion": "Users do not receive owed tokens if TokenSender contract cannot cover their owed amount."}
{"prompt": "_checkDelay(_id, false);\n(uint _limitPrice, address _tigAsset) = tradingExtension._limitClose(_id, _tp, _priceData, _signature);\n_closePosition(_id, DIVISION_CONSTANT, _limitPrice, address(0), _tigAsset, true);\n", "completion": "Riskless trades due to delay check"}
{"prompt": "_payout = int256(_margin) - int256(_initPositionSize * (1e18 * _currentPrice / _price - 1e18)/1e18) + accInterest;\n}\n_positionSize = _initPositionSize * _currentPrice / _price;\n", "completion": "Certain fee configuration enables vaults to be drained"}
{"prompt": "_checkOwner(_id, _trader);\n_checkDelay(_id, true);\nIPosition.Trade memory _trade = position.trades(_id);\n", "completion": "Bypass the maximum PnL check to take extra profit"}
{"prompt": "uint _newPrice = _trade.price*_trade.margin/_newMargin + _price*_addMargin/_newMargin;\n\nposition.addToPosition(\n", "completion": "Incorrect calculation of new price while adding position"}
{"prompt": "* @notice deposit an allowed token and receive tigAsset\n* @param _token address of the allowed token\n* @param _amount amount of _token\n*/\nfunction deposit(address _token, uint256 _amount) public {\nrequire(allowed[_token], \"Token not listed\");\nIERC20(_token).transferFrom(_msgSender(), address(this), _amount);\nIERC20Mintable(stable).mintFor(\n_msgSender(),\n_amount*(10**(18-IERC20Mintable(_token).decimals()))\n);\n}\n\n* @notice swap tigAsset to _token\n* @param _token address of the token to receive\n* @param _amount amount of _token\n*/\nfunction withdraw(address _token, uint256 _amount) external returns (uint256 _output) {\nIERC20Mintable(stable).burnFrom(_msgSender(), _amount);\n_output = _amount/10**(18-IERC20Mintable(_token).decimals());\nIERC20(_token).transfer(\n_msgSender(),\n_output\n);\n}\n\n", "completion": "Incorrect Assumption of Stablecoin Market Stability"}
{"prompt": "uint _id,\nbool _tp,\nPriceData calldata _priceData,\nbytes calldata _signature\n) external view returns(uint _limitPrice, address _tigAsset) {\n_checkGas();\nIPosition.Trade memory _trade = position.trades(_id);\n_tigAsset = _trade.tigAsset;\n\ngetVerifiedPrice(_trade.asset, _priceData, _signature, 0);\nuint256 _price = _priceData.price;\n\nif (_trade.orderType != 0) revert(\"4\"); //IsLimit\n\nif (_tp) {\nif (_trade.tpPrice == 0) revert(\"7\"); //LimitNotSet\nif (_trade.direction) {\nif (_trade.tpPrice > _price) revert(\"6\"); //LimitNotMet\n} else {\nif (_trade.tpPrice < _price) revert(\"6\"); //LimitNotMet\n}\n_limitPrice = _trade.tpPrice;\n} else {\nif (_trade.slPrice == 0) revert(\"7\"); //LimitNotSet\nif (_trade.direction) {\nif (_trade.slPrice < _price) revert(\"6\"); //LimitNotMet\n} else {\nif (_trade.slPrice > _price) revert(\"6\"); //LimitNotMet\n}\n_limitPrice = _trade.slPrice;\n}\n}\n\n", "completion": "User can abuse tight stop losses and high leverage to make risk free trades"}
{"prompt": "_trade.tigAsset,\n_marginAsset,\n_addMargin - _fee,\n_stableVault,\n_permitData,\n_trader\n);\nposition.setAccInterest(_id);\n", "completion": "Not enough margin pulled or burned from user when adding to a position"}
{"prompt": "IERC20(assets[i]).approve(address(bondNFT), type(uint256).max);\nbondNFT.distribute(assets[i], balanceAfter - balanceBefore);\n}\n", "completion": "Must approve 0 first"}
{"prompt": "unchecked {\nDelay memory _delay = blockDelayPassed[_id];\nif (_delay.actionType == _type) {\nblockDelayPassed[_id].delay = block.number + blockDelay;\n} else {\nif (block.number < _delay.delay) revert(\"0\"); //Wait\nblockDelayPassed[_id].delay = block.number + blockDelay;\nblockDelayPassed[_id].actionType = _type;\n}\n}\n}\n\n", "completion": "Bypass the delay security check to win risk free funds"}
{"prompt": "_checkOwner(_id, _trader);\n_checkVault(_stableVault, _outputToken);\nIPosition.Trade memory _trade = position.trades(_id);\nif (position.ownerOf(_id) != _trader) revert(\"2\"); //NotPositionOwner \n}\n\n", "completion": "Approved operators of Position token can\u2019t call Trading.initiateCloseOrder"}
{"prompt": "function lzReceive(\nuint16 _srcChainId,\nbytes memory _srcAddress,\n", "completion": "Failure in endpoint can cause minting more than one NFT with the same token id in different chains"}
{"prompt": "ILayerZeroEndpoint public endpoint;\n\n", "completion": "GovNFT: maxBridge has no effect"}
{"prompt": "uint256 _marginAfterFees = _tradeInfo.margin - _handleOpenFees(_tradeInfo.asset, _tradeInfo.margin*_tradeInfo.leverage/1e18, _trader, _tigAsset, false);\nuint256 _positionSize = _marginAfterFees * _tradeInfo.leverage / 1e18;\n_handleDeposit(_tigAsset, _tradeInfo.marginAsset, _tradeInfo.margin, _tradeInfo.stableVault, _permitData, _trader);\n_feePaid =\n_positionSize\n* (_fees.burnFees + _fees.botFees) // get total fee%\n", "completion": "_handleOpenFees returns an incorrect value for _feePaid. This directly impacts margin calculations"}
{"prompt": "uint _id,\nuint _percent,\nPriceData calldata _priceData,\nbytes calldata _signature,\naddress _stableVault,\naddress _outputToken,\naddress _trader\n)\nexternal\nrequire(!allowed[_token], \"Already added\");\ntokenIndex[_token] = tokens.length;\ntokens.push(_token);\nallowed[_token] = true;\n}\n\naddress _address,\nbool _status\n) \npublic\nonlyOwner()\n{\nisMinter[_address] = _status;\n}\n\nfunction addAsset(uint256 _asset, string memory _name, address _chainlinkFeed, uint256 _minLeverage, uint256 _maxLeverage, uint256 _feeMultiplier, uint256 _baseFundingRate) external onlyOwner {\nbytes memory _assetName = bytes(_idToAsset[_asset].name);\nrequire(_assetName.length == 0, \"Already exists\");\n", "completion": "Centralization risks: owner can freeze withdraws and use timelock to steal all funds"}
{"prompt": "require(_referral[_hash] == address(0), \"Referral code already exists\");\n_referral[_hash] = _msgSender();\nemit ReferralCreated(_msgSender(), _hash);\n}\n\naddress _trader\n) external view returns(address) {\nreturn referrals.getReferral(referrals.getReferred(_trader));\n}\n\n", "completion": "One can become referral of hash 0x0 and because all users default referral hash is 0x0 so he would become all users referral by default and earn a lot of fees while users didn\u2019t approve it"}
{"prompt": "unchecked {\nDelay memory _delay = blockDelayPassed[_id];\nif (_delay.actionType == _type) {\nblockDelayPassed[_id].delay = block.number + blockDelay;\n} else {\nif (block.number < _delay.delay) revert(\"0\"); //Wait\nblockDelayPassed[_id].delay = block.number + blockDelay;\nblockDelayPassed[_id].actionType = _type;\n}\n}\n}\n\n", "completion": "_checkDelay will not work properly for Arbitrum or Optimism due to block.number"}
{"prompt": "uint _id,\nbool _tp,\nPriceData calldata _priceData,\nbytes calldata _signature\n)\nexternal\n{\n_checkDelay(_id, false);\n(uint _limitPrice, address _tigAsset) = tradingExtension._limitClose(_id, _tp, _priceData, _signature);\n_closePosition(_id, DIVISION_CONSTANT, _limitPrice, address(0), _tigAsset, true);\n}\n\n", "completion": "User can close an order via limitClose(), and take bot fees to themselves"}
{"prompt": "trade.price = _price;\n} \nif(trade.direction) {\n", "completion": "StopLoss/TakeProfit should be validated again for the new price in Trading.executeLimitOrder()"}
{"prompt": "totalShares[bond.asset] -= bond.shares;\n(uint256 _claimAmount,) = claim(_id, bond.owner);\namount += _claimAmount;\naccRewardsPerShare[_tigAsset][aEpoch] += _amount * 1e18 / totalShares[_tigAsset];\n}\nemit Distribution(_tigAsset, _amount);\n", "completion": "Unreleased locks cause the reward distribution to be flawed in BondNFT"}
{"prompt": "require(_accountList.isIncluded(sender), \"redeemer not allowed\");\nuint256 fee = amountBeforeFee - amountAfterFee;\nif (fee > 0) {\n", "completion": "PrePO NFT holders will not be able to redeem collateral"}
{"prompt": "contract Lock is Ownable{\n\nuint public constant minPeriod = 7;\naddress _asset,\nuint _amount,\nuint _period\n) public {\nrequire(_period <= maxPeriod, \"MAX PERIOD\");\nrequire(_period >= minPeriod, \"MIN PERIOD\");\nrequire(allowedAssets[_asset], \"!asset\");\n\nclaimGovFees();\n\nIERC20(_asset).transferFrom(msg.sender, address(this), _amount);\ntotalLocked[_asset] += _amount;\n\nbondNFT.createLock( _asset, _amount, _period, msg.sender);\n}\n\nuint _id,\nuint _amount,\nuint _period\n) public {\naddress _asset = claim(_id);\nIERC20(_asset).transferFrom(msg.sender, address(this), _amount);\nbondNFT.extendLock(_id, _asset, _amount, _period, msg.sender);\n}\n\nuint _id\n) public {\nclaimGovFees();\n(uint amount, uint lockAmount, address asset, address _owner) = bondNFT.release(_id, msg.sender);\ntotalLocked[asset] -= lockAmount;\nIERC20(asset).transfer(_owner, amount);\n}\n\n", "completion": "Lock.sol: assets deposited with Lock.extendLock function are lost"}
{"prompt": "uint _id,\naddress _claimer\n) public onlyManager() returns(uint amount, address tigAsset) {\nBond memory bond = idToBond(_id);\nrequire(_claimer == bond.owner, \"!owner\");\namount = bond.pending;\ntigAsset = bond.asset;\nunchecked {\nif (bond.expired) {\nuint _pendingDelta = (bond.shares * accRewardsPerShare[bond.asset][epoch[bond.asset]] / 1e18 - bondPaid[_id][bond.asset]) - (bond.shares * accRewardsPerShare[bond.asset][bond.expireEpoch-1] / 1e18 - bondPaid[_id][bond.asset]);\nif (totalShares[bond.asset] > 0) {\naccRewardsPerShare[bond.asset][epoch[bond.asset]] += _pendingDelta*1e18/totalShares[bond.asset];\n}\n}\nbondPaid[_id][bond.asset] += amount;\n}\nIERC20(tigAsset).transfer(manager, amount);\nemit ClaimFees(tigAsset, amount, _claimer, _id);\n}\n\n", "completion": "Malicious user can steal all assets in BondNFT"}
{"prompt": "_toMint = _trade.margin*maxWinPercent/DIVISION_CONSTANT;\n}\n}\n", "completion": "Users can bypass the maxWinPercent limit using a partially closing"}
{"prompt": "function claimGovFees() public {\naddress[] memory assets = bondNFT.getAssets();\n\nif (totalShares[_tigAsset] == 0 || !allowedAsset[_tigAsset]) return;\nIERC20(_tigAsset).transferFrom(_msgSender(), address(this), _amount);\nunchecked {\n", "completion": "Lock.sol: claimGovFees function can cause assets to be stuck in the Lock contract"}
{"prompt": "require(epoch[bond.asset] == block.timestamp/DAY, \"Bad epoch\");\nrequire(!bond.expired, \"Expired!\");\nunchecked {\n", "completion": "BondNFTs can revert when transferred"}
{"prompt": "IERC20(_marginAsset).approve(_stableVault, type(uint).max);\nIStableVault(_stableVault).deposit(_marginAsset, _margin/_marginDecMultiplier);\nif (tigAsset.balanceOf(address(this)) != _balBefore + _margin) revert BadDeposit();\n", "completion": "Trading will not work on Ethereum if USDT is used"}
{"prompt": "uint _pendingDelta = (bond.shares * accRewardsPerShare[bond.asset][epoch[bond.asset]] / 1e18 - bondPaid[_id][bond.asset]) - (bond.shares * accRewardsPerShare[bond.asset][bond.expireEpoch-1] / 1e18 - bondPaid[_id][bond.asset]);\nif (totalShares[bond.asset] > 0) {\naccRewardsPerShare[bond.asset][epoch[bond.asset]] += _pendingDelta*1e18/totalShares[bond.asset];\n}\n}\nbondPaid[_id][bond.asset] += amount;\n}\nbond = _idToBond[_id];\nbond.owner = ownerOf(_id);\nbond.expired = bond.expireEpoch <= epoch[bond.asset] ? true : false;\nunchecked {\nuint _accRewardsPerShare = accRewardsPerShare[bond.asset][bond.expired ? bond.expireEpoch-1 : epoch[bond.asset]];\nbond.pending = bond.shares * _accRewardsPerShare / 1e18 - bondPaid[_id][bond.asset];\n}\n}\n", "completion": "BondNFT.sol#claim() needs to correct all the missing epochs"}
{"prompt": "uint _marginDecMultiplier = 10**(18-ExtendedIERC20(_marginAsset).decimals());\nIERC20(_marginAsset).transferFrom(_trader, address(this), _margin/_marginDecMultiplier);\nIERC20(_marginAsset).approve(_stableVault, type(uint).max);\nif (IERC20(_outputToken).balanceOf(address(this)) != _balBefore + _toMint/(10**(18-ExtendedIERC20(_outputToken).decimals()))) revert BadWithdraw();\nIERC20(_outputToken).transfer(_trade.trader, IERC20(_outputToken).balanceOf(address(this)) - _balBefore);\n}\n", "completion": "_handleDeposit and _handleWithdraw do not account for tokens with decimals higher than 18"}
{"prompt": "uint256 _positionSize = _marginAfterFees * _tradeInfo.leverage / 1e18;\n_handleDeposit(_tigAsset, _tradeInfo.marginAsset, _tradeInfo.margin, _tradeInfo.stableVault, _permitData, _trader);\n_positionSize\n* (_fees.burnFees + _fees.botFees) // get total fee%\n/ DIVISION_CONSTANT // divide by 100%\n+ _daoFeesPaid;\nemit FeesDistributed(\n", "completion": "Trading#initiateMarketOrder allows to open a position with more margin than expected due to _handleOpenFees wrong calculation when a trade is referred"}
{"prompt": "tradingExtension.modifyLongOi(trade.asset, trade.tigAsset, true, trade.margin*trade.leverage/1e18);\n} else {\ntradingExtension.modifyShortOi(trade.asset, trade.tigAsset, true, trade.margin*trade.leverage/1e18);\n}\n_updateFunding(trade.asset, trade.tigAsset);\n", "completion": "executeLimitOrder() modifies open-interest with a wrong position value"}
{"prompt": "_transfer(_msgSender(), _to, _ids[i]);\n}\n}\n_transfer(_msgSender(), _to, _ids[i]);\n}\n}\n", "completion": "safeTransferMany() doesn\u2019t actually use safe transfer"}
{"prompt": "selfdestruct(_sale.saleReceiver);\n}\n}\nselfdestruct(_sale.saleReceiver);\n}\n}\n", "completion": "selfdestruct may cause the funds to be lost"}
{"prompt": "Sale memory temp = sale;\n(uint256 start, uint256 end) = (temp.startTime, temp.endTime);\nif (block.timestamp < start) return type(uint256).max;\nif (temp.currentId == temp.finalId) return temp.finalPrice;\n\nuint256 timeElapsed = end > block.timestamp ? block.timestamp - start : end - start;\nreturn temp.startPrice - (temp.dropPerSecond * timeElapsed);\n}\n", "completion": "LPDA price can underflow the price due to bad settings and potentially brick the contract"}
{"prompt": "require(newId <= temp.finalId, \"TOO MANY\");\n\nsale.finalPrice = uint80(price);\nuint256 totalSale = price * amountSold;\nuint256 fee = totalSale / 20;\nISaleFactory(factory).feeReceiver().transfer(fee);\ntemp.saleReceiver.transfer(totalSale - fee);\n_end();\n}\n}\n", "completion": "saleReceiver and feeReceiver can steal refunds after sale has ended"}
{"prompt": "require(amount * sale.price == msg.value, \"WRONG PRICE\");\nuint24 newId = amount + temp.currentId;\n\n", "completion": "OpenEdition.buy() might revert due to uint overflow when it should work."}
{"prompt": "ISaleFactory(factory).feeReceiver().transfer(address(this).balance / 20);\nselfdestruct(_sale.saleReceiver);\n}\n", "completion": "Inconsistency in fees"}
{"prompt": "require(newId <= temp.finalId, \"TOO MANY\");\n\nreceipts[msg.sender].amount += amount;\n", "completion": "buy() in LPDA.sol Can be Manipulated by Buyers"}
{"prompt": "if (newId == sale_.finalId) _end(sale);\n}\n\nsale.finalPrice = uint80(price);\nuint256 totalSale = price * amountSold;\nuint256 fee = totalSale / 20;\nISaleFactory(factory).feeReceiver().transfer(fee);\ntemp.saleReceiver.transfer(totalSale - fee);\n_end();\n}\n}\n", "completion": "ETH will get stuck if all NFTs do not get sold."}
{"prompt": "receipts[msg.sender].balance += uint80(msg.value);\n\nfor (uint256 x = temp.currentId + 1; x <= newId; x++) {\nsale.finalPrice = uint80(price);\nuint256 totalSale = price * amountSold;\nuint256 fee = totalSale / 20;\nuint80 price = uint80(getPrice()) * r.amount;\nuint80 owed = r.balance - price;\nrequire(owed > 0, \"NOTHING TO REFUND\");\nuint48 newId = uint48(_amount) + sale_.currentId;\nrequire(newId <= sale_.finalId, \"TOO MANY\");\n\n", "completion": "Unsafe downcasting operation truncate user\u2019s input"}
{"prompt": "selfdestruct(_sale.saleReceiver);\n}\n}\nselfdestruct(_sale.saleReceiver);\n}\n}\n", "completion": "selfdestruct() will not be available after EIP-4758"}
{"prompt": "nft.mint(msg.sender, x);\n}\n\nnft.mint(msg.sender, x);\n}\nsale.currentId = newId;\nnft.mint(msg.sender, x);\n}\n\n", "completion": "Sale contracts can be bricked if any other minter mints a token with an id that overlaps the sale"}
{"prompt": "function cancel() external onlyOwner {\nrequire(block.timestamp < sale.startTime, \"TOO LATE\");\n_end(sale);\n", "completion": "Creator can still \u201ccancel\u201d a sale after it has started by revoking permissions in OpenEdition contract"}
{"prompt": "uint48 amount = uint48(_amount);\nSale memory temp = sale;\nIEscher721 nft = IEscher721(temp.edition);\nrequire(block.timestamp >= temp.startTime, \"TOO SOON\");\nuint256 price = getPrice();\nrequire(msg.value >= amount * price, \"WRONG PRICE\");\n\namountSold += amount;\nuint48 newId = amount + temp.currentId;\nrequire(newId <= temp.finalId, \"TOO MANY\");\n\nreceipts[msg.sender].amount += amount;\nreceipts[msg.sender].balance += uint80(msg.value);\n\nfor (uint256 x = temp.currentId + 1; x <= newId; x++) {\nnft.mint(msg.sender, x);\n}\n\nsale.currentId = newId;\n\nemit Buy(msg.sender, amount, msg.value, temp);\n\nif (newId == temp.finalId) {\nsale.finalPrice = uint80(price);\nuint256 totalSale = price * amountSold;\nuint256 fee = totalSale / 20;\nISaleFactory(factory).feeReceiver().transfer(fee);\ntemp.saleReceiver.transfer(totalSale - fee);\n_end();\n}\n}\n\n", "completion": "NFTs mintable after Auction deadline expires"}
{"prompt": "bytes32 public constant CREATOR_ROLE = keccak256(\"CREATOR_ROLE\");\n/// @notice the role that grants the ability to onboard creators\nbytes32 public constant CURATOR_ROLE = keccak256(\"CURATOR_ROLE\");\nfunction grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n_grantRole(role, account);\n}\nrequire(escher.hasRole(escher.CREATOR_ROLE(), msg.sender), \"NOT AUTHORIZED\");\n\nescherClone = implementation.clone();\n", "completion": "Ownership of EscherERC721.sol contracts can be changed, thus creator roles become useless"}
{"prompt": "payable(msg.sender).transfer(owed);\n}\n\ntemp.saleReceiver.transfer(totalSale - fee);\n_end();\nISaleFactory(factory).feeReceiver().transfer(address(this).balance / 20);\nselfdestruct(_sale.saleReceiver);\n}\nISaleFactory(factory).feeReceiver().transfer(address(this).balance / 20);\n_end(temp);\n}\n", "completion": "Use of payable.transfer() Might Render ETH Impossible to Withdraw"}
{"prompt": "function createFixedSale(FixedPrice.Sale calldata _sale) external returns (address clone) {\nrequire(IEscher721(_sale.edition).hasRole(bytes32(0x00), msg.sender), \"NOT AUTHORIZED\");\nrequire(_sale.startTime >= block.timestamp, \"START TIME IN PAST\");\nfunction createLPDASale(LPDA.Sale calldata sale) external returns (address clone) {\nrequire(IEscher721(sale.edition).hasRole(bytes32(0x00), msg.sender), \"NOT AUTHORIZED\");\nrequire(sale.saleReceiver != address(0), \"INVALID SALE RECEIVER\");\nfunction createOpenEdition(OpenEdition.Sale calldata sale) external returns (address clone) {\nrequire(IEscher721(sale.edition).hasRole(bytes32(0x00), msg.sender), \"NOT AUTHORIZED\");\nrequire(sale.startTime >= block.timestamp, \"START TIME IN PAST\");\n", "completion": "Editions should be checked if they are actually deployed from the legitimate Escher721Factory"}
{"prompt": " address(executor),\n 0,\n _maxSubmissionCost,\n msg.sender,\n msg.sender,\n _gasLimit,\n _gasPriceBid,\n _data\n);\n\n", "completion": "When a smart contract calls CrossChainRelayerArbitrum.processCalls, excess submission fees may be lost"}
{"prompt": "uint256 _nonce,\naddress _sender,\nCallLib.Call[] calldata _calls\n ) external {\nICrossChainRelayer _relayer = relayer;\n_isAuthorized(_relayer);\n\nbool _executedNonce = executed[_nonce];\nexecuted[_nonce] = true;\n\nCallLib.executeCalls(_nonce, _sender, _calls, _executedNonce);\n\nemit ExecutedCalls(_relayer, _nonce);\n }\n\nuint256 _nonce,\naddress _sender,\nCallLib.Call[] calldata _calls\n ) external {\nICrossChainRelayer _relayer = relayer;\n_isAuthorized(_relayer);\n\nbool _executedNonce = executed[_nonce];\nexecuted[_nonce] = true;\n\nCallLib.executeCalls(_nonce, _sender, _calls, _executedNonce);\n\nemit ExecutedCalls(_relayer, _nonce);\n }\n\n", "completion": "CrossChainExecutor contracts do not update the necessary states for failing transactions"}
{"prompt": "address smartContract = msg.sender;\n\nif (_recipient == address(0)) revert InvalidRecipient();\n\ntokenId = _tokenIdTracker.current();\n_mint(_recipient, tokenId);\n_tokenIdTracker.increment();\n\nemit Register(smartContract, _recipient, tokenId);\n\nfeeRecipient[smartContract] = NftData({\ntokenId: tokenId,\nregistered: true\n});\n}\n\ncontract := msg.To()\nif contract == nil {\nreturn nil\n", "completion": "User can redirect fees by using a proxy contract"}
{"prompt": "return sdkerrors.Wrapf(ErrNonexistentAcct, \"EventHandler::RegisterEvent account does not exist: %s\", event.Recipient)\n}\n\n", "completion": "A registered contract won\u2019t earn fees if _recipient is a fresh address"}
{"prompt": "h.processEvents(ctx, receipt)\n\ncontract := msg.To()\n// Get the turnstile address from which state transition events are emitted\nturnstileAddress, found := h.k.GetTurnstile(ctx)\nif !found {\npanic(sdkerrors.Wrapf(ErrContractDeployments, \"EVMHook::PostTxProcessing the turnstile contract has not been found.\"))\n}\n\nfor _, log := range receipt.Logs {\nif len(log.Topics) == 0 {\ncontinue\n}\n\n// Only process events that originate from the Turnstile contract\neventID := log.Topics[0]\nif log.Address == turnstileAddress {\nevent, err := TurnstileContract.EventByID(eventID)\nif err != nil {\nh.k.Logger(ctx).Error(err.Error())\nreturn\n}\n\n// switch and process based on the turnstile event type\nswitch event.Name {\ncase types.TurnstileEventRegister:\nerr = h.k.RegisterEvent(ctx, log.Data)\ncase types.TurnstileEventUpdate:\nerr = h.k.UpdateEvent(ctx, log.Data)\n}\nif err != nil {\nh.k.Logger(ctx).Error(err.Error())\nreturn\n}\n}\n}\n}\n\n", "completion": "evm_hooks ignores some important errors"}
{"prompt": "return sdkerrors.Wrapf(ErrNonexistentCSR, \"EVMHook::PostTxProcessing the NFT ID was found but the CSR was not: %d\", nftID)\n}\n\nreturn sdkerrors.Wrapf(ErrFeeDistribution, \"EVMHook::PostTxProcessing failed to distribute fees from fee collector to module acount, %d\", err)\n}\n\nreturn sdkerrors.Wrapf(ErrContractDeployments, \"EVMHook::PostTxProcessing the turnstile contract has not been found.\")\n}\n\nreturn sdkerrors.Wrapf(ErrFeeDistribution, \"EVMHook::PostTxProcessing failed to distribute fees from module account to turnstile, %d\", err)\n}\n\n", "completion": "PostTxProcessing can revert user transactions not interacting with Turnstile"}
{"prompt": "address smartContract = msg.sender;\n\nif (_recipient == address(0)) revert InvalidRecipient();\n\ntokenId = _tokenIdTracker.current();\n_mint(_recipient, tokenId);\n_tokenIdTracker.increment();\n\nemit Register(smartContract, _recipient, tokenId);\n\nfeeRecipient[smartContract] = NftData({\ntokenId: tokenId,\nregistered: true\n});\n}\n\naddress smartContract = msg.sender;\n\nif (!_exists(_tokenId)) revert InvalidTokenId();\n\nemit Assign(smartContract, _tokenId);\n\nfeeRecipient[smartContract] = NftData({\ntokenId: _tokenId,\nregistered: true\n});\n\nreturn _tokenId;\n}\n\n", "completion": "There is no re-register or re-assign function"}
{"prompt": "function _redeemPxGlp(\naddress token,\nuint256 amount,\nfunction redeemPxGlpETH(\nuint256 amount,\nuint256 minOut,\nfunction redeemPxGlp(\naddress token,\nuint256 amount,\n", "completion": "The redeem related functions are likely to be blocked"}
{"prompt": "function _globalAccrue(GlobalState storage globalState, ERC20 producerToken)\ninternal\n{\nfunction userAccrue(ERC20 producerToken, address user) public {\nif (address(producerToken) == address(0)) revert ZeroAddress();\nif (user == address(0)) revert ZeroAddress();\nfunction claim(ERC20 producerToken, address user) external {\nif (address(producerToken) == address(0)) revert ZeroAddress();\nif (user == address(0)) revert ZeroAddress();\n", "completion": "Users Receive Less Rewards Due To Miscalculations"}
{"prompt": "function convertToShares(uint256 assets)\npublic\nview\nfunction previewWithdraw(uint256 assets)\npublic\nview\nfunction withdraw(\nuint256 assets,\naddress receiver,\n", "completion": "Malicious Users Can Drain The Assets Of Auto Compound Vault"}
{"prompt": "function claim(ERC20 producerToken, address user) external {\nif (address(producerToken) == address(0)) revert ZeroAddress();\nif (user == address(0)) revert ZeroAddress();\n", "completion": "User\u2019s Accrued Rewards Will Be Lost"}
{"prompt": "public\nview\nvirtual\nreturns (uint256)\n{\nuint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\nreturn supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n}\n\npublic\nview\nvirtual\nreturns (uint256)\n{\nuint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\nreturn supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n}\n\n", "completion": "Underlying assets stealing in AutoPxGmx and AutoPxGlp via share price manipulation"}
{"prompt": "external\nwhenPaused\nonlyOwner\n{\nif (newContract == address(0)) revert ZeroAddress();\n\n// Notify the reward router that the current/old contract is going to perform\n// full account transfer to the specified new contract\ngmxRewardRouterV2.signalTransfer(newContract);\n\nmigratedTo = newContract;\n\nemit InitiateMigration(newContract);\n}\n\n", "completion": "PirexGmx.initiateMigration can be blocked"}
{"prompt": "amountOutMinimum: amountOutMinimum,\nsqrtPriceLimitX96: sqrtPriceLimitX96\n})\n", "completion": "Preventing any user from calling the functions withdraw, redeem, or depositGmx in contract AutoPxGmx"}
{"prompt": "uint24 fee,\nuint256 amountOutMinimum,\nuint160 sqrtPriceLimitX96,\nbool optOutIncentive\n)\npublic\nreturns (\nuint256 gmxBaseRewardAmountIn,\nuint256 gmxAmountOut,\nuint256 pxGmxMintAmount,\nuint256 totalFee,\nuint256 incentive\n)\n{\nif (fee == 0) revert InvalidParam();\nif (amountOutMinimum == 0) revert InvalidParam();\n\nuint256 assetsBeforeClaim = asset.balanceOf(address(this));\n\nPirexRewards(rewardsModule).claim(asset, address(this));\n\n// Swap entire reward balance for GMX\ngmxBaseRewardAmountIn = gmxBaseReward.balanceOf(address(this));\n\nif (gmxBaseRewardAmountIn != 0) {\ngmxAmountOut = SWAP_ROUTER.exactInputSingle(\nIV3SwapRouter.ExactInputSingleParams({\ntokenIn: address(gmxBaseReward),\ntokenOut: address(gmx),\nfee: fee,\nrecipient: address(this),\namountIn: gmxBaseRewardAmountIn,\namountOutMinimum: amountOutMinimum,\nsqrtPriceLimitX96: sqrtPriceLimitX96\n})\n);\n\n", "completion": "Anyone can call AutoPxGmx.compound and perform sandwich attacks with control parameters"}
{"prompt": "IV3SwapRouter public constant SWAP_ROUTER =\nIV3SwapRouter(0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45);\nuint256 public constant MAX_WITHDRAWAL_PENALTY = 500;\ngmxBaseReward.safeApprove(address(SWAP_ROUTER), type(uint256).max);\ngmx.safeApprove(_platform, type(uint256).max);\n}\ngmxAmountOut = SWAP_ROUTER.exactInputSingle(\nIV3SwapRouter.ExactInputSingleParams({\ntokenIn: address(gmxBaseReward),\n", "completion": "SWAP_ROUTER in AutoPxGmx.sol is hardcoded and not compatible on Avalanche"}
{"prompt": "function compound(\nuint256 minUsdg,\nuint256 minGlp,\n// Mint and stake GLP using ETH\ndeposited = gmxRewardRouterV2.mintAndStakeGlpETH{\nvalue: tokenAmount\n}(minUsdg, minGlp);\n} else {\nERC20 t = ERC20(token);\n\n// Intake user ERC20 tokens and approve GLP Manager contract for amount\nt.safeTransferFrom(msg.sender, address(this), tokenAmount);\nt.safeApprove(glpManager, tokenAmount);\n\n// Mint and stake GLP using ERC20 tokens\ndeposited = gmxRewardRouterV2.mintAndStakeGlp(\ntoken,\ntokenAmount,\nminUsdg,\nminGlp\n);\n}\n\n", "completion": "Assets may be lost when calling unprotected AutoPxGlp::compound function"}
{"prompt": "constructor(\naddress _gmxBaseReward,\naddress _gmx,\nfunction setPlatform(address _platform) external onlyOwner {\nif (_platform == address(0)) revert ZeroAddress();\n\n", "completion": "Deposit Feature Of The Vault Will Break If Update To A New Platform"}
{"prompt": "function depositGlp(\naddress token,\nuint256 tokenAmount,\nfunction depositGlp(\naddress token,\nuint256 tokenAmount,\n", "completion": "Tokens with fees will break the depositGlp() logic"}
{"prompt": "if (msg.sender != migratedTo) revert NotMigratedTo();\nif (gmxRewardRouterV2.pendingReceivers(address(this)) != address(0))\nrevert PendingMigration();\n\n// Transfer out any remaining base reward (ie. WETH) to the new contract\ngmxBaseReward.safeTransfer(\nmigratedTo,\ngmxBaseReward.balanceOf(address(this))\n);\n}\n", "completion": "PirexGmx#migrateReward() may cause users to lose Reward."}
{"prompt": "p.userStates[user].rewards = 0;\n\n", "completion": "Reward tokens mismanagement can cause users losing rewards"}
{"prompt": "function maxWithdraw(address owner) public view virtual returns (uint256) {\nreturn convertToAssets(balanceOf[owner]);\n}\ncontract AutoPxGmx is ReentrancyGuard, Owned, PirexERC4626 {\nusing SafeTransferLib for ERC20;\nusing FixedPointMathLib for uint256;\ncontract AutoPxGlp is PirexERC4626, PxGmxReward, ReentrancyGuard {\nusing SafeTransferLib for ERC20;\nusing FixedPointMathLib for uint256;\nfunction withdraw(\nuint256 assets,\naddress receiver,\nfunction previewWithdraw(uint256 assets)\npublic\nview\n(FEE_DENOMINATOR - withdrawalPenalty);\n}\n_burn(owner, shares);\n\nemit Withdraw(msg.sender, receiver, owner, assets, shares);\n", "completion": "AutoPxGmx.maxWithdraw and AutoPxGlp.maxWithdraw functions calculate asset amount that is too big and cannot be withdrawn"}
{"prompt": "accumulatedETHPerLPShare += (unprocessed * PRECISION) / _numOfShares;\n\ntotalETHSeen = received;\nuint256 due = ((accumulatedETHPerLPShare * balance) / PRECISION) - claimed[_user][_token];\nif (due > 0) {\nclaimed[_user][_token] = due;\nclaimed[_user][address(lpTokenETH)] = (accumulatedETHPerLPShare * lpTokenETH.balanceOf(_user)) / PRECISION;\n}\n}\n", "completion": "Any user being the first to claim rewards from GiantMevAndFeesPool can unexepectedly collect them all"}
{"prompt": "_setClaimedToMax(_to);\n}\n\ncontract GiantLP is ERC20 {\n\n/// @notice Address of giant pool that deployed the giant LP token\n", "completion": "Rewards of GiantMevAndFeesPool can be locked for all users"}
{"prompt": "function unstake(\naddress _unclaimedETHRecipient,\naddress _sETHRecipient,\n", "completion": "Unstaking does not update the mapping sETHUserClaimForKnot"}
{"prompt": "require(!Address.isContract(_eoaRepresentative), \"Only EOA representative permitted\");\nrequire(_isNodeRunnerValid(msg.sender) == true, \"Unrecognised node runner\");\nrequire(isNodeRunnerBanned(msg.sender) == false, \"Node runner is banned from LSD network\");\nfunction withdrawETHForKnot(address _recipient, bytes calldata _blsPublicKeyOfKnot) external {\nrequire(_recipient != address(0), \"Zero address\");\nrequire(isBLSPublicKeyBanned(_blsPublicKeyOfKnot) == false, \"BLS public key has already withdrawn or not a part of LSD network\");\nIOwnableSmartWallet(associatedSmartWallet).rawExecute(\n_recipient,\n\"\",\nbannedBLSPublicKeys[_blsPublicKeyOfKnot] = associatedSmartWallet;\n\nemit ETHWithdrawnFromSmartWallet(associatedSmartWallet, _blsPublicKeyOfKnot, msg.sender);\n", "completion": "Reentrancy in LiquidStakingManager.sol#withdrawETHForKnow leads to loss of fund from smart wallet"}
{"prompt": "if (address(transferHookProcessor) != address(0)) ITransferHookProcessor(transferHookProcessor).beforeTokenTransfer(_from, _to, _amount);\n}\n\nfunction _afterTokenTransfer(address _from, address _to, uint256 _amount) internal override {\nlastInteractedTimestamp[_from] = block.timestamp;\nlastInteractedTimestamp[_to] = block.timestamp;\nif (address(transferHookProcessor) != address(0)) ITransferHookProcessor(transferHookProcessor).afterTokenTransfer(_from, _to, _amount);\n}\n}\nmsg.sender,\naddress(lpTokenETH),\nlpTokenETH.balanceOf(msg.sender),\n_recipient\n);\n}\naddress _user,\naddress _token,\nuint256 _balance,\naddress _recipient\n) internal {\nrequire(_recipient != address(0), \"Zero address\");\nuint256 balance = _balance;\n", "completion": "GiantLP with a transferHookProcessor cant be burned, users\u2019 funds will be stuck in the Giant Pool"}
{"prompt": "\nlpTokenETH.burn(msg.sender, _amount);\n(bool success,) = msg.sender.call{value: _amount}(\"\");\nrequire(success, \"Failed to transfer ETH\");\nreturn address(this).balance + totalClaimed - idleETH;\n}\n\nif (_numOfShares > 0) {\nuint256 received = totalRewardsReceived();\nuint256 unprocessed = received - totalETHSeen;\n\nif (unprocessed > 0) {\nemit ETHReceived(unprocessed);\n\n// accumulated ETH per minted share is scaled to avoid precision loss. it is scaled down later\naccumulatedETHPerLPShare += (unprocessed * PRECISION) / _numOfShares;\n\ntotalETHSeen = received;\n}\n}\n}\n\n", "completion": "function withdrawETH from GiantMevAndFeesPool can steal most of eth because of idleETH is reduced before burning token"}
{"prompt": "claimed[_user][_token] = due;\n\ntotalClaimed += due;\n_distributeETHRewardsToUserForToken(\nmsg.sender,\naddress(tokenForKnot),\n", "completion": "Incorrect accounting in SyndicateRewardsProcessor results in any LP token holder being able to steal other LP tokens holder\u2019s ETH from the fees and MEV vault"}
{"prompt": "address[] calldata _stakingFundsVaults,\nLPToken[][] calldata _lpTokens,\nuint256[][] calldata _amounts\n) external {\nuint256 numOfVaults = _stakingFundsVaults.length;\nrequire(numOfVaults > 0, \"Empty arrays\");\nrequire(numOfVaults == _lpTokens.length, \"Inconsistent arrays\");\nrequire(numOfVaults == _amounts.length, \"Inconsistent arrays\");\nfor (uint256 i; i < numOfVaults; ++i) {\nStakingFundsVault(payable(_stakingFundsVaults[i])).burnLPTokensForETH(_lpTokens[i], _amounts[i]);\n}\n}\n\nreturn address(this).balance + totalClaimed - idleETH;\n}\n\n", "completion": "GiantMevAndFeesPool.bringUnusedETHBackIntoGiantPool function loses the addition of the idleETH which allows attackers to steal most of eth from the Giant Pool"}
{"prompt": "function withdrawETHForKnot(address _recipient, bytes calldata _blsPublicKeyOfKnot) external {\nrequire(_recipient != address(0), \"Zero address\");\nrequire(isBLSPublicKeyBanned(_blsPublicKeyOfKnot) == false, \"BLS public key has already withdrawn or not a part of LSD network\");\nfunction _assertEtherIsReadyForValidatorStaking(bytes calldata blsPubKey) internal view {\naddress associatedSmartWallet = smartWalletOfKnot[blsPubKey];\nrequire(associatedSmartWallet.balance >= 4 ether, \"Smart wallet balance must be at least 4 ether\");\nfunction stake(\nbytes[] calldata _blsPublicKeyOfKnots,\nbytes[] calldata _ciphertexts,\n", "completion": "Protocol insolvent - Permanent freeze of funds"}
{"prompt": "require(msg.sender == address(lpTokenETH), \"Caller is not giant LP\");\n_setClaimedToMax(_to);\n}\n\n", "completion": "Sender transferring GiantMevAndFeesPool tokens can afterward experience pool DOS and orphaning of future rewards"}
{"prompt": "function _onDepositETH() internal override {\n_setClaimedToMax(msg.sender);\n}\n\n/// @dev Internal re-usable method for setting claimed to max for msg.sender\nfunction _setClaimedToMax(address _user) internal {\n// New ETH stakers are not entitled to ETH earned by\nclaimed[_user][address(lpTokenETH)] = (accumulatedETHPerLPShare * lpTokenETH.balanceOf(_user)) / PRECISION;\n}\n}\nfunction depositETH(uint256 _amount) public payable {\nrequire(msg.value >= MIN_STAKING_AMOUNT, \"Minimum not supplied\");\nrequire(msg.value == _amount, \"Value equal to amount\");\n\n// The ETH capital has not yet been deployed to a liquid staking network\nidleETH += msg.value;\n\n// Mint giant LP at ratio of 1:1\nlpTokenETH.mint(msg.sender, msg.value);\n\n// If anything extra needs to be done\n_onDepositETH();\n\nemit ETHDeposited(msg.sender, msg.value);\n}\n\n", "completion": "User loses remaining rewards in GiantMevAndFeesPool when new deposits happen because _onDepositETH() set claimed[][ to max without transferring user remaining rewards"}
{"prompt": "require(_amount >= MIN_STAKING_AMOUNT, \"Invalid amount\");\nrequire(lpTokenETH.balanceOf(msg.sender) >= _amount, \"Invalid balance\");\nrequire(idleETH >= _amount, \"Come back later or withdraw less ETH\");\n\nidleETH -= _amount;\n\nlpTokenETH.burn(msg.sender, _amount);\n(bool success,) = msg.sender.call{value: _amount}(\"\");\nrequire(success, \"Failed to transfer ETH\");\n\nemit LPBurnedForETH(msg.sender, _amount);\n}\n\n", "completion": "Reentrancy vulnerability in GiantMevAndFeesPool.withdrawETH"}
{"prompt": "function bringUnusedETHBackIntoGiantPool(\naddress[] calldata _stakingFundsVaults,\nLPToken[][] calldata _lpTokens,\n", "completion": "bringUnusedETHBackIntoGiantPool in GiantMevAndFeesPool can be used to steal LPTokens"}
{"prompt": "function withdrawDETH(\naddress[] calldata _savETHVaults,\nLPToken[][] calldata _lpTokens,\n", "completion": "dETH / ETH / LPTokenETH can become depegged due to ETH 2.0 reward slashing"}
{"prompt": "require(!Address.isContract(_eoaRepresentative), \"Only EOA representative permitted\");\nrequire(_isNodeRunnerValid(msg.sender) == true, \"Unrecognised node runner\");\nrequire(isNodeRunnerBanned(msg.sender) == false, \"Node runner is banned from LSD network\");\n", "completion": "Address.isContract() is not a reliable way of checking if the input is an EOA"}
{"prompt": "require(_commissionPercentage <= MODULO, \"Invalid commission\");\n\nemit DAOCommissionUpdated(daoCommissionPercentage, _commissionPercentage);\n\ndaoCommissionPercentage = _commissionPercentage;\n}\n}\n\n", "completion": "Node runners can lose all their stake rewards due to how the DAO commissions can be set to a 100%"}
{"prompt": "_claimFundsFromSyndicateForDistribution(\nliquidStakingNetworkManager.syndicate(),\n_blsPubKeys\n", "completion": "Funds are not claimed from syndicate for valid BLS keys of first key is invalid (no longer part of syndicate)."}
{"prompt": "updateAccumulatedETHPerLP();\n}\n\n", "completion": "User receives less rewards than they are eligible for if first passed BLS key is inactive"}
{"prompt": "function batchRotateLPTokens(\naddress[] calldata _stakingFundsVaults,\nLPToken[][] calldata _oldLPTokens,\n", "completion": "Giant pools are prone to user griefing, preventing their holdings from being staked"}
{"prompt": "(block.timestamp < order.expirationTime)\n);\n}\n", "completion": "All orders which use expirationTime == 0 to support oracle cancellation are not executable"}
{"prompt": "return userShare - sETHUserClaimForKnot[_blsPubKey][_user];\n}\n\n(bool success,) = _recipient.call{value: unclaimedUserShare}(\"\");\nif (!success) revert TransferFailed();\n\nsETHUserClaimForKnot[_blsPubKey][_onBehalfOf] = (_sETHAmount * accumulatedETHPerFreeFloatingShare) / PRECISION;\n\n(address stakeHouse,,,,,) = getStakeHouseUniverse().stakeHouseKnotInfo(_blsPubKey);\n", "completion": "Theft of ETH of free floating SLOT holders"}
{"prompt": "liquidStakingDerivativeFactory.isLiquidStakingManager(address(savETHPool.liquidStakingManager())),\n\"Invalid liquid staking manager\"\n);\nliquidStakingDerivativeFactory.isLiquidStakingManager(address(sfv.liquidStakingNetworkManager())),\n\"Invalid liquid staking manager\"\n);\n", "completion": "Giant pools can be drained due to weak vault authenticity check"}
{"prompt": "updateAccumulatedETHPerLP();\n\nuint256 totalAmount;\nupdateAccumulatedETHPerLP();\n\n// Give anything owed to the user before making updates to user state\n_updateAccumulatedETHPerLP(totalShares);\n}\n\n", "completion": "Old stakers can steal deposits of new stakers in StakingFundsVault"}
{"prompt": "function withdrawLPTokens(LPToken[] calldata _lpTokens, uint256[] calldata _amounts) external {\nuint256 amountOfTokens = _lpTokens.length;\nrequire(amountOfTokens > 0, \"Empty arrays\");\nfunction withdrawDETH(\naddress[] calldata _savETHVaults,\nLPToken[][] calldata _lpTokens,\nrequire(lpTokenETH.lastInteractedTimestamp(msg.sender) + 1 days < block.timestamp, \"Too new\");\n}\n\n", "completion": "Freezing of funds - Hacker can prevent users withdraws in giant pools"}
{"prompt": "function rotateLPTokens(LPToken _oldLPToken, LPToken _newLPToken, uint256 _amount) public {\nrequire(address(_oldLPToken) != address(0), \"Zero address\");\nrequire(address(_newLPToken) != address(0), \"Zero address\");\n", "completion": "Rotating LPTokens to banned BLS public key"}
{"prompt": "function bringUnusedETHBackIntoGiantPool(\naddress[] calldata _savETHVaults,\nLPToken[][] calldata _lpTokens,\nfunction bringUnusedETHBackIntoGiantPool(\naddress[] calldata _stakingFundsVaults,\nLPToken[][] calldata _lpTokens,\n", "completion": "Giant pools cannot receive ETH from vaults"}
{"prompt": "require(_amount >= MIN_STAKING_AMOUNT, \"Invalid amount\");\nrequire(lpTokenETH.balanceOf(msg.sender) >= _amount, \"Invalid balance\");\nrequire(idleETH >= _amount, \"Come back later or withdraw less ETH\");\n", "completion": "GiantPool should not check ETH amount on withdrawal"}
{"prompt": "function rotateEOARepresentativeOfNodeRunner(address _nodeRunner, address _newRepresentative) external onlyDAO {\nrequire(_newRepresentative != address(0), \"Zero address\");\n\nfunction rotateEOARepresentative(address _newRepresentative) external {\nrequire(_newRepresentative != address(0), \"Zero address\");\nrequire(isNodeRunnerBanned(msg.sender) == false, \"Node runner is banned from LSD network\");\n", "completion": "Adding non EOA representative"}
{"prompt": "function withdrawLPTokens(LPToken[] calldata _lpTokens, uint256[] calldata _amounts) external {\nuint256 amountOfTokens = _lpTokens.length;\nrequire(amountOfTokens > 0, \"Empty arrays\");\nrequire(_token.balanceOf(address(this)) >= _amount, \"Pool does not own specified LP\");\nrequire(lpTokenETH.lastInteractedTimestamp(msg.sender) + 1 days < block.timestamp, \"Too new\");\n}\n", "completion": "Withdrawing wrong LPToken from GiantPool leads to loss of funds"}
{"prompt": "function transferOwnership(address newOwner)\npublic\noverride(IOwnableSmartWallet, Ownable)\n// if this wallet ever returns to the previous owner\nif (msg.sender != owner()) {\n", "completion": "OwnableSmartWallet: Multiple approvals can lead to unwanted ownership transfers"}
{"prompt": "function executeAsSmartWallet(\naddress _nodeRunner,\naddress _to,\nIOwnableSmartWallet(smartWallet).execute(\n_to,\n_data,\nfunction registerBLSPublicKeys(\nbytes[] calldata _blsPublicKeys,\nbytes[] calldata _blsSignatures,\n(bool result,) = smartWallet.call{value: msg.value}(\"\");\nrequire(result, \"Transfer failed\");\nemit WalletCredited(smartWallet, msg.value);\nreturn target.functionCallWithValue(callData, value); // F: [OSW-6]\n}\n\n", "completion": "DAO admin in LiquidStakingManager.sol can rug the registered node operator by stealing their fund in the smart wallet via arbitrary execution."}
{"prompt": "require(_new != address(0) && _current != _new, \"New is zero or current\");\n\naddress wallet = smartWalletOfNodeRunner[_current];\nrequire(wallet != address(0), \"Wallet does not exist\");\nrequire(_current == msg.sender || dao == msg.sender, \"Not current owner or DAO\");\n\naddress newRunnerCurrentWallet = smartWalletOfNodeRunner[_new];\nrequire(newRunnerCurrentWallet == address(0), \"New runner has a wallet\");\n\nsmartWalletOfNodeRunner[_new] = wallet;\nnodeRunnerOfSmartWallet[wallet] = _new;\n\ndelete smartWalletOfNodeRunner[_current];\n\nif (msg.sender == dao && _wasPreviousNodeRunnerMalicious) {\nbannedNodeRunners[_current] = true;\nemit NodeRunnerBanned(_current);\n}\n\nemit NodeRunnerOfSmartWalletRotated(wallet, _current, _new);\n}\n\n", "completion": "DAO or lsdn owner can steal funds from node runner"}
{"prompt": "require(isBLSPublicKeyPartOfLSDNetwork(_blsPublicKey) == false, \"BLS public key is banned or not a part of LSD network\");\n\nrequire(\n", "completion": "Banned BLS public keys can still be registered"}
{"prompt": "uint256 stakeAmount = 12 ether;\nIOwnableSmartWallet(_associatedSmartWallet).execute(\naddress(sETH),\nInvalidStakeAmount,\nKnotIsNotAssociatedWithAStakeHouse,\nUnableToStakeFreeFloatingSlot,\n", "completion": "Attacker can grift syndicate staking by staking a small amount"}
{"prompt": "require(lpTokenETH.balanceOf(msg.sender) >= 0.5 ether, \"No common interest\");\nfor (uint256 i; i < numOfRotations; ++i) {\nSavETHVault(_savETHVaults[i]).batchRotateLPTokens(_oldLPTokens[i], _newLPTokens[i], _amounts[i]);\nrequire(lpTokenETH.balanceOf(msg.sender) >= 0.5 ether, \"No common interest\");\nfor (uint256 i; i < numOfRotations; ++i) {\nStakingFundsVault(payable(_stakingFundsVaults[i])).batchRotateLPTokens(_oldLPTokens[i], _newLPTokens[i], _amounts[i]);\nuint256 public constant MIN_STAKING_AMOUNT = 0.001 ether;\n\n/// @notice Total amount of ETH sat idle ready for either withdrawal or depositing into a liquid staking network\n", "completion": "GiantPool batchRotateLPTokens function: Minimum balance for rotating LP Tokens should by dynamically calculated"}
{"prompt": "address _deployer,\naddress _transferHookProcessor,\nstring calldata _tokenSymbol,\nstring calldata _tokenName\n) external returns (address) {\nrequire(address(_deployer) != address(0), \"Zero address\");\nrequire(bytes(_tokenSymbol).length != 0, \"Symbol cannot be zero\");\nrequire(bytes(_tokenName).length != 0, \"Name cannot be zero\");\n\naddress newInstance = Clones.clone(lpTokenImplementation);\nILPTokenInit(newInstance).init(\n_deployer,\n_transferHookProcessor,\n_tokenSymbol,\n_tokenName\n);\n\nemit LPTokenDeployed(newInstance);\n\nreturn newInstance;\n}\n}\n", "completion": "Cross-chain replay attacks are possible with deployLPToken"}
{"prompt": "function previewAccumulatedETH(\naddress _user,\naddress[] calldata _stakingFundsVaults,\naccumulated = StakingFundsVault(payable(_stakingFundsVaults[i])).batchPreviewAccumulatedETH(\naddress(this),\n_lpTokens[i]\n", "completion": "GiantMevAndFeesPool.previewAccumulatedETH function: \u201caccumulated\u201d variable is not updated correctly in for loop leading to result that is too low"}
{"prompt": "require(msg.sender == address(lpTokenETH), \"Caller is not giant LP\");\nupdateAccumulatedETHPerLP();\n\n", "completion": "When users transfer GiantLP, some rewards may be lost"}
{"prompt": "address _nodeRunner,\naddress _to,\nbytes calldata _data,\nuint256 _value\n) external payable onlyDAO {\naddress smartWallet = smartWalletOfNodeRunner[_nodeRunner];\nrequire(smartWallet != address(0), \"No wallet found\");\nIOwnableSmartWallet(smartWallet).execute(\n_to,\n_data,\n_value\n);\n}\n\naddress target,\nbytes memory callData,\nuint256 value\n)\nexternal\noverride\npayable\nonlyOwner // F: [OSW-6A]\nreturns (bytes memory)\n{\nreturn target.functionCallWithValue(callData, value); // F: [OSW-6]\n}\n\n", "completion": "ETH sent when calling executeAsSmartWallet function can be lost"}
{"prompt": "require(_amount >= MIN_STAKING_AMOUNT, \"Invalid amount\");\nrequire(_token.balanceOf(address(this)) >= _amount, \"Pool does not own specified LP\");\nrequire(lpTokenETH.lastInteractedTimestamp(msg.sender) + 1 days < block.timestamp, \"Too new\");\n}\n\n", "completion": "Incorrect checking in _assertUserHasEnoughGiantLPToClaimVaultLP"}
{"prompt": "function rotateNodeRunnerOfSmartWallet(address _current, address _new, bool _wasPreviousNodeRunnerMalicious) external {\nrequire(_new != address(0) && _current != _new, \"New is zero or current\");\n\ndelete smartWalletOfNodeRunner[_current];\n\nif (msg.sender == dao && _wasPreviousNodeRunnerMalicious) {\n", "completion": "rotateNodeRunnerOfSmartWallet is vulnerable to a frontrun attack"}
{"prompt": "require(_amount >= MIN_STAKING_AMOUNT, \"Min amount not reached\");\nrequire(_blsPublicKeyOfKnot.length == 48, \"Invalid BLS public key\");\n\n", "completion": "Vaults can be griefed to not be able to be used for deposits"}
{"prompt": "require(_smartWallet != address(this), \"This address\");\n\n(bool result,) = _smartWallet.call{value: _amount}(\"\");\nrequire(result, \"Transfer failed\");\n\n", "completion": "smartWallet address is not guaranteed correct. ETH may be lost"}
{"prompt": "function bulkExecute(Execution[] calldata executions)\nexternal\npayable\nfunction _executeFundsTransfer(\naddress seller,\naddress buyer,\nfunction _returnDust() private {\nuint256 _remainingETH = remainingETH;\nassembly {\nfunction execute(Input calldata sell, Input calldata buy)\nexternal\npayable\n", "completion": "Direct theft of buyer\u2019s ETH funds"}
{"prompt": "require(account != address(0), \"INVALID_ADDRESS\");\n// If we're using maxSupply, we need to make sure we respect it\n// mintableSupply = 0 means mint at will\nif(mintableSupply > 0) {\nrequire(amount <= mintableSupply, \"INVALID_AMOUNT\");\n// We need to reduce the amount only if we're using the limit, if not just leave it be\nmintableSupply -= amount;\n}\n_mint(account, amount);\n}\n\n", "completion": "Yul call return value not checked"}
{"prompt": "executionDelegate.transferERC20(WETH, from, to, amount);\n} else {\nrevert(\"Invalid payment token\");\ncontract Exchange is IExchange, ReentrancyGuarded, EIP712, OwnableUpgradeable, UUPSUpgradeable {\n\n/* Auth */\n", "completion": "Hacked owner or malicious owner can immediately steal all assets on the platform"}
{"prompt": "contract Pool is IPool, OwnableUpgradeable, UUPSUpgradeable {\n// required by the OZ UUPS module\nfunction _authorizeUpgrade(address) internal override onlyOwner {}\n", "completion": "Pool designed to be upgradeable but does not set owner, making it un-upgradeable"}
{"prompt": "uint256 _remainingETH = remainingETH;\nassembly {\nif gt(_remainingETH, 0) {\nlet callStatus := call(\ngas(),\ncaller(),\nselfbalance(),\n0,\n0,\n0,\n0\n)\n}\n}\n}\n\n", "completion": "Yul call return value not checked"}
{"prompt": "if (fee > 0) _transferFee(fee, lastOrderCurrency, feeRecipient);\n}\n\n", "completion": "The _executeNonAtomicOrders function in SeaportProxy.sol may fail unexpectedly"}
{"prompt": "BasicOrder[] calldata orders,\nuint256 feeBp,\naddress feeRecipient\n) private {\naddress lastOrderCurrency;\nuint256 fee;\nuint256 ordersLength = orders.length;\n\nfor (uint256 i; i < ordersLength; ) {\naddress currency = orders[i].currency;\nuint256 orderFee = (orders[i].price * feeBp) / 10000;\n\n", "completion": "Too much fee charged when Seaport is partially filled"}
{"prompt": "abstract contract OwnableTwoSteps is IOwnableTwoSteps {\n// Address of the current owner\naddress public owner;\n", "completion": "It is clearly stated that timelock is used, but this does not happen in the codes"}
{"prompt": "let status := call(gas(), caller(), selfbalance(), 0, 0, 0, 0)\n}\n}\nlet status := call(gas(), recipient, selfbalance(), 0, 0, 0, 0)\n}\n}\nlet status := call(gas(), caller(), sub(selfbalance(), 1), 0, 0, 0, 0)\n}\n}\n", "completion": "call opcode\u2019s return value not checked."}
{"prompt": "function rescueETH(address to) external onlyOwner {\nuint256 withdrawAmount = address(this).balance - 1;\nif (withdrawAmount == 0) revert InsufficientAmount();\nfunction rescueERC20(address currency, address to) external onlyOwner {\nuint256 withdrawAmount = IERC20(currency).balanceOf(address(this)) - 1;\nif (withdrawAmount == 0) revert InsufficientAmount();\nTokenRescuer,\nTokenReceiver,\nReentrancyGuard,\nif (tokenTransfersLength > 0) _returnERC20TokensIfAny(tokenTransfers, originator);\n_returnETHIfAny(originator);\n\n_returnETHIfAny(originator);\n\nemit Sweep(originator);\nif (balance > 0) _executeERC20DirectTransfer(tokenTransfers[i].currency, recipient, balance);\n\nunchecked {\nfunction _returnETHIfAny(address recipient) internal {\nassembly {\nif gt(selfbalance(), 0) {\n", "completion": "Public to all funds escape"}
{"prompt": "uint256 filledQuote = FixedPointMathLib.mulDivDown(clearingQuote, data.filledBase, clearingBase);\n\nSafeTransferLib.safeTransfer(ERC20(a.params.quoteToken), a.data.seller, filledQuote);\n", "completion": "Bidders might fail to withdraw their unused funds after the auction was finalized because the contract doesn\u2019t have enough balance."}
{"prompt": "} else if (a.data.lowestQuote != type(uint128).max) {\nif (_state != States.Finalized) revert InvalidState();\n} else if (block.timestamp <= a.timings.endTimestamp + 24 hours) {\na.data.lowestQuote = clearingQuote;\n\n// Bitmap of all the bid indices that have been processed\n", "completion": "Attacker can steal any funds in the contract by state confusion (no preconditions)"}
{"prompt": "SafeTransferLib.safeTransferFrom(ERC20(a.params.quoteToken), msg.sender, address(this), quoteAmount);\n\nemit Bid(\n\nSafeTransferLib.safeTransferFrom(\nERC20(auctionParams.baseToken), msg.sender, address(this), auctionParams.totalBaseAmount\n);\n\nuint256 balanceAfterTransfer = ERC20(auctionParams.baseToken).balanceOf(address(this));\nif (balanceAfterTransfer - balanceBeforeTransfer != auctionParams.totalBaseAmount) {\nrevert UnexpectedBalanceChange();\n}\n\n", "completion": "Incompatibility with fee-on-transfer/inflationary/deflationary/rebasing tokens, on both base tokens and quote tokens, with varying impacts"}
{"prompt": "SafeTransferLib.safeTransferFrom(ERC20(a.params.quoteToken), msg.sender, address(this), quoteAmount);\n\nemit Bid(\n", "completion": "Solmate\u2019s ERC20 does not check for token contract\u2019s existence, which opens up possibility for a honeypot attack"}
{"prompt": "if (quotePerBase >= data.previousQuotePerBase) {\n// If last bid was the same price, make sure we filled the earliest bid first\nif (quotePerBase == data.previousQuotePerBase) {\nif (data.previousIndex > bidIndex) revert InvalidSorting();\n} else {\nrevert InvalidSorting();\n}\n}\n\n", "completion": "The sorting logic is not strict enough"}
{"prompt": "\nSafeTransferLib.safeTransferFrom(\nERC20(auctionParams.baseToken), msg.sender, address(this), auctionParams.totalBaseAmount\n);\n\nuint256 balanceAfterTransfer = ERC20(auctionParams.baseToken).balanceOf(address(this));\nif (balanceAfterTransfer - balanceBeforeTransfer != auctionParams.totalBaseAmount) {\n", "completion": "Auction created by ERC777 Tokens with tax can be stolen by re-entrancy attack"}
{"prompt": "revert UnauthorizedCaller();\n}\n\n", "completion": "Seller\u2019s ability to decrypt bids before reveal could result in a much higher clearing price than anticpated and make buyers distrust the system"}
{"prompt": "\nbytes32 decryptedMessage = ECCMath.decryptMessage(sharedPoint, b.encryptedMessage);\n// If the bidder didn't faithfully submit commitment or pubkey\n// Or the bid was cancelled\nif (computeCommitment(decryptedMessage) != b.commitment) continue;\n\nrevert InvalidState();\n}\n\nif (quotePerBase >= data.previousQuotePerBase) {\n// If last bid was the same price, make sure we filled the earliest bid first\nif (quotePerBase == data.previousQuotePerBase) {\nif (data.previousIndex > bidIndex) revert InvalidSorting();\n} else {\nrevert InvalidSorting();\n}\n}\n\n// Only fill if above reserve price\nif (quotePerBase < data.reserveQuotePerBase) continue;\n\n", "completion": "Attacker may DOS auctions using invalid bid parameters"}
{"prompt": "function finalize(uint256 auctionId, uint256[] memory bidIndices, uint128 clearingBase, uint128 clearingQuote)\npublic\natState(idToAuction[auctionId], States.RevealPeriod)\nuint256 quotePerBase = FixedPointMathLib.mulDivDown(b.quoteAmount, type(uint128).max, baseAmount);\nif (quotePerBase >= data.previousQuotePerBase) {\n// If last bid was the same price, make sure we filled the earliest bid first\nif iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\nrevert(0, 0)\n}\n", "completion": "Denial of service when baseAmount is equal to zero"}
{"prompt": "function declareInsolvent() external whileBorrowing returns(bool) {\nif(arbiter != msg.sender) { revert CallerAccessDenied(); }\nif(LineLib.STATUS.LIQUIDATABLE != _updateStatus(_healthcheck())) {\nif(count == 0 || credits[ids[0]].principal == 0) { revert NotBorrowing(); }\n_;\n}\n\n", "completion": "Call to declareInsolvent() would revert when contract status reaches liquidation point after repayment of credit position 1"}
{"prompt": "claimed = _claimRevenue(self, revenueContract, token, data);\n\n// splits revenue stream according to Spigot settings\n", "completion": "Non-existing revenue contract can be passed to claimRevenue to send all tokens to treasury"}
{"prompt": "mutualConsent(lender, borrower)\nreturns (bytes32)\n{\n mutualConsentById(id)\n returns (bool)\n{\n", "completion": "addCredit / increaseCredit cannot be called by lender first when token is ETH"}
{"prompt": "Credit memory credit = credits[id];\naddress b = borrower; // gas savings\nif(msg.sender != credit.lender && msg.sender != b) {\n", "completion": "Borrower can close a credit without repaying debt"}
{"prompt": "uint256 lastSpot = ids.length - 1;\nuint256 nextQSpot = lastSpot;\nbytes32 id;\nfor (uint256 i; i <= lastSpot; ++i) {\nid = ids[i];\nif (p != id) {\nif (\n id == bytes32(0) || // deleted element. In the middle of the q because it was closed.\n nextQSpot != lastSpot || // position already found. skip to find `p` asap\n credits[id].principal > 0 //`id` should be placed before `p` \n) continue;\nnextQSpot = i; // index of first undrawn line found\n} else {\nif(nextQSpot == lastSpot) return true; // nothing to update\n// swap positions\nids[i] = ids[nextQSpot];// id put into old `p` position\nids[nextQSpot] = p; // p put at target index\nreturn true; \n}\n \n}\n}\n}\n", "completion": "Borrower can craft a borrow that cannot be liquidated, even by arbiter."}
{"prompt": " credit.principal -= principalPayment;\n credit.interestRepaid += interest;\n credit.interestAccrued = 0;\n", "completion": "Repaying a line of credit with a higher than necessary claimed revenue amount will force the borrower into liquidation"}
{"prompt": " spigot.claimEscrow(claimToken) : // same asset. dont trade\n _claimAndTrade( // trade revenue token for debt obligation\n claimToken,\n credit.token,\n zeroExTradeData\n );\n\nclaimed + unused,\nclaimToken,\nswapTarget,\nzeroExTradeData\n);\n\n// underflow revert ensures we have more tokens than we started with\nuint256 tokensBought = LineLib.getBalance(targetToken) - oldTargetTokens;\n\nif(tokensBought == 0) { revert TradeFailed(); } // ensure tokens bought\n\n", "completion": "Lender can trade claimToken in a malicious way to steal the borrower\u2019s money via claimAndRepay() in SpigotedLine by using malicious zeroExTradeData"}
{"prompt": "if (credit.deposit + credit.interestRepaid > 0) {\nLineLib.sendOutTokenOrETH(\ncredit.token,\n", "completion": "Reentrancy bug allows lender to steal other lenders funds"}
{"prompt": "function close(bytes32 id) external payable override returns (bool) {\nCredit memory credit = credits[id];\naddress b = borrower; // gas savings\nLineLib.sendOutTokenOrETH(\ncredit.token,\ncredit.lender,\n", "completion": "The lender can draw out extra credit token from borrower\u2019s account"}
{"prompt": "credit.lender,\ncredit.deposit + credit.interestRepaid\n);\n}\n\n", "completion": "Lender can reject closing a position"}
{"prompt": "uint128 drate,\nuint128 frate,\nuint256 amount,\naddress token,\naddress lender\n)\nexternal\npayable\noverride\nwhileActive\nmutualConsent(lender, borrower)\nreturns (bytes32)\n{\nLineLib.receiveTokenOrETH(token, lender, amount);\n\nbytes32 id = _createCredit(lender, token, amount);\n\nrequire(interestRate.setRate(id, drate, frate));\n\nreturn id;\n}\n\n address token,\n address sender,\n uint256 amount\n)\n external\n returns (bool)\n{\nif(token == address(0)) { revert TransferFailed(); }\nif(token != Denominations.ETH) { // ERC20\nIERC20(token).safeTransferFrom(sender, address(this), amount);\n} else { // ETH\nif(msg.value < amount) { revert TransferFailed(); }\n}\nreturn true;\n}\n\n", "completion": "Borrower can by mistake add own money to credit if credit is in ETH"}
{"prompt": "function depositAndClose()\nexternal\npayable\nfunction depositAndRepay(uint256 amount)\nexternal\npayable\nfunction addCredit(\nuint128 drate,\nuint128 frate,\nfunction increaseCredit(bytes32 id, uint256 amount)\n external\n payable\nif(msg.value < amount) { revert TransferFailed(); }\n}\nreturn true;\nfunction close(bytes32 id) external payable override returns (bool) {\nCredit memory credit = credits[id];\naddress b = borrower; // gas savings\n", "completion": "Borrower/Lender excessive ETH not refunded and permanently locked in protocol"}
{"prompt": "if(!self.whitelistedFunctions[func]) { revert BadFunction(); }\n\n// cant claim revenue via operate() because that fucks up accounting logic. Owner shouldn't whitelist it anyway but just in case\nmapping(bytes4 => bool) whitelistedFunctions; // function -> allowed\n// Configurations for revenue contracts related to the split of revenue, access control to claiming revenue tokens and transfer of Spigot ownership\nmapping(address => ISpigot.Setting) settings; // revenue contract -> settings\n", "completion": "Whitelisted functions aren\u2019t scoped to revenue contracts and may lead to unnoticed calls due to selector clashing"}
{"prompt": " address token,\n address sender,\n uint256 amount\n)\n external\n returns (bool)\n{\nif(token == address(0)) { revert TransferFailed(); }\nif(token != Denominations.ETH) { // ERC20\nIERC20(token).safeTransferFrom(sender, address(this), amount);\n} else { // ETH\nif(msg.value < amount) { revert TransferFailed(); }\n}\nreturn true;\n}\n\n", "completion": "Mistakenly sent eth could be locked"}
{"prompt": "payable(receiver).transfer(amount);\n}\nreturn true;\n", "completion": "address.call{value:x}() should be used instead of payable.transfer()"}
{"prompt": "\nself.deposited[token].amount += amount;\n\n o.getLatestAnswer(d.asset),\n deposit,\n d.assetDecimals\n);\n}\ncredit = _accrue(credit, id);\n\ncredit.deposit += amount;\n\ncredits[id] = credit;\n\nLineLib.receiveTokenOrETH(credit.token, credit.lender, amount);\n\nLineLib.sendOutTokenOrETH(\ncredit.token,\ncredit.lender,\ncredit.deposit + credit.interestRepaid\n);\n}\n\n", "completion": "Variable balance ERC20 support"}
{"prompt": "uint256 constant BLOCK_PERIOD = 13 seconds;\n\n/// @dev Expiration delta for priority request to be satisfied (in seconds)\n", "completion": "BLOCK_PERIOD is incorrect"}
{"prompt": "function executeDiamondCutProposal(Diamond.DiamondCutData calldata _diamondCut) external onlyGovernor {\nDiamond.DiamondStorage storage diamondStorage = Diamond.getDiamondStorage();\n\nfunction _initializeDiamondCut(address _init, bytes memory _calldata) private {\nif (_init == address(0)) {\nrequire(_calldata.length == 0, \"H\"); // Non-empty calldata for zero address\n", "completion": "diamondCut is not protected in case of governor\u2019s key leakage"}
{"prompt": "\n// Creates the DelegationBoost\n", "completion": "Due to loss of precision, targetVotes may not reach"}
{"prompt": "function recoverERC20(address token) external onlyOwner returns(bool) {\nif(minAmountRewardToken[token] != 0) revert Errors.CannotRecoverToken();\n\n", "completion": "Owner can transfer all ERC20 reward token out using function recoverERC20"}
{"prompt": "contract WardenPledge is Ownable, Pausable, ReentrancyGuard {\nusing SafeERC20 for IERC20;\n\n", "completion": "WardenPledge accidentally inherits Ownable instead of Owner which removes an important safeguard without sponsor knowledge"}
{"prompt": "uint256 totalRewardAmount = (pledgeParams.rewardPerVote * pledgeParams.votesDifference * addedDuration) / UNIT;\nuint256 feeAmount = (totalRewardAmount * protocalFeeRatio) / MAX_PCT ;\nif(totalRewardAmount > maxTotalRewardAmount) revert Errors.IncorrectMaxTotalRewardAmount();\nuint256 totalRewardAmount = (rewardPerVoteDiff * pledgeParams.votesDifference * remainingDuration) / UNIT;\nuint256 feeAmount = (totalRewardAmount * protocalFeeRatio) / MAX_PCT ;\nif(totalRewardAmount > maxTotalRewardAmount) revert Errors.IncorrectMaxTotalRewardAmount();\n", "completion": "Reward can be over- or undercounted in extendPledge and increasePledgeRewardPerVote"}
{"prompt": "vars.feeAmount = (vars.totalRewardAmount * protocalFeeRatio) / MAX_PCT ;\nif(vars.totalRewardAmount > maxTotalRewardAmount) revert Errors.IncorrectMaxTotalRewardAmount();\nif(vars.feeAmount > maxFeeAmount) revert Errors.IncorrectMaxFeeAmount();\n", "completion": "Fees charged from entire theoretical pledge amount instead of actual pledge amount"}
{"prompt": "escrow.pay(to, amount);\nemit Withdraw(from, to, amount);\n}\n", "completion": "ERC777 reentrancy when withdrawing can be used to withdraw all collateral"}
{"prompt": "function repay(address user, uint amount) public {\nuint debt = debts[user];\nrequire(debt >= amount, \"Insufficient debt\");\n", "completion": "repay function can be DOSed"}
{"prompt": "uint day = block.timestamp / 1 days;\nuint todaysLow = dailyLows[token][day];\nif(todaysLow == 0 || normalizedPrice < todaysLow) {\n", "completion": "Oracle\u2019s two-day feature can be gamed"}
{"prompt": "function forceReplenish(address user, uint amount) public {\nuint deficit = dbr.deficitOf(user);\nrequire(deficit > 0, \"No DBR deficit\");\nfunction liquidate(address user, uint repaidDebt) public {\nrequire(repaidDebt > 0, \"Must repay positive debt\");\nuint debt = debts[user];\n", "completion": "Liquidation should make a borrower healthier"}
{"prompt": "dola.transfer(msg.sender, amount);\n}\n\ncollateral.transferFrom(msg.sender, address(escrow), amount);\nif(callOnDepositCallback) {\nescrow.onDeposit();\ndola.transfer(to, amount);\nemit Borrow(borrower, amount);\n}\ndola.transferFrom(msg.sender, address(this), amount);\nemit Repay(user, msg.sender, amount);\n}\ndola.transfer(msg.sender, replenisherReward);\nemit ForceReplenish(user, msg.sender, amount, replenishmentCost, replenisherReward);\n}\ndola.transferFrom(msg.sender, address(this), repaidDebt);\nIEscrow escrow = predictEscrow(user);\nescrow.pay(msg.sender, liquidatorReward);\n", "completion": "Unhandled return values of transfer and transferFrom"}
{"prompt": "uint accrued = (block.timestamp - lastUpdated[user]) * debt / 365 days;\ndueTokensAccrued[user] += accrued;\ntotalDueTokensAccrued += accrued;\n", "completion": "Users can avoid paying fees if they manage to update their accrued fees periodically"}
{"prompt": "require(collateralValue >= debts[user], \"Exceeded collateral value\");\ntotalDebt += replenishmentCost;\ndbr.onForceReplenish(user, amount);\n", "completion": "User can borrow DOLA indefinitely without settling DBR deficit by keeping their debt close to the allowed maximum"}
{"prompt": "uint liquidationFee = repaidDebt * 1 ether / price * liquidationFeeBps / 10000;\nif(escrow.balance() >= liquidationFee) {\nescrow.pay(gov, liquidationFee);\n}\n}\nemit Liquidate(user, msg.sender, repaidDebt, liquidatorReward);\n", "completion": "User can free from liquidation fee if its escrow balance is less than the calculated liquidation fee"}
{"prompt": "if(collateralFactorBps == 0) return 0;\nuint minimumCollateral = debt * 1 ether / oracle.getPrice(address(collateral), collateralFactorBps) * 10000 / collateralFactorBps;\nif(collateralBalance <= minimumCollateral) return 0;\nif(collateralFactorBps == 0) return 0;\nuint minimumCollateral = debt * 1 ether / oracle.viewPrice(address(collateral), collateralFactorBps) * 10000 / collateralFactorBps;\nif(collateralBalance <= minimumCollateral) return 0;\n", "completion": "Protocol withdrawals of collateral can be unexpectedly locked if governance sets the collateralFactorBps to 0"}
{"prompt": "escrow.onDeposit();\n}\nemit Deposit(user, amount);\n", "completion": "Avoidable misconfiguration could lead to INVEscrow contract not minting xINV tokens"}
{"prompt": "uint todaysLow = dailyLows[token][day];\n// get yesterday's low\nuint yesterdaysLow = dailyLows[token][day - 1];\n", "completion": "viewPrice doesn\u2019t always report dampened price"}
{"prompt": "uint collateralValue = getCollateralValueInternal(user);\nrequire(collateralValue >= debts[user], \"Exceeded collateral value\");\ntotalDebt += replenishmentCost;\n", "completion": "Users could get some DOLA even if they are on liquidation position"}
{"prompt": "require(deficit >= amount, \"Amount > deficit\");\nuint replenishmentCost = amount * dbr.replenishmentPriceBps() / 10000;\nuint replenisherReward = replenishmentCost * replenishmentIncentiveBps / 10000;\n", "completion": "Market::forceReplenish can be DoSed"}
{"prompt": "uint price = oracle.getPrice(address(collateral), collateralFactorBps);\nuint liquidatorReward = repaidDebt * 1 ether / price;\nliquidatorReward += liquidatorReward * liquidationIncentiveBps / 10000;\nrequire(getCreditLimitInternal(user) < debt, \"User debt is healthy\");\nrequire(repaidDebt <= debt * liquidationFactorBps / 10000, \"Exceeded liquidation factor\");\nuint price = oracle.getPrice(address(collateral), collateralFactorBps);\nuint liquidatorReward = repaidDebt * 1 ether / price;\nliquidatorReward += liquidatorReward * liquidationIncentiveBps / 10000;\ndebts[user] -= repaidDebt;\n", "completion": "Two day low oracle used in Market.liquidate() makes the system highly at risk in an oracle attack"}
{"prompt": "uint8 decimals = 36 - feedDecimals - tokenDecimals;\nuint normalizedPrice = price * (10 ** decimals);\nuint day = block.timestamp / 1 days;\nuint8 decimals = 36 - feedDecimals - tokenDecimals;\nuint normalizedPrice = price * (10 ** decimals);\n// potentially store price as today's low\n", "completion": "Oracle assumes token and feed decimals will be limited to 18 decimals"}
{"prompt": "require(gasleft() > gasLimit, \"HOLOGRAPH: not enough gas left\");\n/**\n * @dev execute the job\n", "completion": "An attacker can lock operator out of the pod by setting gas limit that\u2019s higher than the block gas limit of dest chain"}
{"prompt": "assembly {\n baseGas := sload(_baseGasSlot)\n}\n }\n\n /**\n * @notice Update the baseGas value\n * @param baseGas minimum gas amount that a message requires\n */\n function setBaseGas(uint256 baseGas) external onlyAdmin {\nassembly {\n sstore(_baseGasSlot, baseGas)\n}\n }\n\n", "completion": "LayerZeroModule miscalculates gas, risking loss of assets"}
{"prompt": "require(gasPrice >= tx.gasprice, \"HOLOGRAPH: gas spike detected\");\n/**\n * @dev check if time is within fallback operator slots\n", "completion": "MEV: Operator can bribe miner and steal honest operator\u2019s bond amount if gas price went high"}
{"prompt": "require(gasleft() > gasLimit, \"HOLOGRAPH: not enough gas left\");\n/**\n * @dev execute the job\n", "completion": "Gas limit check is inaccurate, leading to an operator being able to fail a job intentionally"}
{"prompt": "if (_storedTier.initialQuantity == _storedTier.remainingQuantity) return 1;\n\n// The number of reserved tokens of the tier already minted.\n", "completion": "Reserved token rounding can be abused to honeypot and steal user\u2019s funds"}
{"prompt": "_numberOfReservedTokensOutstandingFor(_nft, _i, _storedTier);\n\n unchecked {\n", "completion": "Redemption weight of tiered NFTs miscalculates, making users redeem incorrect amounts - Bug #1"}
{"prompt": "_tierToAdd.reservedTokenBeneficiary != defaultReservedTokenBeneficiaryOf[msg.sender]\n ) {\nif (_tierToAdd.shouldUseBeneficiaryAsDefault)\n", "completion": "Changing default reserved token beneficiary may result in wrong beneficiary for tier"}
{"prompt": " function recordMintReservesFor(uint256 _tierId, uint256 _count)\nexternal\noverride\n", "completion": "Deactivated tiers can still mint reserve tokens, even if no non-reserve tokens were minted."}
{"prompt": "require(gasPrice >= tx.gasprice, \"HOLOGRAPH: gas spike detected\");\n/**\n * @dev check if time is within fallback operator slots\n", "completion": "Gas price spikes cause the selected operator to be vulnerable to frontrunning and be slashed"}
{"prompt": "delete _operatorJobs[hash];\n/**\n * @dev check that a specific operator was selected for the job\n HolographOperatorInterface(address(this)).nonRevertingBridgeCall{value: msg.value}(\nmsg.sender,\nbridgeInRequestPayload\n )\n{\n /// @dev do nothing\n} catch {\n _failedJobs[hash] = true;\n emit FailedOperatorJob(hash);\n}\n/**\n", "completion": "Failed job can\u2019t be recovered. NFT may be lost."}
{"prompt": " function isOwner() external view returns (bool) {\nif (msg.sender == holographer()) {\n return msgSender() == _getOwner();\n modifier onlyOwner() {\nif (msg.sender == holographer()) {\n require(msgSender() == _getOwner(), \"ERC721: owner only function\");\n", "completion": "isOwner / onlyOwner checks can be bypassed by attacker in ERC721/ERC20 implementations"}
{"prompt": " require(erc20.transfer(addresses[i], sending), \"PA1D: Couldn't transfer token\");\n // sent = sent + sending;\n}\nrequire(erc20.transfer(addresses[i], sending), \"PA1D: Couldn't transfer token\");\n// sent = sent + sending;\n }\n", "completion": "_payoutToken[s]() is not compatible with tokens with missing return value"}
{"prompt": "require(gasPrice >= tx.gasprice, \"HOLOGRAPH: gas spike detected\");\n/**\n * @dev check if time is within fallback operator slots\n", "completion": "Beaming job might freeze on dest chain under some conditions, leading to owner losing (temporarily) access to token"}
{"prompt": " ERC721TokenReceiver(to).onERC721Received(address(this), from, tokenId, data) ==\n ERC721TokenReceiver.onERC721Received.selector),\n\"ERC721: onERC721Received fail\"\n", "completion": "Incorrect implementation of ERC721 may have bad consequences for receiver"}
{"prompt": " /**\n * @dev load and increment operator temp storage in one call\n */\n ++_operatorTempStorageCounter;\n /**\n * @dev use job hash, job nonce, block number, and block timestamp for generating a random number\n */\n uint256 random = uint256(keccak256(abi.encodePacked(jobHash, _jobNonce(), block.number, block.timestamp)));\n /**\n * @dev divide by total number of pods, use modulus/remainder\n */\n uint256 pod = random % _operatorPods.length;\n /**\n * @dev identify the total number of available operators in pod\n */\n uint256 podSize = _operatorPods[pod].length;\n /**\n * @dev select a primary operator\n */\n uint256 operatorIndex = random % podSize;\n /**\n", "completion": "Bad source of randomness"}
{"prompt": " _operatorPods.push([address(0)]);\n}\n }\n", "completion": "Attacker can force chaotic operator behavior"}
{"prompt": "balance = balance - gasCost;\nuint256 sending;\n// uint256 sent;\n sending = ((bps[i] * balance) / 10000);\n addresses[i].transfer(sending);\n // sent = sent + sending;\n", "completion": "_payoutEth() calculates balance with an offset, always leaving dust ETH in the contract"}
{"prompt": "require(_checkOnERC20Received(account, recipient, amount, data), \"ERC20: non ERC20Receiver\");\nif (_isEventRegistered(HolographERC20Event.afterSafeTransfer)) {\n require(SourceERC20().afterSafeTransfer(account, recipient, amount, data));\n", "completion": "HolographERC20 breaks composability by forcing usage of draft proposal EIP-4524"}
{"prompt": " function sourceBurn(uint256 tokenId) external onlySource {\naddress wallet = _tokenOwner[tokenId];\n_burn(wallet, tokenId);\n function sourceTransfer(address to, uint256 tokenId) external onlySource {\naddress wallet = _tokenOwner[tokenId];\n_transferFrom(wallet, to, tokenId);\n", "completion": "Source contract can steal NFTs from users"}
{"prompt": "/**\n * @dev select operator that failed to do the job, is slashed the pod base fee\n */\n_bondedAmounts[job.operator] -= amount;\n/**\n * @dev the slashed amount is sent to current operator\n */\n_bondedAmounts[msg.sender] += amount;\n/**\naddress operator,\nuint256 amount,\nuint256 pod\n ) external {\n/**\n * @dev an operator can only bond to one pod at any give time per network\n */\nrequire(_bondedOperators[operator] == 0 && _bondedAmounts[operator] == 0, \"HOLOGRAPH: operator is bonded\");\nunchecked {\n", "completion": "Bond tokens (HLG) can get permanently stuck in operator"}
{"prompt": " function unbondUtilityToken(address operator, address recipient) external {\n/**\n * @dev validate that operator is currently bonded\nuint256 amount = _bondedAmounts[operator];\n/**\n * @dev unset operator bond amount before making a transfer\n_bondedAmounts[operator] = 0;\n/**\n * @dev remove all operator references\n_popOperator(_bondedOperators[operator] - 1, _operatorPodIndex[operator]);\n/**\n * @dev transfer tokens to recipient\nrequire(_utilityToken().transfer(recipient, amount), \"HOLOGRAPH: token transfer failed\");\n }\n\n", "completion": "Implementation code does not align with the business requirement: Users are not charged with withdrawn fee when user unbound token in HolographOperator.sol"}
{"prompt": "// this information is outside of the scope of our\nbidShares.prevOwner.value = 0;\nbidShares.owner.value = 0;\nif (_getReceiver(tokenId) == address(0)) {\n bidShares.creator.value = _getDefaultBp();\n} else {\n bidShares.creator.value = _getBp(tokenId);\n}\nreturn bidShares;\n }\n\n", "completion": "PA1D#bidSharesForToken returns incorrect bidShares.creator.value"}
{"prompt": "(ERC165(to).supportsInterface(ERC165.supportsInterface.selector) &&\n ERC165(to).supportsInterface(ERC721TokenReceiver.onERC721Received.selector) &&\n ERC721TokenReceiver(to).onERC721Received(address(this), from, tokenId, data) ==\n", "completion": "HolographERC721.safeTransferFrom not compliant with EIP-721"}
{"prompt": " require(SourceERC721().afterApprovalAll(to, approved));\n}\n }\n", "completion": "ApprovalAll event is missing parameters"}
{"prompt": "/**\n * @dev select operator that failed to do the job, is slashed the pod base fee\n */\n_bondedAmounts[job.operator] -= amount;\n/**\n * @dev the slashed amount is sent to current operator\n */\n_bondedAmounts[msg.sender] += amount;\n/**\n", "completion": "Wrong slashing calculation rewards for operator that did not do his job"}
{"prompt": " receive() external payable {}\n\n /**\n", "completion": "Leak of value when interacting with an ERC721 enforcer contract"}
{"prompt": "require(_isApproved(msg.sender, tokenId), \"ERC721: not approved sender\");\nif (_isEventRegistered(HolographERC721Event.beforeApprove)) {\n require(SourceERC721().beforeApprove(tokenOwner, to, tokenId));\n", "completion": "HolographERC721.approve not EIP-721 compliant"}
{"prompt": "(_storedTier.contributionFloor *\n (_storedTier.initialQuantity - _storedTier.remainingQuantity)) +\n_numberOfReservedTokensOutstandingFor(_nft, _i, _storedTier);\n\n", "completion": "Outstanding reserved tokens are incorrectly counted in total redemption weight"}
{"prompt": "require(address(store) == address(0));\n\n// Initialize the sub class.\n", "completion": "Multiples initializations of JBTiered721Delegate"}
{"prompt": "while (_currentSortIndex != 0) {\n // Set the tier being iterated on. Tier's are 1 indexed.\n _storedTier = _storedTierOf[msg.sender][_currentSortIndex];\n", "completion": "Iterations over all tiers in recordMintBestAvailableTier can render system unusable"}
{"prompt": "else return;\n\n// Keep a reference to the amount of credits the beneficiary already has.\n", "completion": "NFT not minted when contributed via a supported payment terminal"}
{"prompt": " function _processPayment(JBDidPayData calldata _data) internal override {\n// Normalize the currency.\nuint256 _value;\n", "completion": "Beneficiary credit balance can unwillingly be used to mint low tier NFT"}
{"prompt": "if (_pricing.tiers.length > 0) _store.recordAddTiers(_pricing.tiers);\n\n// Set the flags if needed.\n function recordAddTiers(JB721TierParams[] memory _tiersToAdd)\nexternal\noverride\ncontributionFloor: uint80(_tierToAdd.contributionFloor),\nlockedUntil: uint48(_tierToAdd.lockedUntil),\nremainingQuantity: uint40(_tierToAdd.initialQuantity),\n", "completion": "The tier setting parameter are unsafely downcasted from type uint256 to type uint80 / uint48 / uint40 / uint16"}
{"prompt": "uint256 _fromBalance = _balances[_id][_from];\nif (_fromBalance < _amount) revert LBToken__TransferExceedsBalance(_from, _id, _amount);\n\nuint256 _toBalance = _balances[_id][_to];\n\nunchecked {\n_balances[_id][_from] = _fromBalance - _amount;\n_balances[_id][_to] = _toBalance + _amount;\n}\n\n", "completion": "Transfering funds to yourself increases your balance"}
{"prompt": "uint256 _amountOut = (_reserve1 * (_balance - _reserve0) * 997) / (_balance * 1_000);\n\nIJoePair(_pair).swap(0, _amountOut, _recipient, \"\");\nuint256 _amountOut = (_reserve0 * (_balance - _reserve1) * 997) / (_balance * 1_000);\n\nIJoePair(_pair).swap(_amountOut, 0, _recipient, \"\");\n", "completion": "Incorrect output amount calculation for Trader Joe V1 pools"}
{"prompt": "bytes32 _feeStorageSlot;\nassembly {\n_feeStorageSlot := sload(_feeParameters.slot)\n}\n\nuint256 _varParameters = _feeStorageSlot.decode(type(uint112).max, _OFFSET_VARIABLE_FEE_PARAMETERS);\nuint256 _newFeeParameters = _packedFeeParameters.decode(type(uint144).max, 0);\n\nassembly {\nsstore(_feeParameters.slot, or(_newFeeParameters, _varParameters))\n}\n}\n\n", "completion": "Wrong implementation of function LBPair.setFeeParameter can break the funcionality of LBPair and make user\u2019s tokens locked"}
{"prompt": "amountsIn[i - 1] = (_reserveIn * amountOut_ * 1_000) / (_reserveOut - amountOut_ * 997) + 1;\n} else {\n(amountsIn[i - 1], ) = getSwapIn(ILBPair(_pair), amountsIn[i], ILBPair(_pair).tokenX() == _token);\n", "completion": "Wrong calculation in function LBRouter._getAmountsIn make user lose a lot of tokens when swap through JoePair (most of them will gifted to JoePair freely)"}
{"prompt": "if (_from != address(0) && _from != address(this)) {\nuint256 _balanceFrom = balanceOf(_from, _id);\n\n_cacheFees(_bin, _from, _id, _balanceFrom, _balanceFrom - _amount);\n}\n\nif (_to != address(0) && _to != address(this)) {\nuint256 _balanceTo = balanceOf(_to, _id);\n\n_cacheFees(_bin, _to, _id, _balanceTo, _balanceTo + _amount);\n}\nfunction _mint(\naddress _account,\nuint256 _id,\n", "completion": "Attacker can steal entire reserves by abusing fee calculation"}
{"prompt": "(amountX, amountY) = _removeLiquidity(_LBPair, _amountXMin, _amountYMin, _ids, _amounts, _to);\n}\n\n", "completion": "LBRouter.removeLiquidity returning wrong values"}
{"prompt": "_beforeTokenTransfer(address(0), _account, _id, _amount);\n\nunchecked {\n", "completion": "beforeTokenTransfer called with wrong parameters in LBToken._burn"}
{"prompt": "_bins[_id].accTokenYPerShare += _feesY.getTokenPerShare(_totalSupply);\n\n", "completion": "Flashloan fee collection mechanism can be easily manipulated"}
{"prompt": "_fp.indexRef = uint24(_activeId);\nif (_deltaT < _fp.decayPeriod) {\nunchecked {\n// This can't overflow as `reductionFactor <= BASIS_POINT_MAX`\n_fp.volatilityReference = uint24(\n(uint256(_fp.reductionFactor) * _fp.volatilityAccumulated) / Constants.BASIS_POINT_MAX\n);\n}\n} else {\n_fp.volatilityReference = 0;\n}\n}\n\n_fp.time = (block.timestamp).safe40();\n\n", "completion": "Attacker can keep fees max at no cost"}
{"prompt": "\nif (_maxAmountInToBin + fees.total <= amountIn) {\namountInToBin = _maxAmountInToBin;\namountOutOfBin = _reserve;\n} else {\nfees = fp.getFeeAmountDistribution(fp.getFeeAmountFrom(amountIn));\namountInToBin = amountIn - fees.total;\n.getAmounts(_fp, _pair.activeId, _swapForY, _amountIn);\n\n_amountInWithFees = _amountInToBin + _fee;\n\n", "completion": "Incorrect fee calculation on LBPair (fees collected on swaps are less than what they \u201cshould\u201d be)"}
{"prompt": "_transferOwnership(msg.sender);\n}\n\n", "completion": "Very critical Owner privileges can cause complete destruction of the project in a possible privateKey exploit"}
{"prompt": "function initialize(address _controller) external onlyImpl {\nManaged._initialize(_controller);\n_paused = true;\nfunction initialize(address _owner) external onlyImpl {\nrequire(_owner != address(0), \"Owner must be set\");\n// Initial supply hard coded to 0 as tokens are only supposed\nfunction initialize(address _controller) external onlyImpl {\nManaged._initialize(_controller);\n_paused = true;\nfunction initialize(address _controller) external onlyImpl {\nManaged._initialize(_controller);\n}\n", "completion": "Initialize function in L2GraphToken.sol, BridgeEscrow.sol, L2GraphTokenGateway.sol, L1GraphTokenGateway.sol can be invoked multiple times from the implementation contract"}
{"prompt": "seqNum = sendTxToL2(\ninbox,\nl2Counterpart,\n", "completion": "If L1GraphTokenGateway\u2019s outboundTransfer is called by a contract, the entire msg.value is blackholed, whether the ticket got redeemed or not"}
{"prompt": "graphToken().approve(_spender, type(uint256).max);\n}\n\n", "completion": "Governor can rug pull the escrow"}
{"prompt": "msg.sender == AddressAliasHelper.applyL1ToL2Alias(l1Counterpart),\n\"ONLY_COUNTERPART_GATEWAY\"\n);\n", "completion": "After proposed 0.8.0 upgrade kicks in, L2 finalizeInboundTransfer might not work"}
{"prompt": "external\npure\noverride\nreturns (\nbool,\nuint256,\nuint256,\nuint256,\nAssetType\n)\n{\nreturn (\n(makerAsk.side != takerBid.side) &&\n(makerAsk.paymentToken == takerBid.paymentToken) &&\n(makerAsk.collection == takerBid.collection) &&\n(makerAsk.tokenId == takerBid.tokenId) &&\n(makerAsk.matchingPolicy == takerBid.matchingPolicy) &&\n(makerAsk.price == takerBid.price),\nmakerAsk.price,\nmakerAsk.tokenId,\n1,\nAssetType.ERC1155\n);\n}\n\nsell.order.collection,\nsell.order.trader,\nbuy.order.trader,\ntokenId,\namount,\nassetType\n);\n\n", "completion": "StandardPolicyERC1155.sol returns amount == 1 instead of amount == order.amount"}
{"prompt": "function transferERC20(address token, address from, address to, uint256 amount)\napprovedContract\nexternal\n", "completion": "Contract Owner Possesses Too Many Privileges"}
{"prompt": "uint256 shares,\naddress receiver,\nuint256 deadline,\nbool approveMax,\nuint8 v,\nbytes32 r,\nbytes32 s\n) external nonReentrant returns (uint256 assets) {\nuint256 amount = approveMax ? type(uint256).max : previewMint(shares);\nasset.permit(msg.sender, address(this), amount, deadline, v, r, s);\nreturn (mint(shares, receiver));\n}\n\n", "completion": "sfrxETH: The volatile result of previewMint() may prevent mintWithSignature from working"}
{"prompt": "if (block.timestamp >= rewardsCycleEnd) { syncRewards(); } \n}\n\n", "completion": "Wrong accounting logic when syncRewards() is called within beforeWithdraw makes withdrawals impossible"}
{"prompt": "function depositEther() external nonReentrant {\n// Initial pause check\nrequire(!depositEtherPaused, \"Depositing ETH is paused\");\n", "completion": "Frontrunning by malicious validator"}
{"prompt": "uint192 lastRewardAmount_ = lastRewardAmount;\nuint32 timestamp = block.timestamp.safeCastTo32();\n\nif (timestamp < rewardsCycleEnd) revert SyncError();\n\nuint256 storedTotalAssets_ = storedTotalAssets;\nuint256 nextRewards = asset.balanceOf(address(this)) - storedTotalAssets_ - lastRewardAmount_;\n\nstoredTotalAssets = storedTotalAssets_ + lastRewardAmount_; // SSTORE\n\nuint32 end = ((timestamp + rewardsCycleLength) / rewardsCycleLength) * rewardsCycleLength;\n\n// Combined single SSTORE\nlastRewardAmount = nextRewards.safeCastTo192();\nlastSync = timestamp;\nrewardsCycleEnd = end;\n\nemit NewRewardsCycle(end, nextRewards);\n}\n}\n", "completion": "Rewards delay release could cause yields steal and loss"}
{"prompt": "contract frxETH is ERC20PermitPermissionedMint {\n\n/* ========== CONSTRUCTOR ========== */\n", "completion": "frxETH can be depegged due to ETH staking balance slashing"}
{"prompt": "for (uint256 i = 0; i < original_validators.length; ++i) {\nif (i != remove_idx) {\nvalidators.push(original_validators[i]);\n}\n}\n}\nif (minters_array[i] == minter_address) {\nminters_array[i] = address(0); // This will leave a null in the array and keep the indices the same\nbreak;\n}\n}\n\n", "completion": "removeValidator() and removeMinter() may fail due to exceeding gas limit"}
{"prompt": "for (uint256 i = 0; i < numDeposits; ++i) {\n// Get validator information\n(\n", "completion": "frxETHMinter.depositEther may run out of gas, leading to lost ETH"}
{"prompt": "require(IERC20(tokenAddress).transfer(owner, tokenAmount), \"recoverERC20: Transfer failed\");\n\nemit EmergencyERC20Recovered(tokenAddress, tokenAmount);\n", "completion": "frxETHMinter: Non-conforming ERC20 tokens not recoverable"}
{"prompt": "// Get validator information\n(\nbytes memory pubKey,\nbytes memory withdrawalCredential,\nbytes memory signature,\nbytes32 depositDataRoot\n) = getNextValidator(); // Will revert if there are not enough free validators\n\n// Make sure the validator hasn't been deposited into already, to prevent stranding an extra 32 eth\n// until withdrawals are allowed\nrequire(!activeValidators[pubKey], \"Validator already has 32 ETH\");\n\n// Deposit the ether in the ETH 2.0 deposit contract\ndepositContract.deposit{value: DEPOSIT_SIZE}(\npubKey,\nwithdrawalCredential,\nsignature,\ndepositDataRoot\n);\n\n// Set the validator as used so it won't get an extra 32 ETH\nactiveValidators[pubKey] = true;\n\nemit DepositSent(pubKey, withdrawalCredential);\n}\n}\n\n", "completion": "getNextValidator() error could temporarily make depositEther() inoperable"}
{"prompt": "require(amount <= currentWithheldETH, \"Not enough withheld ETH in contract\");\ncurrentWithheldETH -= amount;\n\n(bool success,) = payable(to).call{ value: amount }(\"\");\nrequire(success, \"Invalid transfer\");\n\nemit WithheldETHMoved(to, amount);\n}\n\n(bool success,) = address(owner).call{ value: amount }(\"\");\nrequire(success, \"Invalid transfer\");\n\nemit EmergencyEtherRecovered(amount);\n}\n\n_submit(msg.sender);\n}\n\n", "completion": "Withheld ETH shoud not be sent back to the frxETHMinter contract itself"}
{"prompt": "(bool success,) = address(owner).call{ value: amount }(\"\");\nrequire(success, \"Invalid transfer\");\n\nemit EmergencyEtherRecovered(amount);\n}\n\n", "completion": "recoverEther not updating currentWithheldETH breaks calculation of withheld amount for further deposits"}
{"prompt": "function revokeClaim(address _recipient) external onlyAdmin hasActiveClaim(_recipient) {\n// Fetch the claim\nClaim storage _claim = claims[_recipient];\nuint112 vestAmt = 0;\n\n// the condition to have anything vested is to be active\nif(_claim.isActive) {\n// no point of looking past the endTimestamp as nothing should vest afterwards\nfunction withdraw() hasActiveClaim(_msgSender()) external {\n// Get the message sender claim - if any\n\n", "completion": "Loss of vested amounts"}
{"prompt": "// truncatedCurrentVestingDurationSecs / finalVestingDurationSecs * linearVestAmount, so we can rewrite as below to avoid \n// rounding errors\nuint112 linearVestAmount = _claim.linearVestAmount * truncatedCurrentVestingDurationSecs / finalVestingDurationSecs;\n", "completion": "Tokens with lower number of decimals can result in postponed linear vesting for user"}
{"prompt": "uint112 linearVestAmount = _claim.linearVestAmount * truncatedCurrentVestingDurationSecs / finalVestingDurationSecs;\n\n// Having calculated the linearVestAmount, simply add it to the vested amount\n", "completion": "Permanent freeze of vested tokens due to overflow in _baseVestedAmount"}
{"prompt": "require(account != address(0), \"INVALID_ADDRESS\");\n// If we're using maxSupply, we need to make sure we respect it\n// mintableSupply = 0 means mint at will\nif(mintableSupply > 0) {\nrequire(amount <= mintableSupply, \"INVALID_AMOUNT\");\n// We need to reduce the amount only if we're using the limit, if not just leave it be\nmintableSupply -= amount;\n}\n_mint(account, amount);\n}\n\n", "completion": "Supply cap of VariableSupplyERC20Token is not properly enforced"}
{"prompt": "// Rationale: no matter how we calculate the vestAmt, we can never return that less was vested than was already withdrawn.\n// Case where this could be relevant - If the claim is inactive, vestAmt would be 0, yet if something was already withdrawn \n// on that claim, we want to return that as vested thus far - as we want the function to be monotonic.\nreturn (vestAmt > _claim.amountWithdrawn) ? vestAmt : _claim.amountWithdrawn;\n}\nreturn _baseVestedAmount(_claim, _referenceTs);\n}\n\n", "completion": "_baseVestedAmount() and vestedAmount() Return Incorrect Historical Values"}
{"prompt": "return vestingRecipients;\n}\n\nfunction _createClaimUnchecked(\naddress _recipient, \nuint40 _startTimestamp, \nvestingRecipients.push(_recipient); // add the vesting recipient to the list\nemit ClaimCreated(_recipient, _claim); // let everyone know\n}\nfunction createClaim(\naddress _recipient, \nuint40 _startTimestamp, \n", "completion": "Possible DoS on vestingRecipients due to lack of disposal mechanism"}
{"prompt": "require(tokenAddress.balanceOf(address(this)) >= numTokensReservedForVesting + allocatedAmount, \"INSUFFICIENT_BALANCE\");\n\n// Done with checks\ntokenAddress.safeTransfer(_msgSender(), amountRemaining);\n\n// Let withdrawal known to everyone.\n", "completion": "Variable balance token causing fund lock and loss"}
{"prompt": "require(_otherTokenAddress != tokenAddress, \"INVALID_TOKEN\"); // tokenAddress address is already sure to be nonzero due to constructor\nuint256 bal = _otherTokenAddress.balanceOf(address(this));\nrequire(bal > 0, \"INSUFFICIENT_BALANCE\");\n_otherTokenAddress.safeTransfer(_msgSender(), bal);\n}\n}\n", "completion": "Two address tokens can be withdrawn by the admin even if they are vested"}
{"prompt": "@notice Admin withdrawal of the unallocated tokens.\n@param _amountRequested - the amount that we want to withdraw\n */\nfunction withdrawAdmin(uint112 _amountRequested) public onlyAdmin {\n// Allow the owner to withdraw any balance not currently tied up in contracts.\nuint256 amountRemaining = tokenAddress.balanceOf(address(this)) - numTokensReservedForVesting;\n\nrequire(amountRemaining >= _amountRequested, \"INSUFFICIENT_BALANCE\");\n\n// Actually withdraw the tokens\n// Reentrancy note - this operation doesn't touch any of the internal vars, simply transfers\n// Also following Checks-effects-interactions pattern\ntokenAddress.safeTransfer(_msgSender(), _amountRequested);\n\n// Let the withdrawal known to everyone\nemit AdminWithdrawn(_msgSender(), _amountRequested);\n}\n\n", "completion": "Reentrancy may allow an admin to steal funds"}
{"prompt": "for (uint256 i = 0; i < cost; ++i) {\nid = gobblerIds[i];\n\nmsg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id],\n\"NOT_AUTHORIZED\"\n);\n", "completion": "Can Recover Gobblers Burnt In Legendary Mint"}
{"prompt": "// Revert if waiting for seed, so we don't interrupt requests in flight.\nif (gobblerRevealsData.waitingForSeed) revert SeedPending();\n\nrandProvider = newRandProvider; // Update the randomness provider.\n\nemit RandProviderUpgraded(msg.sender, newRandProvider);\n}\n\n", "completion": "Possible centralization issue around RandProvider"}
{"prompt": "\n/// @notice Callback from rand provider. Sets randomSeed. Can only be called by the rand provider.\n/// @param randomness The 256 bits of verifiable randomness provided by the rand provider.\n", "completion": "The reveal process could brick if randProvider stops working"}
{"prompt": "getUserData[msg.sender].gobblersOwned = uint32(getUserData[msg.sender].gobblersOwned - cost + 1);\n\n// New start price is the max of LEGENDARY_GOBBLER_INITIAL_START_PRICE and cost * 2.\n", "completion": "Wrong balanceOf user after minting legendary gobbler"}
{"prompt": "public\nview\nreturns (\nuint80 roundID,\nint256 nowPrice,\nuint256 startedAt,\nuint256 timeStamp,\nuint80 answeredInRound\n)\n{\n(\nuint80 roundID1,\nint256 price1,\nuint256 startedAt1,\nuint256 timeStamp1,\nuint80 answeredInRound1\n) = priceFeed1.latestRoundData();\n\nint256 price2 = getOracle2_Price();\n\nif (price1 > price2) {\nnowPrice = (price2 * 10000) / price1;\n} else {\nnowPrice = (price1 * 10000) / price2;\n}\n\nint256 decimals10 = int256(10**(18 - priceFeed1.decimals()));\nnowPrice = nowPrice * decimals10;\n\nreturn (\nroundID1,\nnowPrice / 1000000,\nstartedAt1,\ntimeStamp1,\nansweredInRound1\n);\n}\n\nprice = price * int256(decimals);\n\n", "completion": "Incorrect handling of pricefeed.decimals()"}
{"prompt": "public\nview\nreturns (\nuint80 roundID,\nint256 nowPrice,\nuint256 startedAt,\nuint256 timeStamp,\nuint80 answeredInRound\n)\n{\n(\nuint80 roundID1,\nint256 price1,\nuint256 startedAt1,\nuint256 timeStamp1,\nuint80 answeredInRound1\n) = priceFeed1.latestRoundData();\n\nint256 price2 = getOracle2_Price();\n\nif (price1 > price2) {\nnowPrice = (price2 * 10000) / price1;\n} else {\nnowPrice = (price1 * 10000) / price2;\n}\n\nint256 decimals10 = int256(10**(18 - priceFeed1.decimals()));\nnowPrice = nowPrice * decimals10;\n\nreturn (\nroundID1,\nnowPrice / 1000000,\nstartedAt1,\ntimeStamp1,\nansweredInRound1\n);\n}\n\n", "completion": "Risk users are required to payout if the price of the pegged asset goes higher than underlying"}
{"prompt": "public\nview\noverride\nmarketExists(_id)\nreturns (uint256)\n{\nreturn totalSupply(_id);\n}\n\npublic\nview\nvirtual\nreturns (uint256)\n{\nuint256 supply = totalSupply(id); // Saves an extra SLOAD if totalSupply is non-zero.\n\nreturn supply == 0 ? assets : assets.mulDivUp(supply, totalAssets(id));\n}\nreturn type(uint256).max;\n}\n\nreturn type(uint256).max;\n}\n\npublic\nview\nvirtual\nreturns (uint256)\n{\nreturn convertToAssets(id, balanceOf(owner, id));\n}\n\npublic\nview\nvirtual\nreturns (uint256)\n{\nreturn balanceOf(owner, id);\n}\n\n", "completion": "Vault.sol is not EIP-4626 compliant"}
{"prompt": "external\nnonReentrant\nwhenNotPaused\nupdateReward(msg.sender)\n{\nrequire(amount != 0, \"Cannot stake 0\");\n_totalSupply = _totalSupply.add(amount);\n_balances[msg.sender] = _balances[msg.sender].add(amount);\nstakingToken.safeTransferFrom(\nmsg.sender,\naddress(this),\nid,\namount,\n\"\"\n);\nemit Staked(msg.sender, id, amount);\n}\n\n", "completion": "StakingRewards.sol#stake is intended to be pausable but isn\u2019t"}
{"prompt": "uint256 id,\nuint256 assets,\naddress receiver,\naddress owner\n)\nexternal\noverride\nepochHasEnded(id)\nmarketExists(id)\nreturns (uint256 shares)\n{\nif(\nmsg.sender != owner &&\nisApprovedForAll(owner, receiver) == false)\nrevert OwnerDidNotAuthorize(msg.sender, owner);\n\nshares = previewWithdraw(id, assets); // No need to check for rounding error, previewWithdraw rounds up.\n\nuint256 entitledShares = beforeWithdraw(id, shares);\n_burn(owner, id, shares);\n\n//Taking fee from the amount\nuint256 feeValue = calculateWithdrawalFeeValue(entitledShares, id);\nentitledShares = entitledShares - feeValue;\nasset.transfer(treasury, feeValue);\n\nemit Withdraw(msg.sender, receiver, owner, id, assets, entitledShares);\nasset.transfer(receiver, entitledShares);\n\nreturn entitledShares;\n}\n\n", "completion": "Fees are taken on risk collateral"}
{"prompt": "function triggerEndEpoch(uint256 marketIndex, uint256 epochEnd) public {\nif(\nvaultFactory.getVaults(marketIndex).length != VAULTS_LENGTH)\ngetLatestPrice(insrVault.tokenInsured())\n);\n}\nfunction getLatestPrice(address _token)\npublic\nview\nif (!isSequencerUp) {\nrevert SequencerDown();\n}\n\n// Make sure the grace period has passed after the sequencer is back up.\nuint256 timeSinceUp = block.timestamp - startedAt;\nif (timeSinceUp <= GRACE_PERIOD_TIME) {\nrevert GracePeriodNotOver();\n}\n\nfunction withdraw(\nuint256 id,\nuint256 assets,\n", "completion": "End epoch cannot be triggered preventing winners to withdraw"}
{"prompt": "nowPrice = (price2 * 10000) / price1;\n} else {\nnowPrice = (price1 * 10000) / price2;\n}\n\n", "completion": "A design flaw in the case of using 2 oracles (aka PegOracle)"}
{"prompt": "public\nview\nreturns (\nuint80 roundID,\nint256 nowPrice,\nuint256 startedAt,\nuint256 timeStamp,\nuint80 answeredInRound\n)\n{\n(\nuint80 roundID1,\nint256 price1,\nuint256 startedAt1,\nuint256 timeStamp1,\nuint80 answeredInRound1\n) = priceFeed1.latestRoundData();\n\nint256 price2 = getOracle2_Price();\n\nif (price1 > price2) {\nnowPrice = (price2 * 10000) / price1;\n} else {\nnowPrice = (price1 * 10000) / price2;\n}\n\nint256 decimals10 = int256(10**(18 - priceFeed1.decimals()));\nnowPrice = nowPrice * decimals10;\n\nreturn (\nroundID1,\nnowPrice / 1000000,\nstartedAt1,\ntimeStamp1,\nansweredInRound1\n);\n}\n\n", "completion": "LOSS OF PRECISION RESULTING IN WRONG VALUE FOR PRICE RATIO"}
{"prompt": "uint256 id,\nuint256 assets,\naddress receiver,\naddress owner\n) external virtual returns (uint256 shares) {\nrequire(\nmsg.sender == owner || isApprovedForAll(owner, receiver),\n\"Only owner can withdraw, or owner has approved receiver for all\"\n);\n\nuint256 id,\nuint256 assets,\naddress receiver,\naddress owner\n)\nexternal\noverride\nepochHasEnded(id)\nmarketExists(id)\nreturns (uint256 shares)\n{\nif(\nmsg.sender != owner &&\nisApprovedForAll(owner, receiver) == false)\nrevert OwnerDidNotAuthorize(msg.sender, owner);\n\n", "completion": "Griefing attack on the Vaults is possible, withdrawing the winning side stakes"}
{"prompt": "if(\nvault.strikePrice() < getLatestPrice(vault.tokenInsured())\n)\n", "completion": "Depeg event can happen at incorrect price"}
{"prompt": "mapping(address => address) public tokenToOracle; //token address to respective oracle smart contract address\n\n/*//////////////////////////////////////////////////////////////\ntokenToOracle[_token] = _oracle;\n}\n\n", "completion": "Oracle is tracked per token instead of per pair, leading to surprise results"}
{"prompt": "asset.safeTransferFrom(msg.sender, address(this), assets);\n\n_mint(receiver, id, shares, EMPTY);\ninsrVault.sendTokens(epochEnd, address(riskVault));\nriskVault.sendTokens(epochEnd, address(insrVault));\n\ninsrVault.sendTokens(epochEnd, address(riskVault));\n\nVaultTVL memory tvl = VaultTVL(\n", "completion": "Fee-on-Transfer tokens cause problems in multiple places"}
{"prompt": "rewardRate = reward.add(leftover).div(rewardsDuration);\n}\n\n", "completion": "StakingRewards: Significant loss of precision possible"}
{"prompt": "if(block.timestamp > idEpochBegin[id] - timewindow)\nrevert EpochAlreadyStarted();\n_;\n}\n\nuint256 id,\nuint256 assets,\naddress receiver\n)\npublic\noverride\nmarketExists(id)\nepochHasNotStarted(id)\nnonReentrant\nreturns (uint256 shares)\n{\n// Check for rounding error since we round down in previewDeposit.\nrequire((shares = previewDeposit(id, assets)) != 0, \"ZeroValue\");\n\nasset.transferFrom(msg.sender, address(this), shares);\n\n_mint(receiver, id, shares, EMPTY);\n\nemit Deposit(msg.sender, receiver, id, shares, shares);\n\nreturn shares;\n}\n\npublic\nonlyAdmin\n{\naddress[] memory vaults = indexVaults[_marketIndex];\nVault insr = Vault(vaults[0]);\nVault risk = Vault(vaults[1]);\ninsr.changeTimewindow(_timewindow);\nrisk.changeTimewindow(_timewindow);\n\nemit changedTimeWindow(_marketIndex, _timewindow);\n}\n\ntimewindow = _timewindow;\n}\n\n", "completion": "timewindow can be changed unexpectedly that blocks users from calling deposit function"}
{"prompt": "external\nonlyOwner\n{\nrequire(\ntokenAddress != address(stakingToken),\n\"Cannot withdraw the staking token\"\n);\nERC20(tokenAddress).safeTransfer(owner, tokenAmount);\nemit Recovered(tokenAddress, tokenAmount);\n}\n\n", "completion": "StakingRewards: recoverERC20() can be used as a backdoor by the owner to retrieve rewardsToken"}
{"prompt": "require(\nrewardRate <= balance.div(rewardsDuration),\n\"Provided reward too high\"\n);\n\n", "completion": "StakingRewards.sol#notifyRewardAmount() Improper reward balance checks can make some users unable to withdraw their rewards"}
{"prompt": "external\noverride\nonlyRewardsDistribution\nupdateReward(address(0))\n{\nif (block.timestamp >= periodFinish) {\nrewardRate = reward.div(rewardsDuration);\n} else {\nuint256 remaining = periodFinish.sub(block.timestamp);\nuint256 leftover = remaining.mul(rewardRate);\nrewardRate = reward.add(leftover).div(rewardsDuration);\n}\n\n", "completion": "StakingRewards reward rate can be dragged out and diluted"}
{"prompt": "insrVault.setClaimTVL(epochEnd, 0);\nriskVault.setClaimTVL(epochEnd, insrVault.idFinalTVL(epochEnd));\ninsrVault.sendTokens(epochEnd, address(riskVault));\n", "completion": "After the vault expires, users may still receive rewards through the StakingRewards contract"}
{"prompt": ") = priceFeed1.latestRoundData();\n\nint256 price2 = getOracle2_Price();\nif(timeStamp == 0)\nrevert TimestampZero();\n\nrequire(timeStamp2 != 0, \"Timestamp == 0 !\");\n\nreturn price2;\n", "completion": "Different Oracle issues can return outdated prices"}
{"prompt": "public\nonlyAdmin\n{\nif(_controller == address(0))\nrevert AddressZero();\n\naddress[] memory vaults = indexVaults[_marketIndex];\nVault insr = Vault(vaults[0]);\nVault risk = Vault(vaults[1]);\ninsr.changeController(_controller);\nrisk.changeController(_controller);\n\nemit changedController(_marketIndex, _controller);\n}\n\nvaultFactory = VaultFactory(_factory);\nsequencerUptimeFeed = AggregatorV2V3Interface(_l2Sequencer);\n}\naddress[] memory vaultsAddress = vaultFactory.getVaults(marketIndex);\nVault insrVault = Vault(vaultsAddress[0]);\nVault riskVault = Vault(vaultsAddress[1]);\nIController(controller).getVaultFactory() != address(this)\n)\nrevert AddressFactoryNotInController();\n\n", "completion": "It\u2019s possible to change for Vault and lost control on it"}
{"prompt": "function notifyRewardAmount(uint256 reward)\nexternal\noverride\n", "completion": "Rewards are not rolled over"}
{"prompt": "function changeController(address _controller) public onlyFactory {\nif(_controller == address(0))\nrevert AddressZero();\npublic\nonlyController\nmarketExists(id)\n{\nasset.transfer(_counterparty, idFinalTVL[id]);\n}\n\n", "completion": "function changeController() has rug potential as admin can unilaterally withdraw all user funds from both risk and insure vaults"}
{"prompt": "external\nonlyDelegateCall\n{\n// Must be a valid proposal ID.\nif (proposalId == 0) {\nrevert ZeroProposalIdError();\n}\nStorage storage stor = _getStorage();\n{\n// Must be the current InProgress proposal.\nuint256 currentInProgressProposalId = stor.currentInProgressProposalId;\nif (currentInProgressProposalId != proposalId) {\nrevert ProposalNotInProgressError(proposalId);\n}\n}\n// Clear the current InProgress proposal ID and next progress data.\nstor.currentInProgressProposalId = 0;\nstor.nextProgressDataHash = 0;\n}\n\n", "completion": "ArbitraryCallsProposal.sol and ListOnOpenseaProposal.sol safeguards can be bypassed by cancelling in-progress proposal allowing the majority to steal NFT"}
{"prompt": "address payable callTarget,\nuint96 callValue,\nbytes calldata callData,\nFixedGovernanceOpts memory governanceOpts\n)\nexternal\nreturns (Party party_)\n{\nreturn _buy(\nnftContract,\nnftTokenId,\ncallTarget,\ncallValue,\ncallData,\ngovernanceOpts\n);\n}\n}\n\n", "completion": "Attacker can DOS private party by donating ETH then calling buy"}
{"prompt": "uint96 votingPower = getVotingPowerAt(msg.sender, values.proposedTime, snapIndex);\nvalues.votes += votingPower;\ninfo.values = values;\n", "completion": "PartyGovernance: Can vote multiple times by transferring NFT in same block as proposal"}
{"prompt": "// Check whether auction cancelled due to a failed transfer during\n// settlement by seeing if we now possess the NFT.\nif (token.safeOwnerOf(tokenId) == address(this)) {\nemit ZoraAuctionFailed(auctionId);\nreturn false;\n}\n} catch (bytes memory errData) {\nbytes32 errHash = keccak256(errData);\n", "completion": "A majority attack can easily bypass Zora auction stage in OpenseaProposal and steal the NFT from the party."}
{"prompt": "function executeProposal(ExecuteProposalParams memory params)\nexternal\nonlyDelegateCall\nIERC721(address(this)).name(),\nIERC721(address(this)).symbol(),\ndata.token,\ndata.tokenId,\nsupply,\ndata.listPrice,\n0\n);\n// Get the vault we just created.\n", "completion": "A majority attack can steal precious NFT from the party by crafting and chaining two proposals"}
{"prompt": "revert MaximumPriceError(callValue, maximumPrice);\n}\n", "completion": "Attacker can list an NFT they own and inflate to zero all users\u2019 contributions, keeping the NFT and all the money"}
{"prompt": "revert AlreadyHighestBidderError();\n}\n", "completion": "Attacker can force AuctionCrowdfunds to bid their entire contribution up to maxBid"}
{"prompt": "{\nuint96 maximumPrice_ = maximumPrice;\nif (maximumPrice_ != 0 && callValue > maximumPrice_) {\nrevert MaximumPriceError(callValue, maximumPrice);\n}\n// If the purchase would be free, set the settled price to\n// `totalContributions` so everybody who contributed wins.\nsettledPrice_ = callValue == 0 ? totalContributions : callValue;\nif (settledPrice_ == 0) {\n// Still zero, which means no contributions.\nrevert NoContributionsError();\n}\nsettledPrice = settledPrice_;\n}\n{\n// Execute the call to buy the NFT.\n(bool s, bytes memory r) = callTarget.call{ value: callValue }(callData);\nif (!s) {\nr.rawRevert();\n}\n}\n// Make sure we acquired the NFT we want.\n", "completion": "Early contributor can always become majority of crowdfund leading to rugging risks."}
{"prompt": "_contribute(opts.initialContributor, initialBalance, opts.initialDelegate, 0, \"\");\n}\n// Set up gatekeeper after initial contribution (initial always gets in).\n", "completion": "Possibility to burn all ETH in Crowdfund under some circumstances"}
{"prompt": "currentTokenBalance: token.balanceOf(address(this)),\nfeeRecipient: feeRecipient,\nfeeBps: feeBps\nIERC20(token).compatTransfer(recipient, amount);\n}\n}\n", "completion": "TokenDistributor: ERC777 tokensToSend hook can be exploited to drain contract"}
{"prompt": "public\n{\nreturn _burn(contributor, getCrowdfundLifecycle(), party);\n}\n\n", "completion": "Previously nominated delegate can reset the delegation"}
{"prompt": "bytes16 governanceOptsHash_ = _hashFixedGovernanceOpts(governanceOpts);\nif (governanceOptsHash_ != governanceOptsHash) {\nrevert InvalidGovernanceOptionsError(governanceOptsHash_, governanceOptsHash);\nreturns (bytes16 h)\n{\n// Hash in place.\nbytes15 distributionHash15;\n// Whether the distribution's feeRecipient has claimed its fee.\nbool wasFeeClaimed;\n", "completion": "Only part of keccak256() is used as hash, making it susceptible to collision attacks"}
{"prompt": "lastBid_ = totalContributions;\nif (lastBid_ == 0) {\n// Nobody ever contributed. The NFT is effectively burned.\n", "completion": "NFT Owner can stuck Crowdfund user funds"}
{"prompt": "settledPrice_ = callValue == 0 ? totalContributions : callValue;\nif (settledPrice_ == 0) {\n// Still zero, which means no contributions.\n", "completion": "The settledPrice maybe exceed maximumPrice"}
{"prompt": "if (lastBid_ == 0) {\n// The NFT was gifted to us. Everyone who contributed wins.\nlastBid_ = totalContributions;\nif (lastBid_ == 0) {\n// Nobody ever contributed. The NFT is effectively burned.\nrevert NoContributionsError();\n}\nlastBid = lastBid_;\n}\n// Create a governance party around the NFT.\n", "completion": "AuctionCrowdfund: If the contract was bid on before the NFT was gifted to the contract, lastBid will not be totalContributions"}
{"prompt": "votingPower = ((1e4 - splitBps_) * ethUsed) / 1e4;\nif (splitRecipient_ == contributor) {\n// Split recipient is also the contributor so just add the split\nreturn acceptanceRatio >= 0.9999e4;\n}\n\n", "completion": "Possible that unanimous votes is unachievable"}
{"prompt": "function bid() external onlyDelegateCall {\n// Check that the auction is still active.\n{\n", "completion": "Maximum bid will always be used in Auction"}
{"prompt": "ethAvailable -= calls[i].value;\nemit ArbitraryCallExecuted(params.proposalId, i, calls.length);\n}\n", "completion": "Excess eth is not refunded"}
{"prompt": "public\nview\nreturns (address[] memory tokens, uint256[] memory amountsOut)\n{\ntokens = tokensReceivedOnRedeem();\namountsOut = new uint256[](tokens.length);\n\nuint256 base = redeemBase;\nfor (uint256 i = 0; i < tokensReceived.length; i++) {\nuint256 balance = IERC20(tokensReceived[i]).balanceOf(address(this));\nrequire(balance != 0, \"ZERO_BALANCE\");\n// @dev, this assumes all of `tokensReceived` and `redeemedToken`\n// have the same number of decimals\nuint256 redeemedAmount = (amountIn * balance) / base;\namountsOut[i] = redeemedAmount;\n}\n}\n\n", "completion": "A malicious user can send tokens to the TribeRedeemer contract to make the redeem function work, and other users may lose assets as a result"}
{"prompt": "uint256 redeemedAmount = (amountIn * balance) / base;\namountsOut[i] = redeemedAmount;\n}\nredeemBase = base - amountIn; // decrement the base for future redemptions\nfor (uint256 i = 0; i < tokens.length; i++) {\nIERC20(tokens[i]).safeTransfer(to, amountsOut[i]);\n", "completion": "TribeRedeemer will start redeeming incorrectly if someone transfer redeem tokens directly to it"}
{"prompt": "uint decimals = erc20(underlying).decimals();\nreturn 1e18 * 1e18 / (10 ** decimals); //Scale Price as a mantissa to maintain precision in comptroller\n} \nelse if (compareStrings(symbol, \"cUSDC\") && (msg.sender == Comptroller)) {\nuint decimals = erc20(underlying).decimals();\nreturn 1e18 * 1e18 / (10 ** decimals); //Scale Price as a mantissa to maintain precision in comptroller\n}\n}\n", "completion": "Hardcoded USD pegs can be broken"}
{"prompt": "require(msg.sender == admin);\nrequire(newPeriod <= MaxPeriod);\n\nfor (uint i; i < allPairs.length; ) {\nBaseV1Pair(allPairs[i]).setPeriodSize(newPeriod);\nunchecked {++i;}\n}\n}\n\n", "completion": "unbounded loop length dos"}
{"prompt": "uint token0TVL = assetReserves[i] * (prices[i] / decimals);\nuint token1TVL = unitReserves[i]; // price of the unit asset is always 1\nLpPricesCumulative += (token0TVL + token1TVL) * 1e18 / supply[i];\n", "completion": "Calculated token0TVL may be zero under certain scenarios"}
{"prompt": "function createPair(address tokenA, address tokenB, bool stable) external returns (address pair) {\nrequire(tokenA != tokenB, \"IA\"); // BaseV1: IDENTICAL_ADDRESSES\n(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n", "completion": "Period Size not updated on creating new Pair"}
{"prompt": "checkpoint.timestamp = uint64(block.timestamp);\n\n", "completion": "Multiple vote checkpoints per block will lead to incorrect vote accounting"}
{"prompt": "// Get the previous delegate\naddress prevDelegate = delegation[_from];\n\n// Store the new delegate\ndelegation[_from] = _to;\n\nemit DelegateChanged(_from, prevDelegate, _to);\n\n// Transfer voting weight from the previous delegate to the new delegate\n_moveDelegateVotes(prevDelegate, _to, balanceOf(_from));\n}\n\n", "completion": "NFT owner can block token burning and transfer by delegating to zero address"}
{"prompt": "settings.vetoer = _vetoer;\nsettings.votingDelay = SafeCast.toUint48(_votingDelay);\nsettings.votingPeriod = SafeCast.toUint48(_votingPeriod);\nif (_newVetoer == address(0)) revert ADDRESS_ZERO();\n\nemit VetoerUpdated(settings.vetoer, _newVetoer);\n\nsettings.vetoer = _newVetoer;\n}\n\n", "completion": "Loss of Veto Power can Lead to 51% Attack"}
{"prompt": "_moveDelegateVotes(_from, _to, 1);\n\nsuper._afterTokenTransfer(_from, _to, _tokenId);\n", "completion": "User can get unlimited votes"}
{"prompt": "address _from,\naddress _to,\nuint256 _tokenId\n) internal override {\n// Transfer 1 vote from the sender to the recipient\n_moveDelegateVotes(_from, _to, 1);\n\n", "completion": "ERC721Votes\u2019s delegation disables NFT transfers and burning"}
{"prompt": "_moveDelegateVotes(_from, _to, 1);\n\nsuper._afterTokenTransfer(_from, _to, _tokenId);\n", "completion": "_transferFrom() can be used to indefinitely increase voting power"}
{"prompt": "// Transfer ownership of the contract to the DAO\ntransferOwnership(settings.treasury);\n\n// Start the first auction\n_createAuction();\n}\n// Else if the contract was paused and the previous auction was settled:\n", "completion": "Highest bid in first auction can get irretrievably stuck in the protocol"}
{"prompt": "uint256 baseTokenId = _tokenId % 100;\n\n// If there is no scheduled recipient:\n", "completion": "Token:mint: infinite loop if the founders\u2019 shares sum up to 100"}
{"prompt": "(baseTokenId += schedule) % 100;\n}\n}\n", "completion": "Founders can receive less tokens that expected"}
{"prompt": "if (getVotes(msg.sender, block.timestamp - 1) < proposalThreshold()) revert BELOW_PROPOSAL_THRESHOLD();\n}\n\nif (msg.sender != proposal.proposer && getVotes(proposal.proposer, block.timestamp - 1) > proposal.proposalThreshold)\nrevert INVALID_CANCEL();\n}\n", "completion": "A proposal can be cancelled by anyone if the proposal has exactly proposalThreshold votes"}
{"prompt": "function updateQuorumThresholdBps(uint256 _newQuorumVotesBps) external onlyOwner {\nemit QuorumVotesBpsUpdated(settings.quorumThresholdBps, _newQuorumVotesBps);\n\n", "completion": "Proposals can be bricked and Auctions stalled by bad settings"}
{"prompt": "// Get the previous delegate\naddress prevDelegate = delegation[_from];\n\n// Store the new delegate\ndelegation[_from] = _to;\n\nemit DelegateChanged(_from, prevDelegate, _to);\n\n// Transfer voting weight from the previous delegate to the new delegate\n_moveDelegateVotes(prevDelegate, _to, balanceOf(_from));\n}\n\n", "completion": "Delegation should not be allowed to address(0)"}
{"prompt": "for (uint256 i = 0; i < numProperties; ++i) {\n// Get the number of items to choose from\nuint256 numItems = properties[i].items.length;\n\n// Use the token's seed to select an item\ntokenAttributes[i + 1] = uint16(seed % numItems);\n\n// Adjust the randomness\nseed >>= 16;\n}\n}\n", "completion": "Index out of bounds error when properties length is more than attributes length breaks minting"}
{"prompt": "return (settings.token.totalSupply() * settings.quorumThresholdBps) / 10_000;\n}\n}\nfunction proposalThresholdBps() external view returns (uint256) {\nreturn settings.proposalThresholdBps;\n}\n", "completion": "The quorum votes calculations don\u2019t take into account burned tokens"}
{"prompt": "} catch Error(string memory) {\n_pause();\n}\n", "completion": "Try-catch block at Auction._createAuction() will only catch string errors"}
{"prompt": "// Ensure the caller is the vetoer\nif (msg.sender != settings.vetoer) revert ONLY_VETOER();\n\n// Ensure the proposal has not been executed\nif (state(_proposalId) == ProposalState.Executed) revert PROPOSAL_ALREADY_EXECUTED();\n\n// Get the pointer to the proposal\nProposal storage proposal = proposals[_proposalId];\n\n// Update the proposal as vetoed\nproposal.vetoed = true;\n\n// If the proposal was queued:\nif (settings.treasury.isQueued(_proposalId)) {\n// Cancel the proposal\nsettings.treasury.cancel(_proposalId);\n}\n\nemit ProposalVetoed(_proposalId);\n}\n\n", "completion": "Compromised or malicious vetoer can veto any proposals with unrestricted power"}
{"prompt": "if (proposal.voteStart != 0) revert PROPOSAL_EXISTS(proposalId);\n\n// Used to store the snapshot and deadline\n// Ensure the proposal hasn't been executed\nif (state(_proposalId) == ProposalState.Executed) revert PROPOSAL_ALREADY_EXECUTED();\n\n// Get a copy of the proposal\nProposal memory proposal = proposals[_proposalId];\n\n// Cannot realistically underflow and `getVotes` would revert\nunchecked {\n// Ensure the caller is the proposer or the proposer's voting weight has dropped below the proposal threshold\nif (msg.sender != proposal.proposer && getVotes(proposal.proposer, block.timestamp - 1) > proposal.proposalThreshold)\nrevert INVALID_CANCEL();\n}\n\n// Update the proposal as canceled\nproposals[_proposalId].canceled = true;\n\n// If the proposal was queued:\nif (settings.treasury.isQueued(_proposalId)) {\n// Cancel the proposal\nsettings.treasury.cancel(_proposalId);\n}\n\nemit ProposalCanceled(_proposalId);\n}\n\n", "completion": "Creating a new governance proposal can be prevented by anyone"}
{"prompt": "function _createAuction() private {\n// Get the next token available for bidding\ntry token.mint() returns (uint256 tokenId) {\ntry token.mint() returns (uint256 tokenId) {\n// Store the token id\nauction.tokenId = tokenId;\n_pause();\n}\n}\n", "completion": "Malicious pausing the contract"}
{"prompt": "settings.duration = SafeCast.toUint40(_duration);\n\nemit DurationUpdated(_duration);\n}\n\n/// @notice Updates the reserve price of each auction\n/// @param _reservePrice The new reserve price\nfunction setReservePrice(uint256 _reservePrice) external onlyOwner {\nsettings.reservePrice = _reservePrice;\n\nemit ReservePriceUpdated(_reservePrice);\n}\n\n/// @notice Updates the time buffer of each auction\n/// @param _timeBuffer The new time buffer\nfunction setTimeBuffer(uint256 _timeBuffer) external onlyOwner {\nsettings.timeBuffer = SafeCast.toUint40(_timeBuffer);\n\nemit TimeBufferUpdated(_timeBuffer);\n}\n\n/// @notice Updates the minimum bid increment of each subsequent bid\n/// @param _percentage The new percentage\nfunction setMinimumBidIncrement(uint256 _percentage) external onlyOwner {\nsettings.minBidIncrement = SafeCast.toUint8(_percentage);\n\nemit MinBidIncrementPercentageUpdated(_percentage);\n}\n\n", "completion": "Auction parameters can be changed during ongoing auction"}
{"prompt": "} else if (proposal.forVotes < proposal.againstVotes || proposal.forVotes < proposal.quorumVotes) {\nreturn ProposalState.Defeated;\n\n", "completion": "A proposal can pass with 0 votes in favor at early DAO stages"}
{"prompt": "function proposalThreshold() public view returns (uint256) {\nunchecked {\nreturn (settings.token.totalSupply() * settings.proposalThresholdBps) / 10_000;\n}\n}\n\n/// @notice The current number of votes required to be in favor of a proposal in order to reach quorum\nfunction quorum() public view returns (uint256) {\nunchecked {\nreturn (settings.token.totalSupply() * settings.quorumThresholdBps) / 10_000;\n}\n}\n\n", "completion": "Precision is not enough for proposalThreshold and quorum. Collections with at least 20000 NFTs in total supply may have some trouble."}
{"prompt": "return (settings.token.totalSupply() * settings.quorumThresholdBps) / 10_000;\n}\n}\nreturn settings.token.getPastVotes(_account, _timestamp);\n}\n\n", "completion": "Governor - Quorum could be less than intended"}
{"prompt": "contract Governor is IGovernor, UUPS, Ownable, EIP712, GovernorStorageV1 {\n/// ///\n/// CONSTANTS///\nfunction transferOwnership(address _newOwner) public onlyOwner {\nemit OwnerUpdated(_owner, _newOwner);\n\ncontract Auction is IAuction, UUPS, Ownable, ReentrancyGuard, Pausable, AuctionStorageV1 {\n/// ///\n/// IMMUTABLES ///\n", "completion": "Changing treasury owner through transferOwnership() can break Governer.sol and Auction.sol"}
{"prompt": "baseTokenId = _getNextTokenId(baseTokenId);\n\n// Store the founder as the recipient\n", "completion": "Token: Founder percentages not always respected"}
{"prompt": "tokenAttributes[i + 1] = uint16(seed % numItems);\n\n// Adjust the randomness\n", "completion": "MetadataRenderer contract raise error when minting"}
{"prompt": "tokenAttributes[i + 1] = uint16(seed % numItems);\n\n// Adjust the randomness\n", "completion": "Minting is not possible when a property has no items"}
{"prompt": "if (msg.sender != settings.token) revert ONLY_TOKEN();\n\n// Compute some randomness for the token id\nuint256 seed = _generateSeed(_tokenId);\n\n// Get the pointer to store generated attributes\nuint16[16] storage tokenAttributes = attributes[_tokenId];\n\n// Cache the total number of properties available\nuint256 numProperties = properties.length;\n\n// Store the total as reference in the first slot of the token's array of attributes\ntokenAttributes[0] = uint16(numProperties);\n\nunchecked {\n// For each property:\nfor (uint256 i = 0; i < numProperties; ++i) {\n// Get the number of items to choose from\nuint256 numItems = properties[i].items.length;\n\n// Use the token's seed to select an item\ntokenAttributes[i + 1] = uint16(seed % numItems);\n\n// Adjust the randomness\nseed >>= 16;\n}\n}\n\nreturn true;\n}\nif (!settings.metadataRenderer.onMinted(_tokenId)) revert NO_METADATA_GENERATED();\n}\n\n", "completion": "Tokens without properties can be minted and cannot be rendered"}
{"prompt": "revert Price_BadFeed(address(_ohmEthPriceFeed));\nohmEthPrice = uint256(ohmEthPriceInt);\n\nint256 reserveEthPriceInt;\n(, reserveEthPriceInt, , updatedAt, ) = _reserveEthPriceFeed.latestRoundData();\nif (updatedAt < block.timestamp - uint256(observationFrequency))\nrevert Price_BadFeed(address(_reserveEthPriceFeed));\n", "completion": "Inconsistency in staleness checks between OHM and reserve token oracles"}
{"prompt": "if (!active) revert Operator_Inactive();\n_;\n}\n\nfunction swap(\nERC20 tokenIn_,\nuint256 amountIn_,\nfunction bondPurchase(uint256 id_, uint256 amountOut_)\nexternal\nonlyWhileActive\n", "completion": "Protocol\u2019s Walls / cushion bonds remain active even if heart is not beating"}
{"prompt": "if (currentPrice > earliestPrice) {\n_movingAverage += (currentPrice - earliestPrice) / numObs;\n} else {\n_movingAverage -= (earliestPrice - currentPrice) / numObs;\n}\n\n// Push new observation into storage and store timestamp taken at\nobservations[nextObsIndex] = currentPrice;\nlastObservationTime = uint48(block.timestamp);\nnextObsIndex = (nextObsIndex + 1) % numObs;\n\n", "completion": "\u201cTWAP\u201d used is an observation-weighted-average-price, not a time-weighted one"}
{"prompt": "(totalEndorsementsForProposal[proposalId_] * 100) <\nVOTES.totalSupply() * ENDORSEMENT_THRESHOLD\n) {\nrevert NotEnoughEndorsementsToActivateProposal();\n}\n\nrevert CannotReclaimTokensForActiveVote();\n}\n\n", "completion": "In Governance.sol, it might be impossible to activate a new proposal forever after failed to execute the previous active proposal."}
{"prompt": "if (VOTES.balanceOf(msg.sender) * 10000 < VOTES.totalSupply() * SUBMISSION_REQUIREMENT)\nrevert NotEnoughVotesToPropose();\n\nVOTES.totalSupply() * ENDORSEMENT_THRESHOLD\n) {\nif (netVotes * 100 < VOTES.totalSupply() * EXECUTION_THRESHOLD) {\nrevert NotEnoughVotesToExecute();\n}\n", "completion": "Anyone can pass any proposal alone before first VOTES are minted"}
{"prompt": "address withdrawer_,\nERC20 token_,\nuint256 amount_\n) external permissioned {\nwithdrawApproval[withdrawer_][token_] = amount_;\n\nemit ApprovedForWithdrawal(withdrawer_, token_, amount_);\n}\n\naddress for_,\nERC20 token_,\nuint256 amount_\n) external onlyRole(\"custodian\") {\nTRSRY.setApprovalFor(for_, token_, amount_);\n}\n\n", "completion": "TRSRY: front-runnable setApprovalFor"}
{"prompt": "function setReserveFactor(uint32 reserveFactor_) external onlyRole(\"operator_policy\") {\n/// Confirm factor is within allowed values\nif (reserveFactor_ > 10000 || reserveFactor_ < 100) revert Operator_InvalidParams();\nuint256 capacity = fullCapacity(true);\n\n/// Regenerate the side with the capacity\nif (capacity_ < _range.high.threshold && _range.high.active) {\n// Set wall to inactive\n_range.high.active = false;\nif (capacity_ < _range.low.threshold && _range.low.active) {\n// Set wall to inactive\n_range.low.active = false;\nuint256 threshold = (capacity_ * thresholdFactor) / FACTOR_SCALE;\n\nif (high_) {\nuint256 capacity = (reservesInTreasury * _config.reserveFactor) / FACTOR_SCALE;\nif (high_) {\ncapacity =\n", "completion": "Operator::setReserveFactor doesn\u2019t check if bond market should be changed"}
{"prompt": "token_.safeTransferFrom(msg.sender, address(this), amount_);\n\nuint256 received = token_.balanceOf(address(this)) - prevBalance;\ntoken_.safeTransfer(msg.sender, amount_);\n\nemit DebtIncurred(token_, msg.sender, amount_);\n", "completion": "Solmate safetransfer and safetransferfrom does not check the codesize of the token address, which may lead to fund loss"}
{"prompt": "function executeProposal() external {\nuint256 netVotes = yesVotesForProposal[activeProposal.proposalId] -\nnoVotesForProposal[activeProposal.proposalId];\nkernel.executeAction(instructions[step].action, instructions[step].target);\nunchecked {\n++step;\n}\n}\n\nemit ProposalExecuted(activeProposal.proposalId);\n\n// deactivate the active proposal\nactiveProposal = ActivatedProposal(0, 0);\n}\n", "completion": "OlympusGovernance#executeProposal: reentrancy attack vulnerable function"}
{"prompt": "uint256 proposalId = INSTR.store(instructions_);\ngetProposalMetadata[proposalId] = ProposalMetadata(\ntitle_,\nINSTR = OlympusInstructions(getModuleAddress(dependencies[0]));\nVOTES = OlympusVotes(getModuleAddress(dependencies[1]));\n}\n", "completion": "Proposals overwrite"}
{"prompt": "// Revoke the votes in the VOTES module\nVOTES.burnFrom(wallet_, amount_);\n}\n}\nuint256 userVotes = VOTES.balanceOf(msg.sender);\n\nif (proposalId_ == 0) {\nrevert CannotEndorseNullProposal();\n}\n\nInstruction[] memory instructions = INSTR.getInstructions(proposalId_);\nif (instructions.length == 0) {\nrevert CannotEndorseInvalidProposal();\n}\n\n// undo any previous endorsement the user made on these instructions\nuint256 previousEndorsement = userEndorsementsForProposal[proposalId_][msg.sender];\ntotalEndorsementsForProposal[proposalId_] -= previousEndorsement;\n\n// reapply user endorsements with most up-to-date votes\nuserEndorsementsForProposal[proposalId_][msg.sender] = userVotes;\ntotalEndorsementsForProposal[proposalId_] += userVotes;\n\nemit ProposalEndorsed(proposalId_, msg.sender, userVotes);\n}\n\n", "completion": "Endorsed votes by a user do not decrease after the user\u2019s votes are revoked"}
{"prompt": "uint256 userVotes = VOTES.balanceOf(msg.sender);\n\nif (activeProposal.proposalId == 0) {\nrevert NoActiveProposalDetected();\n}\n\nif (userVotesForProposal[activeProposal.proposalId][msg.sender] > 0) {\nrevert UserAlreadyVoted();\n}\n\nif (for_) {\nyesVotesForProposal[activeProposal.proposalId] += userVotes;\n} else {\nnoVotesForProposal[activeProposal.proposalId] += userVotes;\n}\n\nuserVotesForProposal[activeProposal.proposalId][msg.sender] = userVotes;\n\nVOTES.transferFrom(msg.sender, address(this), userVotes);\n\nemit WalletVoted(activeProposal.proposalId, msg.sender, for_, userVotes);\n}\n\n// Issue the votes in the VOTES module\nVOTES.mintTo(wallet_, amount_);\n}\n\n// Revoke the votes in the VOTES module\nVOTES.burnFrom(wallet_, amount_);\n}\n}\n", "completion": "Voted votes cannot change after the user is issued new votes or the user\u2019s old votes are revoked during voting"}
{"prompt": "uint256 userVotes = VOTES.balanceOf(msg.sender);\n\nif (activeProposal.proposalId == 0) {\nrevert NoActiveProposalDetected();\n}\n\nif (userVotesForProposal[activeProposal.proposalId][msg.sender] > 0) {\nrevert UserAlreadyVoted();\n}\n\nif (for_) {\nyesVotesForProposal[activeProposal.proposalId] += userVotes;\n} else {\nnoVotesForProposal[activeProposal.proposalId] += userVotes;\n}\n\nuserVotesForProposal[activeProposal.proposalId][msg.sender] = userVotes;\n\nVOTES.transferFrom(msg.sender, address(this), userVotes);\n\nemit WalletVoted(activeProposal.proposalId, msg.sender, for_, userVotes);\n}\n\n", "completion": "OlympusGovernance: Users can prevent their votes from being revoked"}
{"prompt": "if (Policy(policy_).isActive()) revert PolicyStillActive();\n\n// TODO Make sure `policy_` is an actual policy and not a random address.\n\nuint256 len = tokens_.length;\nfor (uint256 j; j < len; ) {\nTRSRY.setApprovalFor(policy_, tokens_[j], 0);\nunchecked {\n++j;\n}\n}\n\nemit ApprovalRevoked(policy_, tokens_);\n}\n\n", "completion": "Griefing/DOS of withdrawals by EOAs from treasury (TRSRY) possible"}
{"prompt": "function _deactivatePolicy(Policy policy_) internal {\nif (!policy_.isActive()) revert Kernel_PolicyNotActivated(address(policy_));\n\n", "completion": "Missing checks in Kernel._deactivatePolicy"}
{"prompt": "function _issueReward(address to_) internal {\nrewardToken.safeTransfer(to_, reward);\nemit RewardIssued(to_, reward);\n}\n\n/*//////////////////////////////////////////////////////////////\n", "completion": "Heart will stop if all rewards are swept"}
{"prompt": "uint256[3] memory rangeParams_ // [thresholdFactor, cushionSpread, wallSpread]\n) Module(kernel_) {\n_range = Range({\nwallSpread_ > 10000 ||\nwallSpread_ < 100 ||\ncushionSpread_ > 10000 ||\ncushionSpread_ < 100 ||\ncushionSpread_ > wallSpread_\n) revert RANGE_InvalidParams();\n\nif (thresholdFactor_ > 10000 || thresholdFactor_ < 100) revert RANGE_InvalidParams();\nthresholdFactor = thresholdFactor_;\n\ncushionFactor: configParams[0],\ncushionDuration: configParams[1],\ncushionDebtBuffer: configParams[2],\nif (cushionFactor_ > 10000 || cushionFactor_ < 100) revert Operator_InvalidParams();\n\n/// Set factor\n", "completion": "Inconsistant parameter requirements between constructor() and Set() functions in RANGE.sol and Operator.sol."}
{"prompt": "revert NotEnoughVotesToExecute();\n}\n", "completion": "No Cap on Amount of VOTES means the voter_admin can get any proposal to pass"}
{"prompt": "if (reserveDebt[token_][msg.sender] == 0) revert TRSRY_NoDebtOutstanding();\n\n// Deposit from caller first (to handle nonstandard token transfers)\nuint256 prevBalance = token_.balanceOf(address(this));\ntoken_.safeTransferFrom(msg.sender, address(this), amount_);\n\nuint256 received = token_.balanceOf(address(this)) - prevBalance;\n\nreserve.safeTransferFrom(msg.sender, address(TRSRY), amountIn_);\n\n/// Mint OHM to sender\n", "completion": "TRSRY: reenter from OlympusTreasury::repayLoan to Operator::swap"}
{"prompt": "// Confirm spreads are within allowed values\nif (\nwallSpread_ > 10000 ||\nwallSpread_ < 100 ||\ncushionSpread_ > 10000 ||\ncushionSpread_ < 100 ||\ncushionSpread_ > wallSpread_\n) revert RANGE_InvalidParams();\n\n", "completion": "Operator: if WallSpread is 10000, operate and beat will revert and price information cannot be updated anymore"}
{"prompt": "uint256 netVotes = yesVotesForProposal[activeProposal.proposalId] -\nnoVotesForProposal[activeProposal.proposalId];\nif (netVotes * 100 < VOTES.totalSupply() * EXECUTION_THRESHOLD) {\nrevert NotEnoughVotesToExecute();\n}\n\nif (block.timestamp < activeProposal.activationTimestamp + EXECUTION_TIMELOCK) {\nrevert ExecutionTimelockStillActive();\n}\n\nInstruction[] memory instructions = INSTR.getInstructions(activeProposal.proposalId);\n\nfor (uint256 step; step < instructions.length; ) {\nkernel.executeAction(instructions[step].action, instructions[step].target);\nunchecked {\n++step;\n}\n}\n\nemit ProposalExecuted(activeProposal.proposalId);\n\n// deactivate the active proposal\nactiveProposal = ActivatedProposal(0, 0);\n}\n\n", "completion": "OlympusGovernance - active proposal does not expire"}
{"prompt": "return token_.balanceOf(address(this)) + totalDebt[token_];\n}\n\n", "completion": "Low market bonds/swaps not working after loan is taken from treasury"}
{"prompt": "uint256 prevBalance = token_.balanceOf(address(this));\ntoken_.safeTransferFrom(msg.sender, address(this), amount_);\n\nuint256 received = token_.balanceOf(address(this)) - prevBalance;\n\n", "completion": "Treasury module is vulnerable to cross-contract reentrancy"}
{"prompt": "(, int256 ohmEthPriceInt, , uint256 updatedAt, ) = _ohmEthPriceFeed.latestRoundData();\n// Use a multiple of observation frequency to determine what is too old to use.\n// Price feeds will not provide an updated answer if the data doesn't change much.\n(, reserveEthPriceInt, , updatedAt, ) = _reserveEthPriceFeed.latestRoundData();\nif (updatedAt < block.timestamp - uint256(observationFrequency))\nrevert Price_BadFeed(address(_reserveEthPriceFeed));\n", "completion": "[NAZ-M1 Chainlink\u2019s latestRoundData Might Return Stale Results"}
{"prompt": "if (currentPrice > earliestPrice) {\n_movingAverage += (currentPrice - earliestPrice) / numObs;\n} else {\n_movingAverage -= (earliestPrice - currentPrice) / numObs;\n}\n\n", "completion": "Moving average precision is lost"}
{"prompt": "} else if (instruction.action == Actions.ChangeExecutor && i != length - 1) {\n// Throw an error if ChangeExecutor exists and is not the last Action in the instruction list.\n// This exists because if ChangeExecutor is not the last item in the list of instructions,\n", "completion": "Unexecutable proposals when Actions.MigrateKernel is not last instruction"}
{"prompt": "if (policy_.isActive()) revert Kernel_PolicyAlreadyActivated(address(policy_));\n\n// Add policy to list of active policies\n", "completion": "Activating same Policy multiple times in Kernel possible"}
{"prompt": "function beat() external nonReentrant {\nif (!active) revert Heart_BeatStopped();\nif (block.timestamp < lastBeat + frequency()) revert Heart_OutOfCycle();\nlastBeat += frequency();\n\n// Issue reward to sender\n", "completion": "Heart::beat() could be called several times in one block if no one called it for a some time"}
{"prompt": "admin = target_;\n} else if (action_ == Actions.MigrateKernel) {\nensureContract(instruction.target);\n\n// If the instruction deals with a module, make sure the module has a valid keycode (UPPERCASE A-Z ONLY)\n", "completion": "Admin cannot be changed to EOA after deployment"}
{"prompt": "address delegatee,\nuint256 nonce,\nuint256 expiry,\nuint8 v,\nbytes32 r,\nbytes32 s\n) public {\nbytes32 domainSeparator = keccak256(\nabi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))\n);\nbytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));\nbytes32 digest = keccak256(abi.encodePacked('\\x19\\x01', domainSeparator, structHash));\naddress signatory = ecrecover(digest, v, r, s);\nrequire(signatory != address(0), 'ERC721Checkpointable::delegateBySig: invalid signature');\nrequire(nonce == nonces[signatory]++, 'ERC721Checkpointable::delegateBySig: invalid nonce');\nrequire(block.timestamp <= expiry, 'ERC721Checkpointable::delegateBySig: signature expired');\nreturn _delegate(signatory, delegatee);\n}\n\n", "completion": "ERC721Checkpointable: delegateBySig allows the user to vote to address 0, which causes the user to permanently lose his vote and cannot transfer his NFT."}
{"prompt": "uint256 proposalId,\nuint8 support,\nstring calldata reason\n) external {\ncastRefundableVoteInternal(proposalId, support, reason);\n}\n\nuint256 proposalId,\nuint8 support,\nstring memory reason\n) internal {\nuint256 startGas = gasleft();\nuint96 votes = castVoteInternal(msg.sender, proposalId, support);\nemit VoteCast(msg.sender, proposalId, support, votes, reason);\nif (votes > 0) {\n_refundGas(startGas);\n}\n}\n\nuint256 public constant REFUND_BASE_GAS = 36000;\n\n/// @notice The EIP-712 typehash for the contract's domain\n", "completion": "Voters can burn large amounts of Ether by submitting votes with long reason strings"}
{"prompt": "vetoer = vetoer_;\nvotingPeriod = votingPeriod_;\nvotingDelay = votingDelay_;\nvetoer = vetoer_;\nvotingPeriod = votingPeriod_;\nvotingDelay = votingDelay_;\nrequire(msg.sender == vetoer, 'NounsDAO::_setVetoer: vetoer only');\n\nemit NewVetoer(vetoer, newVetoer);\n\nvetoer = newVetoer;\n}\n\nrequire(msg.sender == vetoer, 'NounsDAO::_setVetoer: vetoer only');\n\nemit NewVetoer(vetoer, newVetoer);\n\nvetoer = newVetoer;\n}\n\n", "completion": "Loss of Veto Power can Lead to 51% Attack"}
{"prompt": "require(_isContract(addr), \"Only contracts\");\n_blocklist[addr] = true;\nIVotingEscrow(ve).forceUndelegate(addr);\n", "completion": "Attacker contract can avoid being blocked by BlockList.sol"}
{"prompt": "_newRate = uint64(penaltyRate);\n} else {\nbytes memory _rateData = abi.encode(\n", "completion": "Penalty rate is used for pre-maturity date as well"}
{"prompt": "return type(uint128).max;\n}\n\nreturn type(uint128).max;\n}\n\n", "completion": "FraxlendPair.sol is not fully EIP-4626 compliant"}
{"prompt": "token.transferFrom(msg.sender, address(this), _value),\n\"Transfer failed\"\n);\nemit Deposit(\ntoken.transferFrom(msg.sender, address(this), _value),\n\"Transfer failed\"\n);\nemit Deposit(msg.sender, _value, unlockTime, action, block.timestamp);\nrequire(token.transfer(msg.sender, value), \"Transfer failed\");\nemit Withdraw(msg.sender, value, LockAction.WITHDRAW, block.timestamp);\n}\nrequire(token.transfer(msg.sender, remainingAmount), \"Transfer failed\");\nemit Withdraw(msg.sender, value, LockAction.QUIT, block.timestamp);\n}\nrequire(token.transfer(penaltyRecipient, amount), \"Transfer failed\");\nemit CollectPenalty(amount, penaltyRecipient);\n}\n", "completion": "Unsafe usage of ERC20 transfer and transferFrom"}
{"prompt": "locked_.amount += int128(int256(_value));\nlocked_.end = unlock_time;\nlocked_.delegated += int128(int256(_value));\n", "completion": "The current implementation of the VotingEscrow contract doesn\u2019t support fee on transfer tokens"}
{"prompt": "external\noverride\nnonReentrant\ncheckBlocklist\n{\nLockedBalance memory locked_ = locked[msg.sender];\nuint256 unlock_time = _floorToWeek(_unlockTime); // Locktime is rounded down to weeks\n// Validate inputs\nrequire(locked_.amount > 0, \"No lock\");\nrequire(unlock_time > locked_.end, \"Only increase lock end\");\nrequire(unlock_time <= block.timestamp + MAXTIME, \"Exceeds maxtime\");\n// Update lock\nuint256 oldUnlockTime = locked_.end;\nlocked_.end = unlock_time;\nlocked[msg.sender] = locked_;\nif (locked_.delegatee == msg.sender) {\n// Undelegated lock\nrequire(oldUnlockTime > block.timestamp, \"Lock expired\");\nLockedBalance memory oldLocked = _copyLock(locked_);\noldLocked.end = unlock_time;\n_checkpoint(msg.sender, oldLocked, locked_);\n}\nemit Deposit(\nmsg.sender,\n0,\nunlock_time,\nLockAction.INCREASE_TIME,\nblock.timestamp\n);\n}\n\n", "completion": "Inconsistent logic of increase unlock time to the expired locks"}
{"prompt": "_checkpoint(msg.sender, oldLocked, locked_);\n}\n", "completion": "Error in Updating _checkpoint in the increaseUnlockTime Function"}
{"prompt": "locked_.amount += int128(int256(_value));\nlocked_.end = unlock_time;\nlocked_.delegated += int128(int256(_value));\n", "completion": "Unsafe casting from int128 can cause wrong accounting of locked amounts"}
{"prompt": "// Undelegated lock\nrequire(oldUnlockTime > block.timestamp, \"Lock expired\");\nLockedBalance memory oldLocked = _copyLock(locked_);\noldLocked.end = unlock_time;\n_checkpoint(msg.sender, oldLocked, locked_);\n}\nemit Deposit(\n", "completion": "increaseUnlockTime missing _checkpoint for delegated values"}
{"prompt": "IVotingEscrow(ve).forceUndelegate(addr);\n}\n\nrequire(locked_.delegatee == msg.sender, \"Lock delegated\");\n// Update lock\nuint256 value = uint256(uint128(locked_.amount));\nrequire(locked_.delegatee == msg.sender, \"Lock delegated\");\n// Update lock\nuint256 value = uint256(uint128(locked_.amount));\n", "completion": "Blocking Through Change of Blocklist Could Trap Tokens"}
{"prompt": "uint128 _amountToAdjust;\n{\nif (_leftoverCollateral <= 0) {\nuint128 _leftoverBorrowShares = _borrowerShares - _sharesToLiquidate;\nif (_leftoverBorrowShares > 0) {\n// Write off bad debt\n_sharesToAdjust = _leftoverBorrowShares;\n_amountToAdjust = (_totalBorrow.toAmount(_sharesToAdjust, false)).toUint128();\n\n// Effects: write to state\ntotalAsset.amount -= _amountToAdjust;\n\n// Note: Ensure this memory stuct will be passed to _repayAsset for write to state\n_totalBorrow.amount -= _amountToAdjust;\n_totalBorrow.shares -= _sharesToAdjust;\n}\n}\n}\n\n", "completion": "Any borrower with bad debt can be liquidated multiple times to lock funds in the lending pair"}
{"prompt": "bytes memory _firstHalf = BytesLib.slice(_creationCode, 0, 13000);\ncontractAddress1 = SSTORE2.write(_firstHalf);\nif (_creationCode.length > 13000) {\nbytes memory _secondHalf = BytesLib.slice(_creationCode, 13000, _creationCode.length - 13000);\ncontractAddress2 = SSTORE2.write(_secondHalf);\n}\n}\n\n// ============================================================================================\nSSTORE2.read(contractAddress1),\nSSTORE2.read(contractAddress2)\n);\nbytes memory bytecode = abi.encodePacked(\n", "completion": "Impossible to setCreationCode() with code size less than 13K"}
{"prompt": "dirtyLiquidationFee = (_liquidationFee * 9000) / LIQ_PRECISION; // 90% of clean fee\n\nif (_maxLTV >= LTV_PRECISION && !_isBorrowerWhitelistActive) revert BorrowerWhitelistRequired();\n", "completion": "Wrong percent for FraxlendPairCore.dirtyLiquidationFee."}
{"prompt": "address public immutable COMPTROLLER_ADDRESS;\naddress public TIME_LOCK_ADDRESS;\n\nemit SetTimeLock(TIME_LOCK_ADDRESS, _newAddress);\nTIME_LOCK_ADDRESS = _newAddress;\n}\n\n", "completion": "FraxlendPair#setTimeLock: Allows the owner to reset TIMELOCKADDRESS"}
{"prompt": "if (msg.sender != TIME_LOCK_ADDRESS) revert OnlyTimeLock();\nif (_newFee > MAX_PROTOCOL_FEE) {\nrevert BadProtocolFee();\n}\ncurrentRateInfo.feeToProtocolRate = _newFee;\nemit ChangeFee(_newFee);\n}\n\n", "completion": "FraxlendPair.changeFee() doesn\u2019t update interest before changing fee."}
{"prompt": "TIME_LOCK_ADDRESS = _newAddress;\n}\n\n", "completion": "Owner of FraxlendPair can set arbitrary time lock contract address to circumvent time lock"}
{"prompt": "_exchangeRate = _price / oracleNormalization;\n\n// write to storage, if no overflow\n", "completion": "Decimals limitation limits the tokens that can be used"}
{"prompt": "require(deployedPairsBySalt[salt] == address(0), \"FraxlendPairDeployer: Pair already deployed\");\n\nbytes memory _creationCode = BytesLib.concat(\n_configData,\nabi.encode(CIRCUIT_BREAKER_ADDRESS, COMPTROLLER_ADDRESS, TIME_LOCK_ADDRESS, FRAXLEND_WHITELIST_ADDRESS),\nrequire(deployedPairsByName[_name] == address(0), \"FraxlendPairDeployer: Pair name must be unique\");\ndeployedPairsByName[_name] = _pairAddress;\ndeployedPairsArray.push(_name);\n", "completion": "Fraxlend pair deployment can be front-run by a custom pair deployment"}
{"prompt": "_updatedAddresses[i] = _addresses[i];\n} catch {}\nunchecked {\n", "completion": "Denial of service in globalPause by wrong logic"}
{"prompt": "? _userCollateralBalance\n: (_liquidationAmountInCollateralUnits * (LIQ_PRECISION + dirtyLiquidationFee)) / LIQ_PRECISION;\n}\nif (_leftoverBorrowShares > 0) {\n// Write off bad debt\n_sharesToAdjust = _leftoverBorrowShares;\n", "completion": "No incentives to write off bad debt when remaining collateral is very small"}
{"prompt": " creatorRecipients[i],\n creatorShares[i],\n SEND_VALUE_GAS_LIMIT_MULTIPLE_RECIPIENTS\n", "completion": "Creator fees may be burned"}
{"prompt": " // If the numbers are >100% we ignore the fee recipients and pay just the first instead\n totalShares = 0;\n break;\n", "completion": "User may get all of the creator fees by specifying high number for himself"}
{"prompt": "address receiver,\nuint256 /* royaltyAmount */\n ) {\n", "completion": "Forget to check \u201cSome manifolds contracts of ERC-2981 return (address(this), 0) when royalties are not defined\u201d in 3rd priority - MarketFees.sol"}
{"prompt": " SEND_VALUE_GAS_LIMIT_MULTIPLE_RECIPIENTS\n);\n// Sum the total creator rev from shares\n", "completion": "NFT creator sales revenue recipients can steal gas"}
{"prompt": "if (IERC721(nftContract).balanceOf(msg.sender) + count > saleConfig.limitPerAccount) {\n if (saleConfig.limitPerAccount == 0) {\n// Provide a more targeted error if the collection has not been listed.\n", "completion": "Possible to bypass saleConfig.limitPerAccount"}
{"prompt": "firstTokenId = INFTDropCollectionMint(nftContract).mintCountTo(count, msg.sender);\n\n// Distribute revenue from this sale.\n", "completion": "Malicious Creator can steal from collectors upon minting with a custom NFT contract"}
{"prompt": "firstTokenId = INFTDropCollectionMint(nftContract).mintCountTo(count, msg.sender);\n\n// Distribute revenue from this sale.\n", "completion": "mintFromFixedPriceSale for a custom contract can lead to users losing funds"}
{"prompt": "IMIMOProxy currentProxy = _currentProxies[owner];\n\n// Do not deploy if the proxy already exists and the owner is the same.\nif (address(currentProxy) != address(0) && currentProxy.owner() == owner) {\n revert CustomErrors.PROXY_ALREADY_EXISTS(owner);\n}\n\n// Deploy the proxy via the factory.\nproxy = factory.deployFor(owner);\n\n// Set or override the current proxy for the owner.\n_currentProxies[owner] = IMIMOProxy(proxy);\n }\n}\n\n", "completion": "If a MIMOProxy owner destroys their proxy, they cannot deploy another from the same address"}
{"prompt": "\nvaultCollateral.safeIncreaseAllowance(address(lendingPool), flashloanRepayAmount);\n\nreturn true;\n }\n", "completion": "MIMOEmptyVault.sol executeOperation() does not transfer the Vault leftover assets to the owner, it is locked in the MIMOEmptyVault"}
{"prompt": "address vaultOwner = a.vaultsData().vaultOwner(vaultId);\naddress mimoProxy = address(proxyRegistry.getCurrentProxy(msg.sender));\n\naddress mimoProxy = address(proxyRegistry.getCurrentProxy(msg.sender));\n\nif (mimoProxy != vaultOwner && vaultOwner != msg.sender) {\n", "completion": "Automation / management can be set for not yet existing vault"}
{"prompt": " function execute(address target, bytes calldata data) public payable override returns (bytes memory response) {\n// Check that the caller is either the owner or an envoy.\nif (owner != msg.sender) {\n function setPermission(\naddress envoy,\naddress target,\n", "completion": "Incorrect implementation of access control in MIMOProxy:execute"}
{"prompt": "\n /// @notice Maps envoys to target contracts to function selectors to boolean flags.\n mapping(address => mapping(address => mapping(bytes4 => bool))) internal _permissions;\n\nif (owner != msg.sender) {\n bytes4 selector;\n assembly {\nselector := calldataload(data.offset)\n }\n if (!_permissions[msg.sender][target][selector]) {\nrevert CustomErrors.EXECUTION_NOT_AUTHORIZED(owner, msg.sender, target, selector);\n }\n}\n\n", "completion": "Malicious targets can manipulate MIMOProxy permissions"}
{"prompt": " uint256 public override minGasReserve;\n\nuint256 stipend = gasleft() - minGasReserve;\n\n// Delegate call to the target contract.\nbool success;\n(success, response) = target.delegatecall{ gas: stipend }(data);\n\n", "completion": "Malicious manipulation of gas reserve can deny access to MIMOProxy"}
{"prompt": " function batch(bytes[] calldata calls, bool revertOnFail) external payable {\nfor (uint256 i = 0; i < calls.length; i++) {\n (bool success, bytes memory result) = address(this).delegatecall(calls[i]);\n", "completion": "Persisted msg.value in a loop of delegate calls can be used to drain ETH from your proxy"}
{"prompt": " function deployFor(address owner) public override returns (IMIMOProxy proxy) {\nproxy = IMIMOProxy(mimoProxyBase.clone());\nproxy.initialize();\n", "completion": "ProxyFactory can circumvent ProxyRegistry"}
{"prompt": " function setAutomation(uint256 vaultId, AutomatedVault calldata autoParams) external override {\naddress vaultOwner = a.vaultsData().vaultOwner(vaultId);\naddress mimoProxy = address(proxyRegistry.getCurrentProxy(msg.sender));\n function rebalance(uint256 vaultId, IMIMOSwap.SwapData calldata swapData) external override {\nAutomatedVault memory autoVault = _automatedVaults[vaultId];\n\n", "completion": "vaultOwner Can Front-Run rebalance() With setAutomation() To Lower Incentives"}
{"prompt": "bytes32 _hash = keccak256(_data);\n\n// Decode params from _data\nbytes32 _hash = keccak256(_data);\n\n// Decode params from _data\nbytes32 _hash = keccak256(_data);\n\n// Local instance of variable. For saving gas.\nkeccak256(_data),\n_signature,\n0\ncheckSignature(_data, _signature);\n\nemit ContractorInvited(contractor);\ncheckSignature(_data, _signature);\n\n// Decode params from _data\n) = abi.decode(_data, (bytes[], uint256[], uint256, address));\n\n// Revert if decoded taskCount is incorrect. This indicates wrong data.\ncheckSignature(_data, _signature);\n}\n\ncheckSignatureTask(_data, _signature, _taskID);\n}\n\ncheckSignatureTask(_data, _signature, _taskID);\n}\n\nkeccak256(_data),\n_signature,\n0\n", "completion": "Untyped data signing"}
{"prompt": "_communityProject.lastTimestamp) / 86400; // 24*60*60\n\n", "completion": "Builder can halve the interest paid to a community owner due to arithmetic rounding"}
{"prompt": "function repayLender(\nuint256 _communityID,\naddress _project,\nfunction reduceDebt(\nuint256 _communityID,\naddress _project,\nfunction escrow(bytes calldata _data, bytes calldata _signature)\nexternal\nvirtual\n", "completion": "Builders must pay more interest when the system is paused."}
{"prompt": "// allowing anyone to sign, as its hard to add restrictions here\napprovedHashes[_msgSender()][_hash] = true;\n\nemit ApproveHash(_hash, _msgSender());\n}\n\naddress _sender = _msgSender();\n// Allowing anyone to sign, as its hard to add restrictions here.\n// Store _hash as signed for sender.\napprovedHashes[_sender][_hash] = true;\n\nemit ApproveHash(_hash, _sender);\n}\n\n", "completion": "Project.sol and Community.sol have no way to revoke a hash in approvedHashes"}
{"prompt": "function escrow(bytes calldata _data, bytes calldata _signature)\nexternal\nvirtual\n", "completion": "Builder can call Community.escrow again to reduce debt further using same signatures"}
{"prompt": "checkSignatureValidity(_community.owner, _hash, _signature, 0); // must be community owner\ncheckSignatureValidity(_newMemberAddr, _hash, _signature, 1); // must be new member\n\nuint256 _communityID,\naddress _newMemberAddr,\nbytes memory _messageHash\naddress _recoveredSignature = SignatureDecoder.recoverKey(\n_hash,\n_signature,\nreturn ecrecover(toEthSignedMessageHash(messageHash), v, r, s);\n}\n}\n", "completion": "Add members to the not yet created community"}
{"prompt": "_communityProject.apr = _apr;\n_communityProject.publishFee = _publishFee;\nprojectPublished[_project] = _communityID;\n", "completion": "Wrong APR can be used when project is unpublished and published again"}
{"prompt": "checkSignatureTask(_data, _signature, _taskID);\n}\n\n", "completion": "Project.changeOrder() would work unexpectedly for non SCConfirmed tasks."}
{"prompt": "uint256 _lenderFee = (_lendingAmount * _projectInstance.lenderFee()) /\n(_projectInstance.lenderFee() + 1000);\n\nfunction replaceLenderFee(uint256 _newLenderFee)\nexternal\noverride\nonlyAdmin\n{\n// Revert if no change in lender fee\nrequire(lenderFee != _newLenderFee, \"HomeFi::!Change\");\n\n// Reset variables\nlenderFee = _newLenderFee;\n\nemit LenderFeeReplaced(_newLenderFee);\n}\n\n", "completion": "Missing upper limit definition in replaceLenderFee() of HomeFi.sol"}
{"prompt": "_recoveredSignature == _address || approvedHashes[_address][_hash],\n\"Project::invalid signature\"\n);\naddress _sender = _msgSender();\n// Allowing anyone to sign, as its hard to add restrictions here.\n// Store _hash as signed for sender.\napprovedHashes[_sender][_hash] = true;\n\nemit ApproveHash(_hash, _sender);\n}\n\n", "completion": "Signature Checks could be passed when SignatureDecoder.recoverKey() returns 0"}
{"prompt": "checkSignatureValidity(contractor, _hash, _signature, 1);\ncheckSignatureValidity(_sc, _hash, _signature, 2);\n}\n", "completion": "Hash approval not possible when contractor == subcontractor"}
{"prompt": "keccak256(_data),\n_signature,\n0\n);\n\nif (messageSignatures.length % 65 != 0) {\nreturn (address(0));\n}\n", "completion": "Anyone can create disputes if contractor is not set"}
{"prompt": "function replaceAdmin(address _newAdmin)\nexternal\noverride\nonlyAdmin\nnonZero(_newAdmin)\nnoChange(admin, _newAdmin)\n{\n// Replace admin\nadmin = _newAdmin;\n\nemit AdminReplaced(_newAdmin);\n}\n\n/// @inheritdoc IHomeFi\nfunction setTrustedForwarder(address _newForwarder)\nexternal\noverride\nonlyAdmin\nnoChange(trustedForwarder, _newForwarder)\n{\ntrustedForwarder = _newForwarder;\n}\n\n/// @inheritdoc IHomeFi\n", "completion": "Attacker can drain all the projects within minutes, if admin account has been exposed"}
{"prompt": "for (uint256 _taskID = 1; _taskID <= _length; _taskID++) {\n_cost += tasks[_taskID].cost;\n}\n", "completion": "Possible DOS in lendToProject() and toggleLendingNeeded() function because unbounded loop can run out of gas"}
{"prompt": "mintNFT(_sender, string(_hash));\n\n// Update project related mappings\n", "completion": "Owner of project NFT has no purpose"}
{"prompt": "function updateProjectHash(bytes calldata _data, bytes calldata _signature)\nexternal\noverride\n", "completion": "updateProjectHash does not check project address"}
{"prompt": "function setComplete(bytes calldata _data, bytes calldata _signature)\nexternal\noverride\n", "completion": "In Project.setComplete(), the signature can be reused when the first call is reverted for some reason"}
{"prompt": "require(_taskCount == taskCount, \"Project::!taskCount\");\n\n// Revert if decoded project address does not match this contract. Indicating incorrect _data.\n", "completion": "Project.addTasks() wouldn\u2019t work properly when it\u2019s called from disputes contract."}
{"prompt": "function inviteSC(uint256[] calldata _taskList, address[] calldata _scList)\nexternal\noverride\n{\n// Revert if sender is neither builder nor contractor.\nrequire(\n_msgSender() == builder || _msgSender() == contractor,\n\"Project::!Builder||!GC\"\n);\n\n// Revert if taskList array length not equal to scList array length.\nuint256 _length = _taskList.length;\nrequire(_length == _scList.length, \"Project::Lengths !match\");\n\n// Invite subcontractor for each task.\nfor (uint256 i = 0; i < _length; i++) {\n_inviteSC(_taskList[i], _scList[i], false);\n}\n\nemit MultipleSCInvited(_taskList, _scList);\n}\n\n", "completion": "New subcontractor can be set for a SCConfirmed task without current subcontractor consent"}
{"prompt": "function addTasks(bytes calldata _data, bytes calldata _signature)\nexternal\noverride\nif (_loopCount >= _maxLoop) {\n_exceedLimit = true;\nbreak;\ncheckSignatureValidity(contractor, _hash, _signature, 0);\n}\n// When builder has not delegated rights to contractor\n", "completion": "Malicious delegated contractor can block funding tasks or mark tasks as complete"}
{"prompt": "function autoWithdraw(uint256 _amount) internal {\n// Reduce amount from totalLent\ntotalLent -= _amount;\n", "completion": "Task Functionality completely sidestepped via autoWithdraw"}
{"prompt": "checkSignatureTask(_data, _signature, _taskID);\n}\n\ntasks[_taskID].subcontractor = address(0);\n}\n\n", "completion": "changeOrder requires subcontractor signature when the subcontractor address is 0"}
{"prompt": "function execute(bytes calldata input) external override {\n(bytes memory data, bytes memory proof) = abi.decode(input, (bytes, bytes));\n\nfunction _validateSignatures(\nbytes32 messageHash,\naddress[] memory operators,\nif (operatorsEpoch == 0 || epoch - operatorsEpoch >= OLD_KEY_RETENTION) revert InvalidOperators();\n\n_validateSignatures(messageHash, operators, weights, threshold, signatures);\n", "completion": "Previous {Operators/Weights/Threshold} Are Still Able To Sign Off New Commands After Operatorship Is Transferred"}
{"prompt": "function removeWrapping(string calldata symbol) external onlyOwner {\naddress axelarToken = gateway().tokenAddresses(symbol);\nif (axelarToken == address(0)) revert('NotAxelarToken()');\n", "completion": "removeWrapping can be called when there are still wrapped tokens"}
{"prompt": "selfdestruct(payable(msg.sender));\n}\n\n", "completion": "System will not work anymore after EIP-4758"}
{"prompt": "_safeTransfer(tokenAddress, receiver, amount);\n}\n}\n", "completion": "XC20Wrapper may lose received token forever if LocalAsset(xc20).mint is reverted indefinitely"}
{"prompt": "bool currentOperators = IAxelarAuth(AUTH_MODULE).validateProof(messageHash, proof);\n\nuint256 chainId;\nif (!currentOperators) continue;\n\ncommandSelector = AxelarGateway.transferOperatorship.selector;\n", "completion": "Change of operators possible from old operators"}
{"prompt": "function execute(bytes calldata input) external override {\n(bytes memory data, bytes memory proof) = abi.decode(input, (bytes, bytes));\n\nfunction addGas(\nbytes32 txHash,\nuint256 logIndex,\nfunction addNativeGas(\nbytes32 txHash,\nuint256 logIndex,\n", "completion": "Add cancel and refund option for Transaction Recovery"}
{"prompt": "ve = VE(pendingVoteEscrow);\n} else {\nvoteEscrowEnableDate = block.timestamp + 1 days;\nrequire(address(ve) != address(0), ' VE not added yet');\n\nuint256 reward = 0;\n", "completion": "Owner can not set the ve address via RewardDistributor.addVoteEscrow"}
{"prompt": "Checkpoint memory oldCheckpoint = checkpoints[toTokenId][nCheckpoints - 1];\n\nif (nCheckpoints > 0 && oldCheckpoint.fromBlock == block.number) {\nuint256[] memory array = new uint256[](1);\narray[0] = tokenId;\n_writeCheckpoint(toTokenId, nCheckpoints, array);\n}\n\n", "completion": "VoteEscrowDelegation._writeCheckpoint fails when nCheckpoints is 0"}
{"prompt": "Order calldata o,\nuint256 amount,\naddress referrer,\nPayment calldata p\n) internal {\nuint256 protocolfee = ((o.totalAmt * 50) / 10000) * amount;\nWETH.transferFrom(o.signer, address(this), o.totalAmt * amount);\nWETH.withdraw(o.totalAmt * amount);\npayEther(protocolfee, address(distributor));\npayEther(o.exchange.paymentAmt * amount, o.exchange.paymentAddress);\npayEther(o.prePayment.paymentAmt * amount, o.prePayment.paymentAddress);\nif (o.refererrAmt > 0 && referrer != address(0)) {\npayEther(o.refererrAmt * amount, referrer);\npayEther(\n(o.totalAmt - protocolfee - o.exchange.paymentAmt - o.prePayment.paymentAmt - o.refererrAmt) *\namount -\np.paymentAmt,\nmsg.sender\n);\n} else {\npayEther(\n(o.totalAmt - protocolfee - o.exchange.paymentAmt - o.prePayment.paymentAmt) * amount - p.paymentAmt,\nmsg.sender\n);\n}\npayEther(p.paymentAmt, p.paymentAddress);\n", "completion": "GolomTrader\u2019s _settleBalances double counts protocol fee, reducing taker\u2019s payout for a NFT sold"}
{"prompt": "checkpoint.delegatedTokenIds.push(tokenId);\n_writeCheckpoint(toTokenId, nCheckpoints, checkpoint.delegatedTokenIds);\n} else {\n", "completion": "Old delegatee not deleted when delegating to new tokenId"}
{"prompt": "this.removeDelegation(_tokenId);\n\n// Check requirements\nrequire(ownerOf(tokenId) == msg.sender, 'VEDelegation: Not allowed');\nuint256 nCheckpoints = numCheckpoints[tokenId];\nCheckpoint storage checkpoint = checkpoints[tokenId][nCheckpoints - 1];\n", "completion": "NFT transferring won\u2019t work because of the external call to removeDelegation."}
{"prompt": "\nif (nCheckpoints > 0 && oldCheckpoint.fromBlock == block.number) {\noldCheckpoint.delegatedTokenIds = _delegatedTokenIds;\n} else {\ncheckpoints[toTokenId][nCheckpoints] = Checkpoint(block.number, _delegatedTokenIds);\nnumCheckpoints[toTokenId] = nCheckpoints + 1;\n}\n}\n", "completion": "_writeCheckpoint does not write to storage on same block"}
{"prompt": "Checkpoint storage checkpoint = checkpoints[toTokenId][nCheckpoints - 1];\ncheckpoint.delegatedTokenIds.push(tokenId);\n_writeCheckpoint(toTokenId, nCheckpoints, checkpoint.delegatedTokenIds);\nCheckpoint storage checkpoint = checkpoints[tokenId][nCheckpoints - 1];\nremoveElement(checkpoint.delegatedTokenIds, tokenId);\n_writeCheckpoint(tokenId, nCheckpoints, checkpoint.delegatedTokenIds);\n", "completion": "Upon changing of delegate, VoteDelegation updates both the previous and the current checkpoint"}
{"prompt": "Checkpoint storage checkpoint = checkpoints[tokenId][nCheckpoints - 1];\nremoveElement(checkpoint.delegatedTokenIds, tokenId);\n_writeCheckpoint(tokenId, nCheckpoints, checkpoint.delegatedTokenIds);\n", "completion": "Cannot remove delegation from a token to another token"}
{"prompt": "payable(payAddress).transfer(payAmt); // royalty transfer to royaltyaddress\n}\n}\n", "completion": "Use call() rather than transfer() on address payable"}
{"prompt": "require(msg.sender == voter);\nvoted[_tokenId] = true;\n}\n\nrequire(msg.sender == voter);\nattachments[_tokenId] = attachments[_tokenId] + 1;\n}\n\nrequire(attachments[_from] == 0 && !voted[_from], 'attached');\nrequire(_from != _to);\nrequire(_isApprovedOrOwner(msg.sender, _from));\nrequire(attachments[_tokenId] == 0 && !voted[_tokenId], 'attached');\n// Check requirements\nrequire(_isApprovedOrOwner(_sender, _tokenId));\nrequire(attachments[_tokenId] == 0 && !voted[_tokenId], 'attached');\n\nLockedBalance memory _locked = locked[_tokenId];\n", "completion": "Voter in VoteEscrowCore can permanently lock user tokens"}
{"prompt": "address from,\naddress to,\nuint256 tokenId,\nbytes memory data\n) private returns (bool) {\nif (to.isContract()) {\ntry IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\nreturn retval == IERC721Receiver.onERC721Received.selector;\n} catch (bytes memory reason) {\nif (reason.length == 0) {\nrevert(\"ERC721: transfer to non ERC721Receiver implementer\");\n} else {\n/// @solidity memory-safe-assembly\nassembly {\nrevert(add(32, reason), mload(reason))\n}\n}\n}\n} else {\nreturn true;\n}\n}\n\n", "completion": "VoteEscrowCore.safeTransferFrom does not check correct magic bytes returned from receiver contract\u2019s onERC721Received function"}
{"prompt": "chainId := chainid()\n}\n\n", "completion": "Replay attack in case of hard fork"}
{"prompt": "require(o.signer == msg.sender);\n(, bytes32 hashStruct, ) = validateOrder(o);\nfilled[hashStruct] = o.tokenAmt + 1;\nemit OrderCancelled(hashStruct);\n}\n\n", "completion": "Orders with tokenAmt of type(uint256).max cannot be cancelled by GolomTrader.sol#cancelOrder"}
{"prompt": "require(o.totalAmt >= o.exchange.paymentAmt + o.prePayment.paymentAmt + o.refererrAmt);\n// require eth amt is sufficient\nif (o.reservedAddress != address(0)) {\n(o.totalAmt - protocolfee - o.exchange.paymentAmt - o.prePayment.paymentAmt) * amount - p.paymentAmt,\nmsg.sender\n);\n", "completion": "Pre-check is not correct"}
{"prompt": "require(_isApprovedOrOwner(msg.sender, _tokenId), 'caller is not owner nor approved');\n\naddress owner = ownerOf(_tokenId);\n\n// Clear approval\napprove(address(0), _tokenId);\n// Remove token\n_removeTokenFrom(msg.sender, _tokenId);\nemit Transfer(owner, address(0), _tokenId);\n}\n}\n", "completion": "Delegated NFTs that are withdrawn while still delegated will remain delegated even after burn"}
{"prompt": "this.removeDelegation(_tokenId);\n\n// Check requirements\nrequire(ownerOf(tokenId) == msg.sender, 'VEDelegation: Not allowed');\nuint256 nCheckpoints = numCheckpoints[tokenId];\nCheckpoint storage checkpoint = checkpoints[tokenId][nCheckpoints - 1];\n", "completion": "VoteEscrowDelegation._transferFrom can only be executed by the token owner"}
{"prompt": "require(_delegatedTokenIds.length < 500, 'VVDelegation: Cannot stake more');\n\nCheckpoint memory oldCheckpoint = checkpoints[toTokenId][nCheckpoints - 1];\nrequire(ownerOf(tokenId) == msg.sender, 'VEDelegation: Not allowed');\nrequire(this.balanceOfNFT(tokenId) >= MIN_VOTING_POWER_REQUIRED, 'VEDelegation: Need more voting power');\n\ndelegates[tokenId] = toTokenId;\nuint256 nCheckpoints = numCheckpoints[toTokenId];\n\nif (nCheckpoints > 0) {\nCheckpoint storage checkpoint = checkpoints[toTokenId][nCheckpoints - 1];\ncheckpoint.delegatedTokenIds.push(tokenId);\n_writeCheckpoint(toTokenId, nCheckpoints, checkpoint.delegatedTokenIds);\n} else {\nuint256[] memory array = new uint256[](1);\narray[0] = tokenId;\n_writeCheckpoint(toTokenId, nCheckpoints, array);\n}\n\nemit DelegateChanged(tokenId, toTokenId, msg.sender);\n}\n\n", "completion": "Griefer can minimize delegatee\u2019s voting power"}
{"prompt": "require(signaturesigner == o.signer, 'invalid signature');\nif (signaturesigner != o.signer) {\n", "completion": "GolomTrader: validateOrder function does not check if ecrecover return value is 0"}
{"prompt": "address _from,\naddress _to,\nuint256 _tokenId,\naddress _sender\n) internal override {\nrequire(attachments[_tokenId] == 0 && !voted[_tokenId], 'attached');\n\n// remove the delegation\nthis.removeDelegation(_tokenId);\n\n// Check requirements\nrequire(_isApprovedOrOwner(_sender, _tokenId));\n// Clear approval. Throws if `_from` is not the current owner\n_clearApproval(_from, _tokenId);\n// Remove NFT. Throws if `_tokenId` is not a valid NFT\n_removeTokenFrom(_from, _tokenId);\n// Add NFT\n_addTokenTo(_to, _tokenId);\n// Set the block of ownership transfer (for Flash NFT protection)\nownership_change[_tokenId] = block.number;\n// Log the transfer\nemit Transfer(_from, _to, _tokenId);\n}\n\n", "completion": "NFTs that don\u2019t have a checkpoint can\u2019t be transferred"}
{"prompt": "require(msg.value >= o.totalAmt * amount + p.paymentAmt, 'mgmtm');\n\nif (o.reservedAddress != address(0)) {\n", "completion": "fillAsk() Allows for msg.value to be larger than require locking the excess in the contract"}
{"prompt": "ERC721(o.collection).transferFrom(o.signer, receiver, o.tokenId);\n} else {\nERC1155(o.collection).safeTransferFrom(o.signer, receiver, o.tokenId, amount, '');\n", "completion": "Use safeTransferFrom Instead of transferFrom for ERC721"}
{"prompt": "function auction(bytes12 vaultId, address to)\nexternal\nreturns (DataTypes.Auction memory auction_)\nilkJoin.exit(auction_.auctioneer, auctioneerCut.u128());\n}\n\n", "completion": "Someone can create non-liquidatable auction if the collateral asset fails on transferring to address(0)"}
{"prompt": "uint128 art = uint256(balances.art).wmul(line.proportion).u128();\nif (art < debt.min * (10**debt.dec)) art = balances.art;\nuint128 ink = (art == balances.art)\n", "completion": "Incorrect amount of Collateral moves for Auction"}
{"prompt": "\nVault memory vlt = vaults[o];\n\nuint256 redeemable = vlt.redeemable;\nuint256 exchangeRate = Compounding.exchangeRate(protocol, cTokenAddr);\n\n// if market has matured, calculate marginal interest between the maturity rate and previous position exchange rate\n// otherwise, calculate marginal exchange rate between current and previous exchange rate.\nuint256 yield;\nif (maturityRate > 0) { // Calculate marginal interest\n yield = ((maturityRate * 1e26) / vlt.exchangeRate) - 1e26;\n} else {\n // calculate marginal interest\n yield = ((exchangeRate * 1e26) / vlt.exchangeRate) - 1e26;\n}\n\nuint256 interest = (yield * vlt.notional) / 1e26;\n\nvlt.exchangeRate = exchangeRate;\nvlt.redeemable = 0;\n\nvaults[o] = vlt;\n\n// return adds marginal interest to previously accrued redeemable interest\nreturn (redeemable + interest);\n }\n\n", "completion": "Loss of funds in an underlying protocol would cause catostrophic loss of funds for swivel"}
{"prompt": "string calldata label,\naddress wrappedOwner,\nuint32 fuses,\nuint64 expiry,\naddress resolver\n) public override returns (uint64) {\nuint256 tokenId = uint256(keccak256(bytes(label)));\naddress registrant = registrar.ownerOf(tokenId);\nif (\nregistrant != msg.sender &&\n!isApprovedForAll(registrant, msg.sender) &&\n!registrar.isApprovedForAll(registrant, msg.sender)\n) {\nrevert Unauthorised(\n_makeNode(ETH_NODE, bytes32(tokenId)),\nmsg.sender\n);\n}\n\n// transfer the token from the user to this contract\nregistrar.transferFrom(registrant, address(this), tokenId);\n\n// transfer the ens record back to the new owner (this contract)\nregistrar.reclaim(tokenId, address(this));\n\nreturn _wrapETH2LD(label, wrappedOwner, fuses, expiry, resolver);\n}\n\n", "completion": "wrapETH2LD permissioning is over-extended"}
{"prompt": " return IYearn(c).withdraw(a) >= 0;\n} else if (p == uint8(Protocols.Aave)) {\n // Aave v2 docs state that withraw returns uint256\n", "completion": "Mismatch in withdraw() between Yearn and other protocols can prevent Users from redeeming zcTokens and permanently lock funds"}
{"prompt": " yield = ((maturityRate * 1e26) / vlt.exchangeRate) - 1e26;\n} else {\n // calculate marginal interest\nvlt.exchangeRate = exchangeRate;\nvlt.redeemable = 0;\n\n", "completion": "With most functions in VaultTracker.sol, users can call them only once after maturity has been reached."}
{"prompt": " feenominators[x] = d[x];\n emit SetFee(i[x], d[x]);\n\n", "completion": "Swivel.setFee() is implemented wrongly."}
{"prompt": "revert Approvals(allowed, previewAmount);\n}\nallowance[holder][msg.sender] -= previewAmount;\nif (allowed >= principalAmount) { revert Approvals(allowed, principalAmount); }\nallowance[holder][msg.sender] -= principalAmount; \n", "completion": "Error in allowance logic"}
{"prompt": " uint256 interest = (yield * vlt.notional) / 1e26;\n // add interest and amount to position, reset cToken exchange rate\n vlt.redeemable += interest;\nuint256 interest = (yield * vlt.notional) / 1e26;\n// remove amount from position, Add interest to position, reset cToken exchange rate\nvlt.redeemable += interest;\nuint256 interest = (yield * vlt.notional) / 1e26;\n\nvlt.exchangeRate = exchangeRate;\nuint256 interest = (yield * from.notional) / 1e26;\n// remove amount from position, Add interest to position, reset cToken exchange rate\nfrom.redeemable += interest;\n uint256 newVaultInterest = (yield * to.notional) / 1e26;\n // add interest and amount to position, reset cToken exchange rate\n to.redeemable += newVaultInterest;\n uint256 interest = (yield * sVault.notional) / 1e26;\n // add interest and amount, reset cToken exchange rate\n sVault.redeemable += interest;\n", "completion": "VaultTracker miscalculates compounding interest"}
{"prompt": "if (a > vlt.notional) { revert Exception(31, a, vlt.notional, address(0), address(0)); }\n\nuint256 exchangeRate = Compounding.exchangeRate(protocol, cTokenAddr);\nif (a > from.notional) { revert Exception(31, a, from.notional, address(0), address(0)); }\n\nuint256 exchangeRate = Compounding.exchangeRate(protocol, cTokenAddr);\n", "completion": "Should use >= instead of >"}
{"prompt": " return IYearnVault(c).underlying();\n} else if (p == uint8(Protocols.Aave)) {\nuint8 p,\nuint256 m,\naddress c,\nstring memory n,\nstring memory s\n ) external authorized(admin) unpaused(p) returns (bool) {\nif (swivel == address(0)) { revert Exception(21, 0, 0, address(0), address(0)); }\n\naddress underAddr = Compounding.underlying(p, c);\n\n", "completion": "Yearn vault integration is broken"}
{"prompt": "revert Invalid(msg.sender, owner);\n}\n\n", "completion": "ERC20 Incorrect check on returnedAddress in permit() results in unlimited approval of zero address"}
{"prompt": "uint256 previewAmount = this.previewWithdraw(underlyingAmount);\n// If maturity is not yet reached\nif (block.timestamp < maturity) {\nreturn (underlyingAmount * IRedeemer(redeemer).markets(protocol, underlying, maturity).maturityRate / IRedeemer(redeemer).getExchangeRate(protocol, cToken));\n}\n/// @notice At or after maturity, Burns principalAmount from `owner` and sends exactly `underlyingAmount` of underlying tokens to `receiver`.\n", "completion": "ZcToken.withdraw will send user 0 tokens if called after maturity deadline but before market is set mature"}
{"prompt": "(address zct, address tracker) = ICreator(creator).create(p, underAddr, m, c, swivel, n, s, IErc20(underAddr).decimals()) ;\n\nmarkets[p][underAddr][m] = Market(c, zct, tracker, 0);\naddress tracker = address(new VaultTracker(p, m, c, sw));\n\nreturn (zct, tracker);\nadmin = msg.sender;\nprotocol = p;\nmaturity = m;\n", "completion": "VaultTracker has the wrong admin"}
{"prompt": " function authRedeem(uint8 p, address u, uint256 m, address f, address t, uint256 a) public authorized(markets[p][u][m].zcToken) returns (uint256 underlyingAmount) {\nMarket memory market = markets[p][u][m];\n// if the market has not matured, mature it...\n", "completion": "unpaused(p) modifier missing in authRedeem function"}
{"prompt": " function authRedeem(uint8 p, address u, address c, address t, uint256 a) external returns (bool);\n}\n\n ISwivel(swivel).authRedeem(p, u, market.cTokenAddr, t, amount);\n\n return (amount);\n function authRedeemZcToken(uint8 p, address u, address c, address t, uint256 a) external authorized(marketPlace) returns(bool) {\n// redeem underlying from compounding\nif (!withdraw(p, u, c, a)) { revert Exception(7, 0, 0, address(0), address(0)); }\ncontract Swivel {\n /// @dev maps the key of an order to a boolean indicating if an order was cancelled\n mapping (bytes32 => bool) public cancelled;\n", "completion": "Interface definition error"}
{"prompt": "_setFuses(node, newOwner, fuses, expiry);\n}\n_transferAndBurnFuses(node, newOwner, fuses, expiry);\n}\n}\n_transferAndBurnFuses(node, newOwner, fuses, expiry);\n}\n}\n", "completion": "It is possible to create fake ERC1155 NameWrapper token for subdomain, which is not owned by NameWrapper"}
{"prompt": "function setSubnodeOwner(\nbytes32 parentNode,\nstring calldata label,\nfunction unwrap(\nbytes32 parentNode,\nbytes32 labelhash,\n", "completion": "The expiry of the parent node can be smaller than the one of a child node, violating the guarantee policy"}
{"prompt": "function unwrap(\nbytes32 parentNode,\nbytes32 labelhash,\nfunction wrap(\nbytes calldata name,\naddress wrappedOwner,\nfunction setSubnodeOwner(bytes32 node, bytes32 label, address owner) public virtual override authorised(node) returns(bytes32) {\nbytes32 subnode = keccak256(abi.encodePacked(node, label));\n_setOwner(subnode, owner);\n", "completion": "PARENT_CANNOT_CONTROL can be bypassed by maliciously unwrapping parent node"}
{"prompt": "uint256 expires = base.renew(uint256(label), duration);\n\nif (msg.value > price.base) {\n * @notice Wraps a .eth domain, creating a new token and sending the original ERC721 token to this contract\n * @dev Can be called by the owner of the name on the .eth registrar or an authorised caller on the registrar\n * @param label Label as a string of the .eth domain to wrap\n", "completion": "Renew of 2nd level domain is not done properly"}
{"prompt": "msg.value - (price.base + price.premium)\n);\n}\npayable(msg.sender).transfer(msg.value - price.base);\n}\n\n", "completion": "transfer() depends on gas consts"}
{"prompt": "mask = type(uint256).max;\n} else {\nmask = ~(2 ** (8 * (32 - shortest + idx)) - 1);\n}\nint diff = int(a & mask) - int(b & mask);\n", "completion": "BytesUtil.compare returns wrong result on some strings longer than 32 characters"}
{"prompt": "|| !rrset.signerName.equals(0, name, name.length - rrset.signerName.length))\n{\nrevert InvalidSignerName(name, rrset.signerName);\n}\n\n", "completion": "DNSSECImpl.verifySignature compares strings incorrectly, allowing malicious zones to forge DNSSEC trust chain"}
{"prompt": "uint shortest = len;\nif (otherlen < len)\nshortest = otherlen;\n\nuint selfptr;\nuint otherptr;\n\nassembly {\n", "completion": "BytesUtils: compare will not revert when the offset and len exceeds the bytes lengths"}
{"prompt": "fuses & ~PARENT_CANNOT_CONTROL != 0 &&\nfuses & (PARENT_CANNOT_CONTROL | CANNOT_UNWRAP) !=\n(PARENT_CANNOT_CONTROL | CANNOT_UNWRAP)\n) {\nrevert OperationProhibited(node);\n}\n}\n", "completion": "If PARENT_CANNOT_CONTROL is set on subdomain, it can be unwrapped then wrapped by its owner and then parent can control it again before the expiry"}
{"prompt": "return self.length >= offset + other.length && equals(self, offset, other, 0, other.length);\n}\n\n/*\n* @dev Returns true if the two byte ranges are equal.\n* @param self The first byte range to compare.\n* @param other The second byte range to compare.\n* @return True if the byte ranges are equal, false otherwise.\n*/\nfunction equals(bytes memory self, bytes memory other) internal pure returns(bool) {\nreturn self.length == other.length && equals(self, 0, other, 0, self.length);\n}\n\n", "completion": "Wrong Equals Logic"}
{"prompt": " * @notice Unwraps a .eth domain. e.g. vitalik.eth\n * @dev Can be called by the owner in the wrapper or an authorised caller in the wrapper\n * @param labelhash labelhash of the .eth domain\n * @param newRegistrant sets the owner in the .eth registrar to this address\n * @param newController sets the owner in the registry to this address\n */\n\nfunction unwrapETH2LD(\nbytes32 labelhash,\naddress newRegistrant,\naddress newController\n) public override onlyTokenOwner(_makeNode(ETH_NODE, labelhash)) {\n_unwrap(_makeNode(ETH_NODE, labelhash), newController);\nregistrar.transferFrom(\naddress(this),\nnewRegistrant,\nuint256(labelhash)\n);\n}\n\n", "completion": "The unwrapETH2LD use transferFrom instead of safeTransferFrom to transfer ERC721 token"}
{"prompt": "return int32(i1) - int32(i2) >= 0;\n}\n\n", "completion": "Incorrect implementation of RRUtils.serialNumberGte"}
{"prompt": "if (ens.owner(node) != address(this)) {\nens.setSubnodeOwner(parentNode, labelhash, address(this));\n_addLabelAndWrap(parentNode, node, label, newOwner, fuses, expiry);\n", "completion": "The preimage DB (i.e., NameWrapper.names) can be maliciously manipulated/corrupted"}
{"prompt": "address from,\naddress to,\nuint256 id,\nuint256 amount,\nbytes memory data\n) internal {\n(address oldOwner, uint32 fuses, uint64 expiry) = getData(id);\nif (oldOwner == to) {\nreturn;\n}\n\n", "completion": "ERC1155Fuse: _transfer does not revert when sent to the old owner"}
{"prompt": "address resolver,\nbytes32 label,\nbytes[] calldata data\n) internal {\n// use hardcoded .eth namehash\nbytes32 nodehash = keccak256(abi.encodePacked(ETH_NODE, label));\nfor (uint256 i = 0; i < data.length; i++) {\n// check first few bytes are namehash\nbytes32 txNamehash = bytes32(data[i][4:36]);\nrequire(\ntxNamehash == nodehash,\n\"ETHRegistrarController: Namehash on record do not match the name being registered\"\n);\nresolver.functionCall(\ndata[i],\n\"ETHRegistrarController: Failed to set Record\"\n);\n}\n}\n\nfunction register(\nstring calldata name,\naddress owner,\nfunction register(uint256 id, address owner, uint duration) external override returns(uint) {\n return _register(id, owner, duration, true);\n}\n", "completion": "Users can create extra ENS records at no cost"}
{"prompt": "uint256 fractionPrice = buyoutPrice / totalSupply;\n\n// Sets info mapping of the vault address to auction struct\n", "completion": "Division rounding can make fraction-price lower than intended (down to zero)"}
{"prompt": "uint256 userFractions = userProposalFractions[_proposalId][msg.sender];\n// Updates fractional balance of caller\nuserProposalFractions[_proposalId][msg.sender] = 0;\nuint256 userEth = userProposalEth[_proposalId][msg.sender];\n// Udpates ether balance of caller\nuserProposalEth[_proposalId][msg.sender] = 0;\nIFERC1155(token).safeTransferFrom(\naddress(this),\nmsg.sender,\npayable(msg.sender).transfer(userEth);\n}\n\n", "completion": "Migration::withdrawContribution falsely assumes that user should get exactly his original contribution back"}
{"prompt": "IBuyout(buyout).start{value: proposal.totalEth}(_vault);\nproposal.isCommited = true;\nstarted = true;\nuint256 depositAmount = IERC1155(token).balanceOf(msg.sender, id);\n\n// Transfers fractional tokens into the buyout pool\n", "completion": "Any fractions deposited into any proposal can be stolen at any time until it is commited"}
{"prompt": "function migrateVaultERC20(\naddress _vault,\nuint256 _proposalId,\nfunction migrateVaultERC721(\naddress _vault,\nuint256 _proposalId,\nfunction migrateVaultERC1155(\naddress _vault,\nuint256 _proposalId,\n", "completion": "Malicious User Could Burn The Assets After A Successful Migration"}
{"prompt": "_vault\n);\nif (id == 0) revert NotVault(_vault);\n// Reverts if buyout state is not inactive\n(, , State current, , , ) = IBuyout(buyout).buyoutInfo(_vault);\nState required = State.INACTIVE;\nif (current != required) revert IBuyout.InvalidState(required, current);\n\n", "completion": "Fund will be stuck if a buyout is started while there are pending migration proposals"}
{"prompt": "if (!MerkleProof.verify(_proof, merkleRoot, leaf)) {\nif (msg.sender != owner)\nrevert NotAuthorized(msg.sender, _target, selector);\naddress owner_ = owner;\n// Reserve some gas to ensure that the function has enough to finish the execution\nuint256 stipend = gasleft() - MIN_GAS_RESERVE;\nif (nonce != 0) revert Initialized(owner, msg.sender, nonce);\nnonce = 1;\nowner = msg.sender;\n", "completion": "Delegate call in Vault#_execute can alter Vault\u2019s ownership"}
{"prompt": "mapping(uint256 => address) private royaltyAddress;\n/// @notice Mapping to track the royalty percent for token ID types => royaltyPercent\nmapping(uint256 => uint256) private royaltyPercent;\n\n", "completion": "The FERC1155.sol don\u2019t respect the EIP2981"}
{"prompt": "function join(\naddress _vault,\nuint256 _proposalId,\nfunction leave(address _vault, uint256 _proposalId) external {\n// Reverts if address is not a registered vault\n(address token, uint256 id) = IVaultRegistry(registry).vaultToToken(\n", "completion": "Migration.join() and Migration.leave() can still work after unsucessful migration."}
{"prompt": "constructor() {\nimplementation = address(new Vault());\n}\n\n/// @notice Address of vault owner\naddress public owner;\n/// @notice Merkle root hash of vault permissions\nbytes32 public merkleRoot;\n/// @notice Initializer value\nuint256 public nonce;\n/// @dev Minimum reserve of gas units\nuint256 private constant MIN_GAS_RESERVE = 5_000;\n/// @notice Mapping of function selector to plugin address\nmapping(bytes4 => address) public methods;\n\n/// @dev Initializes nonce and proxy owner\nfunction init() external {\nif (nonce != 0) revert Initialized(owner, msg.sender, nonce);\nnonce = 1;\n", "completion": "Vault implementation can be destroyed leading to loss of all assets"}
{"prompt": "// Deletes auction info\ndelete buyoutInfo[_vault];\n// Transfers fractions and ether back to proposer of the buyout pool\nIERC1155(token).safeTransferFrom(\naddress(this),\nproposer,\nid,\ntokenBalance,\n\"\"\n);\n_sendEthOrWeth(proposer, ethBalance);\n// Emits event for ending unsuccessful auction\nemit End(_vault, State.INACTIVE, proposer);\n}\n}\n", "completion": "Forced buyouts can be performed by malicious buyers"}
{"prompt": "(address token, uint256 id) = IVaultRegistry(registry).vaultToToken(\n_vault\n);\nuserProposalEth[_proposalId][msg.sender] += msg.value;\n// Deposits fractional tokens into contract\nIFERC1155(token).safeTransferFrom(\n(address token, uint256 id) = IVaultRegistry(registry).vaultToToken(\n_vault\n);\nuserProposalFractions[_proposalId][msg.sender] = 0;\n// Updates ether balances of the proposal and caller\nuint256 ethAmount = userProposalEth[_proposalId][msg.sender];\nIFERC1155(token).safeTransferFrom(\naddress(this),\nmsg.sender,\n", "completion": "Migration: no check that user-supplied proposalId and vault match"}
{"prompt": "mapping(address => Auction) public buyoutInfo;\n\n/// @notice Initializes registry, supply, and transfer contracts\nState required = State.INACTIVE;\nif (current != required) revert InvalidState(required, current);\n\n_sendEthOrWeth(proposer, ethBalance);\n// Emits event for ending unsuccessful auction\nemit End(_vault, State.INACTIVE, proposer);\n", "completion": "Proposer can start a perpetual buyout which can only end if the auction succeeds and is not rejected"}
{"prompt": "(totalSupply + tokenBalance);\n_sendEthOrWeth(msg.sender, buyoutShare);\n", "completion": "Cash-out from a successful buyout allows an attacker to drain Ether from the Buyout contract"}
{"prompt": "function withdrawContribution(address _vault, uint256 _proposalId)\nexternal\n{\n", "completion": "Steal NFTs from a Vault, and ETH + Fractional tokens from users."}
{"prompt": "function batchDepositERC20(\naddress _from,\naddress _to,\nfunction batchDepositERC721(\naddress _from,\naddress _to,\n/// @notice Transfers ERC-1155 tokens\n/// @param _from Source address\n/// @param _to Target address\n", "completion": "Malicious Users Can Exploit Residual Allowance To Steal Assets"}
{"prompt": "IFERC1155(token).setApprovalFor(address(buyout), id, true);\n// Starts the buyout process\nIBuyout(buyout).start{value: proposal.totalEth}(_vault);\nproposal.isCommited = true;\nstarted = true;\n}\n", "completion": "Migration Module: Re-enter commit using custom token"}
{"prompt": "Proposal storage proposal = migrationInfo[_vault][_proposalId];\nif (!(proposal.isCommited)) revert NotProposed();\n// Reverts if the migration was unsuccessful\n(, , State current, , , ) = IBuyout(buyout).buyoutInfo(_vault);\nif (current != State.SUCCESS) revert UnsuccessfulMigration();\n// Reverts if the new vault has already been deployed\nif (proposal.newVault != address(0))\nrevert NewVaultAlreadyDeployed(proposal.newVault);\n\n", "completion": "Proposal which started buyout which fails is able to settle migration as if its buyout succeeded."}
{"prompt": "uint256 tokenBalance = IERC1155(token).balanceOf(address(this), id);\n// Checks totalSupply of auction pool to determine if buyout is successful or not\nif (\n", "completion": "The time constraint of selling fractions can be bypassed by directly transferring fraction tokens to the buyout contract"}
{"prompt": "function leave(address _vault, uint256 _proposalId) external {\n// Reverts if address is not a registered vault\n(address token, uint256 id) = IVaultRegistry(registry).vaultToToken(\n", "completion": "Migration\u2019s leave function allows leaving a committed proposal"}
{"prompt": "function install(bytes4[] memory _selectors, address[] memory _plugins)\nexternal\n{\n", "completion": "A vault owner can frontrun a plugin call and change its implementation"}
{"prompt": "function createCollectionFor(\nbytes32 _merkleRoot,\naddress _controller,\nfunction setRoyalties(\nuint256 _id,\naddress _receiver,\n", "completion": "A vault owner can also be the controller and arbitraily set the secondary market royalties"}
{"prompt": "address _to,\nuint256 _id,\nuint256 _amount,\nbytes memory _data\n) external onlyRegistry {\n_mint(_to, _id, _amount, _data);\ntotalSupply[_id] += _amount;\n}\n\n", "completion": "Buyout Module: redeeming before the update of totalSupply will make buyout\u2019s current state success"}
{"prompt": "proposal.totalFractions\n);\n\n(_scalar - ((_totalFractions * _scalar) / _lastTotalSupply));\n}\n\n", "completion": "Migration fails when all tokens are joined"}
{"prompt": "fallback(bytes calldata _data) external payable returns (bytes memory response) {\naddress plugin = methods[msg.sig];\n(,response) = _execute(plugin, _data);\n", "completion": "fallback() function can bypass permission/auth checks imposed in execute()"}
{"prompt": "uint256 newTotalSupply = IVaultRegistry(registry).totalSupply(newVault);\nuint256 shareAmount = (balanceContributedInEth * newTotalSupply) /\ntotalInEth;\n\n_vault\n);\nproposal.newFractionSupply = _newFractionSupply;\n}\n", "completion": "Migration total supply reduction can be used to remove minority shareholders"}
{"prompt": "payable(msg.sender).transfer(ethAmount);\n}\n\npayable(msg.sender).transfer(userEth);\n}\n\n", "completion": "Use of payable.transfer() may lock user funds"}
{"prompt": "(, int256 _price, , , ) = feed.latestRoundData();\n\n// Get a reference to the number of decimals the feed uses.\n function priceFor(\nuint256 _currency,\nuint256 _base,\n : prices.priceFor(_amount.currency, _baseWeightCurrency, _decimals);\n\n// Find the number of tokens to mint, as a fixed point number with as many decimals as `weight` has.\nprices.priceFor(_currency, _balanceCurrency, _MAX_FIXED_POINT_FIDELITY)\n );\n\nprices.priceFor(_currency, _balanceCurrency, _MAX_FIXED_POINT_FIDELITY)\n );\n\nprices.priceFor(_distributionLimitCurrency, _balanceCurrency, _MAX_FIXED_POINT_FIDELITY)\n );\n\n : PRBMath.mulDiv(_ethOverflow, 10**18, prices.priceFor(JBCurrencies.ETH, _currency, 18));\n\n// Adjust the decimals of the fixed point number if needed to match the target decimals.\n", "completion": "Oracle data feed can be outdated yet used anyways which will impact payment logic"}
{"prompt": "(, int256 _price, , , ) = feed.latestRoundData();\n\n// Get a reference to the number of decimals the feed uses.\n", "completion": "Unhandled chainlink revert would lock all price oracle access"}
{"prompt": " PRBMath.mulDiv(_fee, _feeDiscount, JBConstants.MAX_FEE_DISCOUNT);\n\n// The amount of tokens from the `_amount` to pay as a fee.\nreturn\n _amount - PRBMath.mulDiv(_amount, JBConstants.MAX_FEE, _discountedFee + JBConstants.MAX_FEE);\n }\n", "completion": "Discounted fee calculation is imprecise and calculates less fees than anticipated"}
{"prompt": "for (uint256 _i = 0; _i < _heldFeeLength; ) {\n // Get the fee amount.\n uint256 _amount = _feeAmount(\n", "completion": "processFees() may fail due to exceed gas limit"}
{"prompt": "uint256 _currency,\nuint256 _base,\nIJBPriceFeed _feed\n ) external override onlyOwner {\n// There can't already be a feed for the specified currency.\nif (feedFor[_currency][_base] != IJBPriceFeed(address(0))) revert PRICE_FEED_ALREADY_EXISTS();\n\n// Store the feed.\nfeedFor[_currency][_base] = _feed;\n\nemit AddFeed(_currency, _base, _feed);\n }\n}\n\n", "completion": "addFeedFor should check if inverse feed already exists"}
{"prompt": "if (projectOf[_token] != 0) revert TOKEN_ALREADY_IN_USE();\n\n// Can't change to a token that doesn't use 18 decimals.\n oldToken.transferOwnership(_projectId, _newOwner);\n\nemit Change(_projectId, _token, oldToken, _newOwner, msg.sender);\ntokenStore.changeFor(_projectId, _token, _newOwner);\n }\n\n", "completion": "Token Change Can Be Frontrun, Blocking Token"}
{"prompt": "// Check for sameness.\nif (\n _splits[_j].percent == _currentSplits[_i].percent &&\n _splits[_j].beneficiary == _currentSplits[_i].beneficiary &&\n _splits[_j].allocator == _currentSplits[_i].allocator &&\n _splits[_j].projectId == _currentSplits[_i].projectId &&\n // Allow lock extention.\n _splits[_j].lockedUntil >= _currentSplits[_i].lockedUntil\n) _includesLocked = true;\n }\n\n", "completion": "Duplicated locked splits can be discarded"}
{"prompt": "\n// Discount rate must be less than or equal to 100%.\nif (_data.discountRate > JBConstants.MAX_DISCOUNT_RATE) revert INVALID_DISCOUNT_RATE();\n\n// Weight must fit into a uint88.\nif (_data.weight > type(uint88).max) revert INVALID_WEIGHT();\n\npacked |= _start << 144;\n\n// number in bits 200-255.\npacked |= _number << 200;\n\n", "completion": "Lack of check on mustStartAtOrAfter"}
{"prompt": "address _from,\naddress payable _to,\nuint256 _amount\n ) internal override {\n_from == address(this)\n ? IERC20(token).transfer(_to, _amount)\n : IERC20(token).transferFrom(_from, _to, _amount);\n }\n\n", "completion": "Use a safe transfer helper library for ERC20 transfers"}
{"prompt": " function distributeReservedTokensOf(uint256 _projectId, string calldata _memo)\nexternal\nvirtual\n function set(\nuint256 _projectId,\nuint256 _domain,\n", "completion": "Juicebox project owner can create a honeypot to cause grief"}
{"prompt": "_split.beneficiary != address(0) ? _split.beneficiary : payable(msg.sender),\n_netPayoutAmount\n );\n", "completion": "Grieffer beneficiary can cause DOS"}
{"prompt": "uint256 _projectId,\nIJBToken _token,\naddress _newOwner\n )\nexternal\nvirtual\noverride\nrequirePermission(projects.ownerOf(_projectId), _projectId, JBOperations.CHANGE_TOKEN)\n {\n// Get a reference to the project's current funding cycle.\nJBFundingCycle memory _fundingCycle = fundingCycleStore.currentOf(_projectId);\n\n// The current funding cycle must not be paused.\nif (!_fundingCycle.changeTokenAllowed()) revert CHANGE_TOKEN_NOT_ALLOWED();\n\n// Change the token in the store.\ntokenStore.changeFor(_projectId, _token, _newOwner);\n }\n\n", "completion": "changeTokenOf makes it impossible for holders of oldToken to redeem the overflowed assets."}
{"prompt": "uint256 _projectId,\naddress _account,\nuint256 _amount\n ) external override onlyOwner {\n_projectId; // Prevents unused var compiler and natspec complaints.\n\nreturn _mint(_account, _amount);\n }\n\n", "completion": "JBToken: mint function could mint arbitrary amount of tokens"}
{"prompt": "_unprocessedTokenBalanceOf,\nJBConstants.MAX_RESERVED_RATE,\nJBConstants.MAX_RESERVED_RATE - _reservedRate\n ) - _unprocessedTokenBalanceOf;\n }\n", "completion": "More outstanding reserved tokens are distributed than anticipated leading to less redeemable assets and therefore loss of user funds"}
{"prompt": " _splits[_j].percent == _currentSplits[_i].percent &&\n _splits[_j].beneficiary == _currentSplits[_i].beneficiary &&\n _splits[_j].allocator == _currentSplits[_i].allocator &&\n _splits[_j].projectId == _currentSplits[_i].projectId &&\n // Allow lock extention.\n _splits[_j].lockedUntil >= _currentSplits[_i].lockedUntil\n) _includesLocked = true;\n }\n", "completion": "Locked splits can be updated"}
{"prompt": "// send the fee to the admin/DAO if fee is greater than 0%\nuint256 feeAmount = 0;\nif (fee > 0) {\nfeeAmount = (order.strike * fee) / 1000;\nERC20(order.baseAsset).safeTransfer(owner(), feeAmount);\n}\n\nERC20(order.baseAsset).safeTransfer(msg.sender, order.strike - feeAmount);\n\nERC20(order.baseAsset).safeTransfer(msg.sender, order.strike);\n\n// transfer assets from exerciser to putty\n", "completion": "Fee is being deducted when Put is expired and not when it is exercised."}
{"prompt": "ERC20(order.baseAsset).safeTransfer(owner(), feeAmount);\n}\n\n", "completion": "[Denial-of-Service Contract Owner Could Block Users From Withdrawing Their Strike"}
{"prompt": "_transferERC20sIn(order.erc20Assets, msg.sender);\n_transferERC721sIn(order.erc721Assets, msg.sender);\n", "completion": "Put option sellers can prevent exercise by specifying zero amounts, or non-existant tokens"}
{"prompt": "_mint(order.maker, uint256(orderHash));\n\n// create opposite long/short position for taker\nbytes32 oppositeOrderHash = hashOppositeOrder(order);\npositionId = uint256(oppositeOrderHash);\n_mint(msg.sender, positionId);\n\nrequire(to != address(0), \"INVALID_RECIPIENT\");\nrequire(_ownerOf[id] == address(0), \"ALREADY_MINTED\");\n\n_ownerOf[id] = to;\n\nemit Transfer(address(0), to, id);\n}\n\n", "completion": "Putty position tokens may be minted to non ERC721 receivers"}
{"prompt": "Order memory order,\nbytes calldata signature,\nOrder memory originalOrder\n) public payable returns (uint256 positionId) {\n// cancel the original order\ncancel(originalOrder);\n\n// accept the counter offer\nuint256[] memory floorAssetTokenIds = new uint256[](0);\npositionId = fillOrder(order, signature, floorAssetTokenIds);\n}\n\n", "completion": "acceptCounterOffer() May Result In Both Orders Being Filled"}
{"prompt": "? require(floorAssetTokenIds.length == order.floorTokens.length, \"Wrong amount of floor tokenIds\")\n: require(floorAssetTokenIds.length == 0, \"Invalid floor tokens length\");\n\n", "completion": "Create a short call order with non empty floor makes the option impossible to exercise and withdraw"}
{"prompt": "ERC20(order.baseAsset).safeTransferFrom(msg.sender, address(this), order.strike);\n}\n\n", "completion": "Zero strike call options can be systemically used to steal premium from the taker"}
{"prompt": "address[] floorTokens;\nERC20Asset[] erc20Assets;\nERC721Asset[] erc721Assets;\nERC20Asset[] erc20Assets;\nERC721Asset[] erc721Assets;\n}\nERC721Asset[] erc721Assets;\n}\n\naddress baseAsset;\nuint256 strike;\nuint256 premium;\n", "completion": "Malicious Token Contracts May Lead To Locking Orders"}
{"prompt": "for (uint256 i = 0; i < assets.length; i++) {\nERC20(assets[i].token).safeTransfer(msg.sender, assets[i].tokenAmount);\n}\n}\n\nfor (uint256 i = 0; i < assets.length; i++) {\nERC721(assets[i].token).safeTransferFrom(address(this), msg.sender, assets[i].tokenId);\n}\n}\n\nfor (uint256 i = 0; i < floorTokens.length; i++) {\nERC721(floorTokens[i]).safeTransferFrom(address(this), msg.sender, floorTokenIds[i]);\n}\n}\n\n", "completion": "Unbounded loops may cause exercise()s and withdraw()s to fail"}
{"prompt": "ERC20(order.baseAsset).safeTransfer(msg.sender, order.strike);\n\n", "completion": "Put options are free of any fees"}
{"prompt": "ERC20(order.baseAsset).safeTransferFrom(order.maker, msg.sender, order.premium);\n} else {\n// handle the case where the user uses native ETH instead of WETH to pay the premium\nERC20(order.baseAsset).safeTransferFrom(msg.sender, order.maker, order.premium);\n}\n}\nERC20(order.baseAsset).safeTransferFrom(msg.sender, address(this), order.strike);\n}\n\n", "completion": "fillOrder() and exercise() may lock Ether sent to the contract, forever"}
{"prompt": "ERC20(order.baseAsset).safeTransferFrom(order.maker, address(this), order.strike);\nreturn positionId;\n}\n\n", "completion": "An attacker can create a short put option order on an NFT that does not support ERC721 (like cryptopunk), and the user can fulfill the order, but cannot exercise the option"}
{"prompt": "ERC20(order.baseAsset).safeTransferFrom(order.maker, msg.sender, order.premium);\n} else {\n// handle the case where the user uses native ETH instead of WETH to pay the premium\nERC20(order.baseAsset).safeTransferFrom(msg.sender, order.maker, order.premium);\n}\n}\nERC20(order.baseAsset).safeTransferFrom(order.maker, address(this), order.strike);\nreturn positionId;\n}\nERC20(order.baseAsset).safeTransferFrom(msg.sender, address(this), order.strike);\n}\n\nERC20(order.baseAsset).safeTransferFrom(msg.sender, address(this), order.strike);\n}\n\nERC20(token).safeTransferFrom(from, address(this), tokenAmount);\n}\n}\n", "completion": "Overlap Between ERC721.transferFrom() and ERC20.transferFrom() Allows order.erc20Assets or order.baseAsset To Be ERC721 Rather Than ERC20"}
{"prompt": "// -- exercising a call option\n\n// transfer strike from exerciser to putty\n// handle the case where the taker uses native ETH instead of WETH to pay the strike\nif (weth == order.baseAsset && msg.value > 0) {\n// check enough ETH was sent to cover the strike\nrequire(msg.value == order.strike, \"Incorrect ETH amount sent\");\n\n// convert ETH to WETH\n// we convert the strike ETH to WETH so that the logic in withdraw() works\n// - because withdraw() assumes an ERC20 interface on the base asset.\nIWETH(weth).deposit{value: msg.value}();\n} else {\nERC20(order.baseAsset).safeTransferFrom(msg.sender, address(this), order.strike);\n}\n\n// transfer assets from putty to exerciser\n_transferERC20sOut(order.erc20Assets);\n_transferERC721sOut(order.erc721Assets);\n_transferFloorsOut(order.floorTokens, positionFloorAssetTokenIds[uint256(orderHash)]);\n", "completion": "The contract serves as a flashloan pool without fee"}
{"prompt": "function setFee(uint256 _fee) public payable onlyOwner {\nrequire(_fee < 30, \"fee must be less than 3%\");\n\nuint256 feeAmount = 0;\nif (fee > 0) {\nfeeAmount = (order.strike * fee) / 1000;\n", "completion": "fee can change without the consent of users"}
{"prompt": "ERC20(order.baseAsset).safeTransfer(owner(), feeAmount);\n}\n", "completion": "Options with a small strike price will round down to 0 and can prevent assets to be withdrawn"}
{"prompt": "require(order.duration < 10_000 days, \"Duration too long\");\n\n// check order has not expired\n", "completion": "Order duration can be set to 0 by Malicious maker"}
{"prompt": "require(msg.sender == order.maker, \"Not your order\");\n\nbytes32 orderHash = hashOrder(order);\n\n// mark the order as cancelled\ncancelledOrders[orderHash] = true;\n\nemit CancelledOrder(orderHash, order);\n}\n\n", "completion": "Order cancellation is prone to frontrunning and is dependent on a centralized database"}
{"prompt": "if ((order.isCall && isExercised) || (!order.isCall && !isExercised)) {\n// send the fee to the admin/DAO if fee is greater than 0%\nuint256 feeAmount = 0;\nif (fee > 0) {\nfeeAmount = (order.strike * fee) / 1000;\nERC20(order.baseAsset).safeTransfer(owner(), feeAmount);\n}\n\nERC20(order.baseAsset).safeTransfer(msg.sender, order.strike - feeAmount);\n\nreturn;\n}\n\n", "completion": "Zero strike call options will avoid paying system fee"}
{"prompt": "pragma solidity 0.8.13;\n\n/**\n", "completion": "Use of Solidity version 0.8.13 which has two known issues applicable to PuttyV2"}
{"prompt": "function updateTWAV() external override {\nrequire(status == Status.buyout, \"NibblVault: Status!=Buyout\");\nuint32 _blockTimestamp = uint32(block.timestamp % 2**32);\n", "completion": "User Could Change The State Of The System While In Pause Mode"}
{"prompt": "illuminateToken.balanceOf(address(this));\n\n", "completion": "The lend function for tempus uses the wrong return value of depositAndFix"}
{"prompt": "returned = IPendle(pendleAddr).swapExactTokensForTokens(a - fee, r, path, address(this), d)[0];\n\n}\n", "completion": "Pendle Uses Wrong Return Value For swapExactTokensForTokens()"}
{"prompt": "IElementToken(principal).withdrawPrincipal(amount, marketPlace);\n} else if (p == uint8(MarketPlace.Principals.Yield)) {\n// Redeems prinicipal tokens from yield\n", "completion": "Redeemer.redeem() for Element withdraws PT to wrong address."}
{"prompt": "uint8 public twavObservationsIndex;\nuint8 private constant TWAV_BLOCK_NUMBERS = 4; //TWAV of last 4 Blocks \nuint32 public lastBlockTimeStamp;\n", "completion": "Ineffective TWAV Implementation"}
{"prompt": "delete contracts[i];\n}\nunchecked {\nIStaking(contracts[_index]).canBatchTransactions()\n);\n}\nbool canBatch = IStaking(contracts[i]).canBatchTransactions();\nbatch[i] = Batch(contracts[i], canBatch);\nunchecked {\n", "completion": "Denial of Service by wrong BatchRequests.removeAddress logic"}
{"prompt": "// prevent unstaking if override due to vulnerabilities asdf\nrequire(!isUnstakingPaused, \"Unstaking is paused\");\nif (_trigger) {\nrebase();\n}\n_retrieveBalanceFromUser(_amount, msg.sender);\n\nClaim storage userCoolInfo = coolDownInfo[msg.sender];\n\n// try to claim withdraw if user has withdraws to claim function will check if withdraw is valid\nclaimWithdraw(msg.sender);\n\ncoolDownInfo[msg.sender] = Claim({\namount: userCoolInfo.amount + _amount,\ncredits: userCoolInfo.credits +\nIYieldy(YIELDY_TOKEN).creditsForTokenBalance(_amount),\nexpiry: epoch.number + coolDownPeriod\n});\n\nrequestWithdrawalAmount += _amount;\nsendWithdrawalRequests();\n}\n\n", "completion": "User can initiate withdraw for previous epoch if rebase hasn\u2019t been called since end of epoch"}
{"prompt": "// check to see if near the end of a TOKE cycle\nif (canBatchTransactions()) {\n// if has withdrawal amount to be claimed then claim\n_withdrawFromTokemak();\n\n// if more requestWithdrawalAmount exists after _withdrawFromTokemak then request the new amount\nITokeManager tokeManager = ITokeManager(TOKE_MANAGER);\nif (requestWithdrawalAmount > 0) {\n_requestWithdrawalFromTokemak(requestWithdrawalAmount);\n}\n\nuint256 currentCycleIndex = tokeManager.getCurrentCycleIndex();\nlastTokeCycleIndex = currentCycleIndex;\n}\n}\n\n", "completion": "Withdrawals initiated after cycle withdrawal request won\u2019t be withdrawn in the correct cycle"}
{"prompt": "uint256 userWalletBalance = IYieldy(OLD_YIELDY_TOKEN).balanceOf(\nmsg.sender\n);\n\nIYieldy(OLD_YIELDY_TOKEN).transferFrom(\nmsg.sender,\naddress(this),\nuserWalletBalance\n);\n\nIStaking(OLD_CONTRACT).instantUnstake(false);\n\nIStaking(NEW_CONTRACT).stake(userWalletBalance, msg.sender);\n}\n}\n\n", "completion": "Users of Migration.sol may forfeit rebase rewards"}
{"prompt": "if (twavObservations[TWAV_BLOCK_NUMBERS - 1].timestamp != 0) {\nuint8 _index = ((twavObservationsIndex + TWAV_BLOCK_NUMBERS) - 1) % TWAV_BLOCK_NUMBERS;\nTwavObservation memory _twavObservationCurrent = twavObservations[(_index)];\nTwavObservation memory _twavObservationPrev = twavObservations[(_index + 1) % TWAV_BLOCK_NUMBERS];\n_twav = (_twavObservationCurrent.cumulativeValuation - _twavObservationPrev.cumulativeValuation) / (_twavObservationCurrent.timestamp - _twavObservationPrev.timestamp);\n}\n}\n\n", "completion": "Twav.sol#_getTwav() will revert when timestamp > 4294967296"}
{"prompt": "twavObservations[twavObservationsIndex] = TwavObservation(_blockTimestamp, _prevCumulativeValuation + (_valuation * _timeElapsed)); //add the previous observation to make it cumulative\ntwavObservationsIndex = (twavObservationsIndex + 1) % TWAV_BLOCK_NUMBERS;\nlastBlockTimeStamp = _blockTimestamp;\n_twav = (_twavObservationCurrent.cumulativeValuation - _twavObservationPrev.cumulativeValuation) / (_twavObservationCurrent.timestamp - _twavObservationPrev.timestamp);\n}\n}\n", "completion": "_updateTwav() and _getTwav() will revert when cumulativePrice overflows"}
{"prompt": "Safe.transferFrom(ERC20(address(pool.fyToken())), msg.sender, address(pool), ptA);\nreturn pool.mint(msg.sender, msg.sender, minRatio, maxRatio);\nSafe.transferFrom(ERC20(address(pool.base())), msg.sender, address(pool), a);\nreturn pool.mintWithBase(msg.sender, msg.sender, ptBought, minRatio, maxRatio);\n}\n", "completion": "Marketplace calls unimplemented function"}
{"prompt": "function stake(uint256 _amount, address _recipient) public {\n// if override staking, then don't allow stake\nrequire(!isStakingPaused, \"Staking is paused\");\n", "completion": "Arbitrage on stake()"}
{"prompt": "function buy(uint256 _minAmtOut, address _to) external override payable notBoughtOut lock whenNotPaused returns(uint256 _purchaseReturn) {\n//Make update on the first tx of the block\nif (status == Status.buyout) {\nfunction sell(uint256 _amtIn, uint256 _minAmtOut, address payable _to) external override notBoughtOut whenNotPaused returns(uint256 _saleReturn) {\n//Make update on the first tx of the block\nif (status == Status.buyout) {\nfunction redeem(address payable _to) external override boughtOut returns(uint256 _amtOut){\nuint256 _balance = balanceOf(msg.sender);\n_amtOut = ((address(this).balance - feeAccruedCurator - totalUnsettledBids) * _balance) / totalSupply();\nfunction withdrawERC721(address _assetAddress, uint256 _assetID, address _to) external override boughtOut {\nrequire(msg.sender == bidder,\"NibblVault: Only winner\");\nIERC721(_assetAddress).safeTransferFrom(address(this), _to, _assetID);\n", "completion": "Buyout cannot be rejected when paused"}
{"prompt": "uint _primaryReserveBalance = (primaryReserveRatio * _initialTokenSupply * _initialTokenPrice) / (SCALE * 1e18);\nprimaryReserveBalance = _primaryReserveBalance;\nfictitiousPrimaryReserveBalance = _primaryReserveBalance;\n", "completion": "Lack of sanity check on _initialTokenSupply and _initialTokenPrice can lead to a seller losing his NFT"}
{"prompt": "if (_lowerCurveDiff >= msg.value) {\n_purchaseReturn = _buySecondaryCurve(msg.value, _totalSupply);\n} else {\n//Gas Optimization\n_purchaseReturn = _initialTokenSupply - _totalSupply;\nsecondaryReserveBalance += _lowerCurveDiff;\n// _purchaseReturn = _buySecondaryCurve(_to, _lowerCurveDiff);\n_purchaseReturn += _buyPrimaryCurve(msg.value - _lowerCurveDiff, _totalSupply + _purchaseReturn);\n} \n}\n", "completion": "NibblVault: In the buy function, users can avoid paying fees"}
{"prompt": "uint32 _secondaryReserveRatio = uint32((msg.value * SCALE * 1e18) / (_initialTokenSupply * _initialTokenPrice));\nrequire(_secondaryReserveRatio <= primaryReserveRatio, \"NibblVault: Excess initial funds\");\nrequire(_secondaryReserveRatio >= MIN_SECONDARY_RESERVE_RATIO, \"NibblVault: secResRatio too low\");\n", "completion": "[PNM-004 Calculation of _secondaryReserveRatio can be overflowed"}
{"prompt": "uint256 public UPDATE_TIME = 2 days;\nuint256 public constant MAX_ADMIN_FEE = 10_000; //1%\n\npendingVaultImplementation = _newVaultImplementation;\nvaultUpdateTime = block.timestamp + UPDATE_TIME;\n}\n\n/// @notice updates new vault implementation\n/// @dev new vault implementation can be updated only after timelock\nfunction updateVaultImplementation() external override {\nrequire(vaultUpdateTime != 0 && block.timestamp >= vaultUpdateTime, \"NibblVaultFactory: UPDATE_TIME has not passed\");\nvaultImplementation = pendingVaultImplementation;\ndelete vaultUpdateTime;\n}\n\nuint256 private constant BUYOUT_DURATION = 5 days; \n\n/// @notice The percentage of fee that goes for liquidity in lower curve until its reserve ratio becomes equal to primaryReserveRatio\n", "completion": "NibblVault buyout duration longer than update timelock"}
{"prompt": "if (twavObservations[TWAV_BLOCK_NUMBERS - 1].timestamp != 0) {\nuint8 _index = ((twavObservationsIndex + TWAV_BLOCK_NUMBERS) - 1) % TWAV_BLOCK_NUMBERS;\nTwavObservation memory _twavObservationCurrent = twavObservations[(_index)];\n", "completion": "Twav.getTwav() will return a wrong result when twavObservations[TWAVBLOCK_NUMBERS - 1].timestamp = 0."}
{"prompt": "contract Basket is IBasket, ERC721(\"NFT Basket\", \"NFTB\"), Initializable {\n\nevent DepositERC721(address indexed token, uint256 tokenId, address indexed from);\nimport { ERC721, IERC721 } from \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport { IERC165, ERC165 } from \"@openzeppelin/contracts/utils/introspection/ERC165.sol\";\nimport { IBasket } from \"./Interfaces/IBasket.sol\";\n", "completion": "Basket NFT have no name and symbol"}
{"prompt": "returned += (a[i] - fee) * (order.premium / order.principal);\n\nunchecked {\n", "completion": "Division Before Multiplication Can Lead To Zero Rounding Of Return Amount"}
{"prompt": "require(_allowance[holder][msg.sender] >= underlyingAmount, 'not enough approvals');\nreturn IRedeemer(redeemer).authRedeem(underlying, maturity, holder, receiver, principalAmount); \n}\n", "completion": "Allowance check always true in ERC5095 redeem"}
{"prompt": "ISense(d).redeem(o, m, amount);\n\nemit Redeem(p, u, m, amount);\n", "completion": "Redeem Sense can be bricked"}
{"prompt": "require(_allowance[holder][msg.sender] >= underlyingAmount, 'not enough approvals');\nreturn IRedeemer(redeemer).authRedeem(underlying, maturity, holder, receiver, underlyingAmount); \n}\n", "completion": "ERC5095 redeem/withdraw does not update allowances"}
{"prompt": ") public returns (bool) {\n//use market interface to fetch the market for the given market pair\naddress principal = IMarketPlace(marketPlace).markets(u, m, p);\n", "completion": "Lender: no check for paused market on mint"}
{"prompt": "uint256 amount = token.balanceOf(msg.sender);\n// Make sure the market has matured\nif (block.timestamp < token.maturity()) {\n", "completion": "Funds may be stuck when redeeming for Illuminate"}
{"prompt": "\nif (p == uint8(MarketPlace.Principals.Illuminate)) {\n// Get Illuminate's principal token\nIERC5095 token = IERC5095(principal);\n// Get the amount of tokens to be redeemed from the sender\nuint256 amount = token.balanceOf(msg.sender);\n// Make sure the market has matured\nif (block.timestamp < token.maturity()) {\nrevert Invalid('not matured');\n}\n// Burn the prinicipal token from Illuminate\ntoken.burn(o, amount);\n// Transfer the original underlying token back to the user\nSafe.transferFrom(IERC20(u), lender, address(this), amount);\n\n", "completion": "Illuminate PT redeeming allows for burning from other accounts"}
{"prompt": "Safe.transferFrom(IERC20(u), lender, address(this), amount);\n\nif (p == uint8(MarketPlace.Principals.Apwine)) {\n", "completion": "Incorrect implementation of APWine and Tempus redeem"}
{"prompt": "ISwivel(swivelAddr).initiate(o, a, s);\n\nyield(u, y, returned, address(this));\n", "completion": "Calls To Swivel.initiate() Do Not Verify o.exit or o.vault Allowing An Attacker To Manipulate Accounting In Their Favour"}
{"prompt": "if (ITempus(principal).yieldBearingToken() != IERC20Metadata(u)) {\nrevert NotEqual('underlying');\n} else if (ITempus(principal).maturityTime() > m) {\n", "completion": "Checking yieldBearingToken against u instead of backingToken"}
{"prompt": "function approve(\naddress u,\nuint256 m,\nfunction approve(address[] calldata u, address[] calldata a) external authorized(admin) returns (bool) {\nuint256 len = u.length;\nif (len != a.length) {\nfunction setFee(uint256 f) external authorized(admin) returns (bool) {\nfeenominator = f;\nreturn true;\nfunction setMarketPlace(address m) external authorized(admin) returns (bool) {\nif (marketPlace != address(0)) {\nrevert Exists(marketPlace);\nfunction setSwivel(address s) external authorized(admin) returns (bool) {\nswivelAddr = s;\nreturn true;\nfunction withdraw(address e) external authorized(admin) returns (bool) {\nuint256 when = withdrawals[e];\nrequire (when != 0, 'no withdrawal scheduled');\n", "completion": "Centralisation Risk: Admin Can Change Important Variables To Steal Funds"}
{"prompt": "Safe.transferFrom(IERC20(u), msg.sender, address(this), a);\n\nif (p == uint8(MarketPlace.Principals.Yield)) {\n// Purchase yield PTs to lender.sol (address(this))\nuint256 returned = yield(u, y, a - calculateFee(a), address(this));\n// Mint and distribute equivalent illuminate PTs\nIERC5095(principalToken(u, m)).mint(msg.sender, returned);\n\nemit Lend(p, u, m, returned);\n\nreturn returned;\n}\nelse {\n// Purchase illuminate PTs directly to msg.sender\nuint256 returned = yield(u, y, a - calculateFee(a), msg.sender);\n\nemit Lend(p, u, m, returned);\n\nreturn returned;\n}\n}\n", "completion": "Principal types in Illuminate and Yield lending are mixed up"}
{"prompt": "Safe.transferFrom(IERC20(u), msg.sender, address(this), lent);\n// fill the orders on swivel protocol\nISwivel(swivelAddr).initiate(o, a, s);\n", "completion": "Swivel lend method doesn\u2019t pull protocol fee from user"}
{"prompt": "uint8 p,\naddress u,\nuint256 m,\nuint256 a\n) public returns (bool) {\n//use market interface to fetch the market for the given market pair\naddress principal = IMarketPlace(marketPlace).markets(u, m, p);\n//use safe transfer lib and ERC interface...\nSafe.transferFrom(IERC20(principal), msg.sender, address(this), a);\n//use ERC5095 interface...\nIERC5095(principalToken(u, m)).mint(msg.sender, a);\n\nemit Mint(p, u, m, a);\n\nreturn true;\n}\n\n", "completion": "Lender.mint() May Take The Illuminate PT As Input Which Will Transfer And Mint More Illuminate PT Cause an Infinite Supply"}
{"prompt": "/// @param e Address of token to withdraw\n/// @return bool true if successful\nfunction withdraw(address e) external authorized(admin) returns (bool) {\nuint256 when = withdrawals[e];\nrequire (when != 0, 'no withdrawal scheduled');\n \nrequire (block.timestamp >= when, 'withdrawal still on hold');\n \nwithdrawals[e] = 0;\n \nIERC20 token = IERC20(e);\nSafe.transfer(token, admin, token.balanceOf(address(this)));\n \nreturn true;\n}\n\n/// @param e address of the underlying token to withdraw\n/// @return bool true if successful\nfunction withdrawFee(address e) external authorized(admin) returns (bool) {\n// Get the token to be withdrawn\nIERC20 token = IERC20(e);\n\n// Get the balance to be transferred\nuint256 balance = fees[e];\n\n// Reset accumulated fees of the token to 0\nfees[e] = 0;\n\n// Transfer the accumulated fees to the admin\nSafe.transfer(token, admin, balance);\nreturn true;\n}\n\n", "completion": "withdraw eToken before withdrawFee of eToken could render withdrawFee of eToken unfunctioning"}
{"prompt": "address u,\naddress y,\nuint256 a,\naddress r\n) internal returns (uint256) {\n// preview exact swap slippage on yield\nuint128 returned = IYield(y).sellBasePreview(Cast.u128(a));\n\n// send the remaing amount to the given yield pool\nSafe.transfer(IERC20(u), y, a);\n\n// lend out the remaining tokens in the yield pool\nIYield(y).sellBase(r, returned);\n\n", "completion": "Leak of Value in yield function, slippage check is not effective"}
{"prompt": "tokePoolContract.withdraw(requestedWithdrawals.amount);\nrequestWithdrawalAmount -= requestedWithdrawals.amount;\nwithdrawalAmount += requestedWithdrawals.amount;\n", "completion": "No withdrawal possible for ETH TOKE pool"}
{"prompt": "IYieldy(YIELDY_TOKEN).mint(_recipient, _amount);\n} else {\n// create a claim and mint tokens so a user can claim them once warm up has passed\nwarmUpInfo[_recipient] = Claim({\namount: info.amount + _amount,\ncredits: info.credits +\nIYieldy(YIELDY_TOKEN).creditsForTokenBalance(_amount),\nexpiry: epoch.number + warmUpPeriod\n});\n\nIYieldy(YIELDY_TOKEN).mint(address(this), _amount);\n}\n\n", "completion": "Staking.sol#stake() DoS by staking 1 wei for the recipient when warmUpPeriod > 0"}
{"prompt": "_mint(msg.sender, amountToMint);\n}\n\n_burn(msg.sender, _amount);\nIERC20Upgradeable(stakingToken).safeTransfer(\nmsg.sender,\namountMinusFee\n);\nunstakeAllRewardTokens();\n", "completion": "Yield of LiquidityReserve can be stolen"}
{"prompt": "uint256 newValue = _allowances[_from][msg.sender] - _value;\n_allowances[_from][msg.sender] = newValue;\nemit Approval(_from, msg.sender, newValue);\n", "completion": "Unsecure transferFrom"}
{"prompt": "onlyRole(MINTER_BURNER_ROLE)\n{\n_burn(_address, _amount);\n", "completion": "MINTERBURNERROLE can burn any amount of Yieldy from an arbitrary address"}
{"prompt": "for (uint256 i; i < contractsLength; ) {\nif (\ncontracts[i] != address(0) &&\nfor (uint256 i; i < contractsLength; ) {\nbool canBatch = IStaking(contracts[i]).canBatchTransactions();\nbatch[i] = Batch(contracts[i], canBatch);\nfor (uint256 i; i < contractsLength; ) {\nif (contracts[i] == _address) {\ndelete contracts[i];\n", "completion": "Possible DOS (out-of-gas) on loops."}
{"prompt": "CURVE_POOL = _curvePool;\nsetToAndFromCurve();\n}\n\n", "completion": "No way to set CURVE_POOL approval after setting new curve pool address"}
{"prompt": "function transferFrom(\naddress _from,\naddress _to,\n", "completion": "Burn access control can be bypassed"}
{"prompt": "uint256 contractsLength = contracts.length;\nfor (uint256 i; i < contractsLength; ) {\nif (\ncontracts[i] != address(0) &&\nIStaking(contracts[i]).canBatchTransactions()\n) {\nIStaking(contracts[i]).sendWithdrawalRequests();\n}\nunchecked {\n++i;\n}\n}\n}\n\n", "completion": "Sending batch withdrawal requests can possibly DoS"}
{"prompt": "if (updatedTotalSupply > MAX_SUPPLY) {\nupdatedTotalSupply = MAX_SUPPLY;\n}\n", "completion": "Incorrect rebase percentage calculation"}
{"prompt": "msg.sender,\naddress(this),\n_amount\n);\n\nClaim storage info = warmUpInfo[_recipient];\n\n// if claim is available then auto claim tokens\nif (_isClaimAvailable(_recipient)) {\nclaim(_recipient);\n}\n\n_depositToTokemak(_amount);\n\n// skip adding to warmup contract if period is 0\nif (warmUpPeriod == 0) {\nIYieldy(YIELDY_TOKEN).mint(_recipient, _amount);\n} else {\n// create a claim and mint tokens so a user can claim them once warm up has passed\nwarmUpInfo[_recipient] = Claim({\namount: info.amount + _amount,\ncredits: info.credits +\nIYieldy(YIELDY_TOKEN).creditsForTokenBalance(_amount),\nexpiry: epoch.number + warmUpPeriod\n});\n\nIYieldy(YIELDY_TOKEN).mint(address(this), _amount);\nIERC20Upgradeable(stakingToken).safeTransferFrom(\nmsg.sender,\naddress(this),\n_amount\n);\n_mint(msg.sender, amountToMint);\n}\n", "completion": "token transfers in LiquidityReserve and Staking contract don\u2019t support deflationary ERC20 tokens, and user funds can be lost if stacking token was deflationary"}
{"prompt": "uint256 _previousCirculating,\nuint256 _profit,\nuint256 _epoch\n) internal {\nuint256 rebasePercent = (_profit * WAD) / _previousCirculating;\n_totalSupply = updatedTotalSupply;\n\n_storeRebase(updatedTotalSupply, _profit, _epoch);\n}\n", "completion": "_storeRebase() is called with the wrong parameters"}
{"prompt": "// we know about the issues surrounding block.timestamp, using it here will not cause any problems\nif (epoch.endTime <= block.timestamp) {\nIYieldy(YIELDY_TOKEN).rebase(epoch.distribute, epoch.number);\n\nepoch.endTime = epoch.endTime + epoch.duration;\nepoch.timestamp = block.timestamp;\nepoch.number++;\n\nuint256 balance = contractBalance();\nuint256 staked = IYieldy(YIELDY_TOKEN).totalSupply();\n\nif (balance <= staked) {\nepoch.distribute = 0;\n} else {\nepoch.distribute = balance - staked;\n}\n}\n}\n\n", "completion": "Staking: rebase() does not rebase according to the status of the current epoch."}
{"prompt": "require(isReserveEnabled, \"Not enabled yet\");\nuint256 coolDownAmount = IStaking(stakingContract)\n.coolDownInfo(address(this))\n.amount;\nif (coolDownAmount == 0) {\nuint256 amount = IERC20Upgradeable(rewardToken).balanceOf(\naddress(this)\n);\nif (amount > 0) IStaking(stakingContract).unstake(amount, false);\n}\n}\n}\n", "completion": "Removal of liquidity from the reserve can be griefed"}
{"prompt": "// prevent unstaking if override due to vulnerabilities asdf\nrequire(!isUnstakingPaused, \"Unstaking is paused\");\nif (_trigger) {\nrebase();\n}\n_retrieveBalanceFromUser(_amount, msg.sender);\n\nClaim storage userCoolInfo = coolDownInfo[msg.sender];\n\n// try to claim withdraw if user has withdraws to claim function will check if withdraw is valid\nclaimWithdraw(msg.sender);\n\ncoolDownInfo[msg.sender] = Claim({\namount: userCoolInfo.amount + _amount,\ncredits: userCoolInfo.credits +\nIYieldy(YIELDY_TOKEN).creditsForTokenBalance(_amount),\nexpiry: epoch.number + coolDownPeriod\n});\n\nrequestWithdrawalAmount += _amount;\nsendWithdrawalRequests();\n}\n\n", "completion": "Staking: the rebase function needs to be called before calling the function in the Yieldy contract that uses the rebasingCreditsPerToken variable"}
{"prompt": "@notice addLiquidity for the stakingToken and receive lrToken in exchange\n@param _amount uint - amount of staking tokens to add\n */\nfunction addLiquidity(uint256 _amount) external {\nrequire(isReserveEnabled, \"Not enabled yet\");\nuint256 stakingTokenBalance = IERC20Upgradeable(stakingToken).balanceOf(\naddress(this)\n);\nuint256 rewardTokenBalance = IERC20Upgradeable(rewardToken).balanceOf(\naddress(this)\n);\nuint256 lrFoxSupply = totalSupply();\nuint256 coolDownAmount = IStaking(stakingContract)\n.coolDownInfo(address(this))\n.amount;\nuint256 totalLockedValue = stakingTokenBalance +\nrewardTokenBalance +\ncoolDownAmount;\n\nuint256 amountToMint = (_amount * lrFoxSupply) / totalLockedValue;\nIERC20Upgradeable(stakingToken).safeTransferFrom(\nmsg.sender,\naddress(this),\n_amount\n);\n_mint(msg.sender, amountToMint);\n}\n\n", "completion": "User fund lose in addLiquidity() of LiquidityReserve by increasing (totalLockedValue / totalSupply()) to very large number by attacker"}
{"prompt": "require(_totalSupply < MAX_SUPPLY, \"Max supply\");\nemit Transfer(address(0), _address, _amount);\n}\n", "completion": "Cannot mint to exactly max supply using _mint function"}
{"prompt": "function removeLiquidity(uint256 _amount) external {\n// check balance before removing liquidity\nrequire(_amount <= balanceOf(msg.sender), \"Not enough lr tokens\");\n", "completion": "MINIMUM_LIQUIDITY checks missing - Bringing Liquidity below required min"}
{"prompt": "function _requestWithdrawalFromTokemak(uint256 _amount) internal {\nITokePool tokePoolContract = ITokePool(TOKE_POOL);\nuint256 balance = ITokePool(TOKE_POOL).balanceOf(address(this));\n", "completion": "Incorrect withdrawal requested"}
{"prompt": "function preSign(bytes calldata orderUid) external onlyOwner {\nICowSettlement(COW_SETTLEMENT).setPreSignature(orderUid, true);\n}\n", "completion": "Staking preSign could use some basic validations"}
{"prompt": "endTime: _firstEpochEndTime,\ndistribute: 0\n});\n", "completion": "coolDown & warmUp period do not work when a low _firstEpochEndTime is passed to initialize"}
{"prompt": "// check range before setting fee\nrequire(_fee <= BASIS_POINTS, \"Out of range\");\nfee = _fee;\n\nemit FeeChanged(_fee);\n}\n\n", "completion": "instantUnstake function can be frontrunned with fee increase"}
{"prompt": "uint256 amountMinusFee = _amount - ((_amount * fee) / BASIS_POINTS);\n\nIERC20Upgradeable(rewardToken).safeTransferFrom(\n", "completion": "instantUnstake fee can be avoided"}
{"prompt": "(bool success, uint256[] memory amounts) = callOperator(_order, _inputToken, _outputToken);\n// We raise the following error in case the call to the operator failed\n// We do not check the calldata to raise the specific error for now\n(bool success, ) = augustusSwapper.call(swapCallData);\nrequire(success, \"PSO: SWAP_FAILED\");\n\n", "completion": "User can bypass entryFee by sending arbitrary calldata to ParaSwap operator"}
{"prompt": "_onlyGovernanceOrStrategist();\n_onlyNotProtectedTokens(token);\n\nuint256 toSend = IERC20Upgradeable(token).balanceOf(address(this));\n_handleRewardTransfer(token, toSend);\n}\n\n// NOTE: BADGER is emitted through the tree\nif (token == BADGER) {\n_sendBadgerToTree(amount);\n} else {\n// NOTE: All other tokens are sent to bribes processor\n_sendTokenToBribesProcessor(token, amount);\n}\n}\n\n// TODO: Too many SLOADs\nIERC20Upgradeable(token).safeTransfer(address(bribesProcessor), amount);\nemit RewardsCollected(token, amount);\n}\n\n", "completion": "Attacker can call sweepRewardToken() when bribesProcessor==0 and reward funds will be lost because there is no check in sweepRewardToken() and _handleRewardTransfer() and _sendTokenToBribesProcessor()"}
{"prompt": "\n// Claim auraBAL from locker\nLOCKER.getReward(address(this));\n\nharvested = new TokenAmount[](1);\nharvested[0].token = address(AURA);\n\nuint256 auraBalEarned = AURABAL.balanceOf(address(this)).sub(auraBalBalanceBefore);\n// auraBAL -> BAL/ETH BPT -> WETH -> AURA\nfunction claimBribesFromHiddenHand(IRewardDistributor hiddenHandDistributor, IRewardDistributor.Claim[] calldata _claims) external nonReentrant {\n_onlyGovernanceOrStrategist();\nrequire(address(bribesProcessor) != address(0), \"Bribes processor not set\");\n", "completion": "auraBAL can be stuck into the Strategy contract"}
{"prompt": "uint256 balEthBptEarned = BALANCER_VAULT.swap(singleSwap, fundManagement, 0, type(uint256).max);\n\n// Withdraw BAL/ETH BPT -> WETH\nharvested[0].amount = BALANCER_VAULT.swap(singleSwap, fundManagement, 0, type(uint256).max);\n}\n\n", "completion": "_harvest has no slippage protection when swapping auraBAL for AURA"}
{"prompt": "IERC20Upgradeable(BADGER).safeTransfer(BADGER_TREE, amount);\n_processExtraToken(address(BADGER), amount);\n}\nIERC20Upgradeable(_token).safeTransfer(vault, _amount);\nIVault(vault).reportAdditionalToken(_token);\n}\n_sendBadgerToTree(amount);\n} else {\n", "completion": "Badger rewards from Hidden Hand can permanently prevent Strategy from receiving bribes"}
{"prompt": "balanceOfPool() == 0 && LOCKER.balanceOf(address(this)) == 0,\n\"You have to wait for unlock or have to manually rebalance out of it\"\n);\n\n", "completion": "Withdrawing all funds at once to vault can be DoS attacked by frontrunning and locking dust"}
{"prompt": "address from,\naddress to,\nOrderTypes.OrderItem calldata item\n ) internal {\nif (IERC165(item.collection).supportsInterface(0x80ac58cd)) {\n _transferERC721s(from, to, item);\n} else if (IERC165(item.collection).supportsInterface(0xd9b67a26)) {\n _transferERC1155s(from, to, item);\n}\n }\n\n", "completion": "Some real-world NFT tokens may support both ERC721 and ERC1155 standards, which may break InfinityExchange::_transferNFTs"}
{"prompt": " function _transferNFTs(\naddress from,\naddress to,\n", "completion": "_transferNFTs() succeeds even if no transfer is performed"}
{"prompt": "// if the execution currency is weth, we can send the protocol fee and gas cost in one transfer to save gas\n// else we need to send the protocol fee separately in the execution currency\nif (buy.execParams[1] == weth) {\n IERC20(weth).safeTransferFrom(buy.signer, address(this), protocolFee + gasCost);\n} else {\n IERC20(buy.execParams[1]).safeTransferFrom(buy.signer, address(this), protocolFee);\n IERC20(weth).safeTransferFrom(buy.signer, address(this), gasCost);\n}\n }\n", "completion": "Maker order buyer is forced to reimburse the gas cost at any tx.gasprice"}
{"prompt": "OrderTypes.MakerOrder[] calldata makerOrders1,\nOrderTypes.MakerOrder[] calldata makerOrders2\n ) external {\nuint256 startGas = gasleft();\nuint256 numMakerOrders = makerOrders1.length;\nrequire(msg.sender == MATCH_EXECUTOR, 'OME');\nrequire(numMakerOrders == makerOrders2.length, 'mismatched lengths');\n\n// the below 3 variables are copied to memory once to save on gas\n// an SLOAD costs minimum 100 gas where an MLOAD only costs minimum 3 gas\n// since these values won't change during function execution, we can save on gas by copying them to memory once\n// instead of SLOADing once for each loop iteration\nuint16 protocolFeeBps = PROTOCOL_FEE_BPS;\nuint32 wethTransferGasUnits = WETH_TRANSFER_GAS_UNITS;\naddress weth = WETH;\n", "completion": "Protocol fee rate can be arbitrarily modified by the owner and the new rate will apply to all existing orders"}
{"prompt": " function rescueETH(address destination) external payable onlyOwner {\n(bool sent, ) = destination.call{value: msg.value}('');\nrequire(sent, 'failed');\n }\n\n", "completion": "Accumulated ETH fees of InfinityExchange cannot be retrieved"}
{"prompt": "\n receive() external payable {}\n\n function rescueETH(address destination) external payable onlyOwner {\n(bool sent, ) = destination.call{value: msg.value}('');\nrequire(sent, 'failed');\n }\n\n", "completion": "Overpayment of native ETH is not refunded to buyer"}
{"prompt": " function matchOneToManyOrders(\nOrderTypes.MakerOrder calldata makerOrder,\nOrderTypes.MakerOrder[] calldata manyMakerOrders\n isUserOrderNonceExecutedOrCancelled[makerOrder.signer][makerOrder.constraints[5]] = true;\n} else {\n uint256 protocolFee;\n isUserOrderNonceExecutedOrCancelled[makerOrder.signer][makerOrder.constraints[5]] = true;\n uint256 gasCost = (startGas - gasleft() + WETH_TRANSFER_GAS_UNITS) * tx.gasprice;\n // if the execution currency is weth, we can send the protocol fee and gas cost in one transfer to save gas\n", "completion": "Reentrancy from matchOneToManyOrders"}
{"prompt": " uint256 startGasPerOrder = gasleft() + ((startGas - gasleft()) / numMakerOrders);\n require(_complications.contains(makerOrders1[i].execParams[0]), 'invalid complication');\n (bool canExec, uint256 execPrice) = IComplication(makerOrders1[i].execParams[0]).canExecMatchOneToOne(\nuint256 startGasPerOrder = gasleft() + ((startGas + 20000 - gasleft()) / ordersLength);\n_matchOneMakerSellToManyMakerBuys(\n makerOrderHash,\n uint256 startGasPerOrder = gasleft() + ((startGas - gasleft()) / numSells);\n (bool executionValid, uint256 execPrice) = IComplication(sells[i].execParams[0]).canExecMatchOrder(\nsells[i],\n", "completion": "InfinityExchange computes gas refunds in a way where the first order\u2019s buyer pays less than the later ones"}
{"prompt": "// for non ETH orders, IERC20 safeTransferFrom will throw error if insufficient amount is sent\nif (isMakerSeller && currency == address(0)) {\n require(msg.value >= totalPrice, 'invalid total price');\n}\n }\n// for non ETH orders, IERC20 safeTransferFrom will throw error if insufficient amount is sent\nif (isMakerSeller && currency == address(0)) {\n require(msg.value >= totalPrice, 'invalid total price');\n}\n }\n", "completion": "ETH mistakenly sent over with ERC20 based takeOrders and takeMultipleOneOrders calls will be lost"}
{"prompt": " function matchOneToManyOrders(\nOrderTypes.MakerOrder calldata makerOrder,\nOrderTypes.MakerOrder[] calldata manyMakerOrders\n", "completion": "Bug in MatchOneToManyOrders may cause tokens theft"}
{"prompt": "WETH_TRANSFER_GAS_UNITS = _wethTransferGasUnits;\nemit NewWethTransferGasUnits(_wethTransferGasUnits);\n }\n\n// if the execution currency is weth, we can send the protocol fee and gas cost in one transfer to save gas\n// else we need to send the protocol fee separately in the execution currency\nif (buy.execParams[1] == weth) {\n IERC20(weth).safeTransferFrom(buy.signer, address(this), protocolFee + gasCost);\n} else {\n IERC20(buy.execParams[1]).safeTransferFrom(buy.signer, address(this), protocolFee);\n IERC20(weth).safeTransferFrom(buy.signer, address(this), gasCost);\n}\n }\n", "completion": "Malicious governance can use updateWethTranferGas to steal WETH from buyers"}
{"prompt": "doItemsIntersect(sell.nfts, buy.nfts),\n execPrice\n);\n", "completion": "Incorrect condition marks valid order as invalid"}
{"prompt": "// if the execution currency is weth, we can send the protocol fee and gas cost in one transfer to save gas\n// else we need to send the protocol fee separately in the execution currency\nif (buy.execParams[1] == weth) {\n IERC20(weth).safeTransferFrom(buy.signer, address(this), protocolFee + gasCost);\n} else {\n IERC20(buy.execParams[1]).safeTransferFrom(buy.signer, address(this), protocolFee);\n IERC20(weth).safeTransferFrom(buy.signer, address(this), gasCost);\n}\n_transferMultipleNFTs(sell.signer, buy.signer, sell.nfts);\n// transfer final amount (post-fees) to seller\nIERC20(buy.execParams[1]).safeTransferFrom(buy.signer, sell.signer, remainingAmount);\n IERC721(item.collection).safeTransferFrom(from, to, item.tokens[i].tokenId);\n unchecked {\n++i;\n", "completion": "Malicious tokens can be used to grief buyers and cause loss of their WETH balance"}
{"prompt": "function AddProposal(uint propId, string memory title, string memory desc, address[] memory targets, \nuint[] memory values, string[] memory signatures, bytes[] memory calldatas) public {\nProposal memory newProp = Proposal(propId, title, desc, targets, values, signatures, calldatas);\n\n", "completion": "Anyone can create Proposal Unigov Proposal-Store.sol"}
{"prompt": "IERC20[] memory pooledTokens = self.pooledTokens;\nfor (uint256 i = 0; i < pooledTokens.length; i++) {\n IERC20 token = pooledTokens[i];\n uint256 balance = self.adminFees[i];\n if (balance != 0) {\ntoken.safeTransfer(to, balance);\n }\n}\n }\n\n", "completion": "Wrong implementation of withdrawAdminFees() can cause the adminFees to be charged multiple times and therefore cause users\u2019 fund loss"}
{"prompt": " function _reconcile(uint32 _origin, bytes memory _message) internal {\n// Parse tokenId and action from the message.\nbytes29 msg_ = _message.ref(0).mustBeMessage();\n function reimburseLiquidityFees(\naddress _token,\nuint256 _liquidityFee,\n", "completion": "Router Owner Could Steal All The Funds Within SponsorVault"}
{"prompt": " function execute(ExecuteArgs calldata _args) external whenNotPaused nonReentrant returns (bytes32) {\n(bytes32 transferId, bool reconciled) = _executeSanityChecks(_args);\n\n", "completion": "Malicious Relayer can Replay Execute Calldata on Different Chains Causing Double-Spend Issue"}
{"prompt": "uint32 _originDomain,\naddress payable _to,\nuint256 _originRelayerFee\n ) external override onlyConnext {\nuint256 sponsoredFee;\nuint256 num;\nuint256 den;\n\nif (address(gasTokenOracle) != address(0)) {\n (num, den) = gasTokenOracle.getRate(_originDomain);\n\n sponsoredFee = (_originRelayerFee * num) / den;\n} else {\n num = rates[_originDomain].num;\n den = rates[_originDomain].den;\n}\n\nif (den != 0) {\n sponsoredFee = (_originRelayerFee * num) / den;\n\n // calculated or max\n sponsoredFee = sponsoredFee > relayerFeeCap ? relayerFeeCap : sponsoredFee;\n // calculated or leftover\n sponsoredFee = sponsoredFee > address(this).balance ? address(this).balance : sponsoredFee;\n\n Address.sendValue(_to, sponsoredFee);\n}\nemit ReimburseRelayerFees(sponsoredFee, _to);\n }\n\n", "completion": "Malicious relayer could exploit sponsor vaults"}
{"prompt": "PriceInfo storage priceInfo = priceRecords[_tokenAddress];\nif (priceInfo.active) {\n uint256 rawTokenAmount = IERC20Extended(priceInfo.token).balanceOf(priceInfo.lpToken);\n uint256 tokenDecimalDelta = 18 - uint256(IERC20Extended(priceInfo.token).decimals());\n uint256 tokenAmount = rawTokenAmount.mul(10**tokenDecimalDelta);\n uint256 rawBaseTokenAmount = IERC20Extended(priceInfo.baseToken).balanceOf(priceInfo.lpToken);\n uint256 baseTokenDecimalDelta = 18 - uint256(IERC20Extended(priceInfo.baseToken).decimals());\n uint256 baseTokenAmount = rawBaseTokenAmount.mul(10**baseTokenDecimalDelta);\n uint256 baseTokenPrice = getTokenPrice(priceInfo.baseToken);\n uint256 tokenPrice = baseTokenPrice.mul(baseTokenAmount).div(tokenAmount);\n\n return tokenPrice;\n} else {\n return 0;\n}\n }\n\n", "completion": "Tokens with decimals larger than 18 are not supported"}
{"prompt": " function _reconcileProcessPortal(\nuint256 _amount,\naddress _local,\n", "completion": "Routers are not Enforced to Repay AAVE Portal Loan"}
{"prompt": "s.transferRelayer[transferId] = msg.sender;\n\n// execute router liquidity when this is a fast transfer\n", "completion": "Relayer Will Not Receive Any Fee If execute Reverts"}
{"prompt": " diamondStorage().acceptanceTimes[keccak256(abi.encode(_diamondCut))] < block.timestamp,\n \"LibDiamond: delay not elapsed\"\n);\nfor (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {\nIDiamondCut.FacetCut[] memory _diamondCut,\naddress _init,\nbytes memory _calldata\n ) internal {\nuint256 acceptance = block.timestamp + _delay;\ndiamondStorage().acceptanceTimes[keccak256(abi.encode(_diamondCut))] = acceptance;\nemit DiamondCutProposed(_diamondCut, _init, _calldata, acceptance);\n }\n\nIDiamondCut.FacetCut[] memory _diamondCut,\naddress _init,\nbytes memory _calldata\n ) internal {\ndiamondStorage().acceptanceTimes[keccak256(abi.encode(_diamondCut))] = 0;\nemit DiamondCutRescinded(_diamondCut, _init, _calldata);\n }\n\n", "completion": "LibDiamond.diamondCut() should check diamondStorage().acceptanceTimes[keccak256(abi.encode(_diamondCut)) != 0"}
{"prompt": " function _reconcileProcessPortal(\nuint256 _amount,\naddress _local,\nSafeERC20.safeApprove(IERC20(_assetIn), address(pool), _amountIn);\namountIn = pool.swapExactOut(_amountOut, _assetIn, _assetOut, _maxIn);\n }\n", "completion": "Did Not Approve To Zero First Causing Certain Token Transfer To Fail"}
{"prompt": " function _executeSanityChecks(ExecuteArgs calldata _args) private view returns (bytes32, bool) {\n// If the sender is not approved relayer, revert\nif (!s.approvedRelayers[msg.sender] && msg.sender != _args.params.agent) {\n", "completion": "Malicious Relayer Could Cause A Router To Provide More Liquidity Than It Should"}
{"prompt": " function _executeSanityChecks(ExecuteArgs calldata _args) private view returns (bytes32, bool) {\n// If the sender is not approved relayer, revert\nif (!s.approvedRelayers[msg.sender] && msg.sender != _args.params.agent) {\n", "completion": "Malicious Relayers Could Favor Their Routers"}
{"prompt": " function removeRouter(address router) external onlyOwner {\n// Sanity check: not empty\nif (router == address(0)) revert RoutersFacet__removeRouter_routerEmpty();\n function removeRouterLiquidityFor(\nuint256 _amount,\naddress _local,\n function getRouterOwner(address _router) public view returns (address) {\naddress _owner = s.routerPermissionInfo.routerOwners[_router];\nreturn _owner == address(0) ? _router : _owner;\n", "completion": "Router Owner Could Be Rugged By Admin"}
{"prompt": " function setWrapper(address _wrapper) external onlyOwner {\naddress old = address(s.wrapper);\nif (old == _wrapper || !Address.isContract(_wrapper)) revert AssetFacet__setWrapper_invalidWrapper();\n", "completion": "Incorrect Adopted mapping on updating wrapper token"}
{"prompt": "bytes32 canonicalId,\nuint256 amountOut,\naddress assetIn,\naddress assetOut,\nuint256 maxAmountIn,\nuint256 deadline\n ) external payable nonReentrant deadlineCheck(deadline) returns (uint256) {\nreturn\n", "completion": "Missing whenNotPaused modifier"}
{"prompt": " * @notice Uses Aave Portals to provide fast liquidity\n */\n function _executePortalTransfer(\nbytes32 _transferId,\nuint256 _fastTransferAmount,\naddress _local,\naddress _router\n ) internal returns (uint256, address) {\n// Calculate local to adopted swap output if needed\n(uint256 userAmount, address adopted) = AssetLogic.calculateSwapFromLocalAssetIfNeeded(_local, _fastTransferAmount);\n\nIAavePool(s.aavePool).mintUnbacked(adopted, userAmount, address(this), AAVE_REFERRAL_CODE);\n\n// Improvement: Instead of withdrawing to address(this), withdraw directly to the user or executor to save 1 transfer\nIAavePool(s.aavePool).withdraw(adopted, userAmount, address(this));\n\n// Store principle debt\ns.portalDebt[_transferId] = userAmount;\n\n", "completion": "BridgeFacet\u2019s _executePortalTransfer ignores underlying token amount withdrawn from Aave pool"}
{"prompt": " (uint256 bridgedAmt, address bridged) = AssetLogic.swapToLocalAssetIfNeeded(\ncanonical,\ntransactingAssetId,\nreturn AssetLogic.swapFromLocalAssetIfNeeded(_args.local, toSwap, _args.params.slippageTol);\n }\n\n", "completion": "Swaps done internally will be not be possible"}
{"prompt": " function repayAavePortal(\naddress _local,\nuint256 _backingAmount,\n", "completion": "Repaying AAVE Loan in _local rather than adopted asset"}
{"prompt": "assets.length == 1 &&\nEncodeDecode.encodeERC1155Id(\nassets[0].currencyId,\n", "completion": "fCash of the wrong maturity and asset can be sent to wrapper address before wrapper is deployed"}
{"prompt": "function moduleIssueHook(ISetToken _setToken, uint256 /* _setTokenAmount */) external override onlyModule(_setToken) {\n_redeemMaturedPositions(_setToken);\n}\nfunction _redeemMaturedPositions(ISetToken _setToken)\ninternal\n{\n", "completion": "Users Might Not Be Able To Purchase Or Redeem SetToken"}
{"prompt": "function _mintFCashPosition(\nISetToken _setToken,\nIWrappedfCashComplete _fCashPosition,\nfunction _approve(\nISetToken _setToken,\nIWrappedfCashComplete _fCashPosition,\n", "completion": "Residual Allowance Might Allow Tokens In SetToken To Be Stolen"}
{"prompt": "function convertToShares(uint256 assets) public view override returns (uint256 shares) {\nuint256 supply = totalSupply();\nif (supply == 0) {\nfunction previewWithdraw(uint256 assets) public view override returns (uint256 shares) {\nif (hasMatured()) {\nshares = convertToShares(assets);\n", "completion": "Rounding Issues In Certain Functions"}
{"prompt": " * @dev Returns boolean indicating if given paymentToken is the underlying of the given fCashPosition\n * @dev Reverts if given token is neither underlying nor asset token of the fCashPosition\n */\nfunction _isUnderlying(\nIWrappedfCashComplete _fCashPosition,\nIERC20 _paymentToken\n)\ninternal\nview\nreturns(bool isUnderlying)\n{\n(IERC20 underlyingToken, IERC20 assetToken) = _getUnderlyingAndAssetTokens(_fCashPosition);\nisUnderlying = _paymentToken == underlyingToken;\nif(!isUnderlying) {\nrequire(_paymentToken == assetToken, \"Token is neither asset nor underlying token\");\n}\n}\n\n", "completion": "The logic of _isUnderlying() in NotionalTradeModule is wrong which will cause mintFCashPosition() and redeemFCashPosition() revert on fcash tokens which asset token is underlying token (asset.tokenType == TokenType.NonMintable)"}
{"prompt": "try wrappedfCashFactory.computeAddress(_currencyId, _maturity) returns(address _computedAddress){\nreturn _fCashPosition == _computedAddress;\n} catch {\nreturn false;\n}\n} catch {\nreturn false;\n}\n}\n", "completion": "IsWrappedFcash check is a gas bomb"}
{"prompt": "function redeemToUnderlying(\nuint256 amount,\naddress receiver,\n", "completion": "transferfCash does not work as expected"}
{"prompt": "address[] memory components,\nuint256[] memory equityUnits,\nuint256[] memory debtUnits\n) = _calculateRequiredComponentIssuanceUnits(_setToken, quantityWithFees, true);\n\n_resolveEquityPositions(_setToken, quantityWithFees, _to, true, components, equityUnits);\n_resolveDebtPositions(_setToken, quantityWithFees, true, components, debtUnits);\n_resolveFees(_setToken, managerFee, protocolFee);\n\n_setToken.mint(_to, _quantity);\n\n\naddress operator = _msgSender();\n\n_callTokensToSend(operator, from, address(0), amount, data, operatorData);\n\n", "completion": "DOS set token through erc777 hook"}
{"prompt": "\nif (msg.sender != owner) {\n_spendAllowance(owner, msg.sender, shares);\n}\n_redeemInternal(shares, receiver, owner);\n\nuint256 balanceAfter = IERC20(asset()).balanceOf(receiver);\nuint256 assets = balanceAfter - balanceBefore;\nemit Withdraw(msg.sender, receiver, owner, assets, shares);\nreturn assets;\n}\n", "completion": "User can alter amount returned by redeem function due to control transfer"}
{"prompt": "require(lastEvent == 0, \"Inflation has already started.\");\nlastEvent = block.timestamp;\nlastInflationDecay = block.timestamp;\n}\n\n", "completion": "Minter.sol#startInflation() can be bypassed."}
{"prompt": "require(amount > 0, Error.INVALID_AMOUNT);\nrequire(totalLockedBoosted > 0, Error.NOT_ENOUGH_FUNDS);\nIERC20(rewardToken).safeTransferFrom(msg.sender, address(this), amount);\n\nRewardTokenData storage curRewardTokenData = rewardTokenData[rewardToken];\n\ncurRewardTokenData.feeIntegral += amount.scaledDiv(totalLockedBoosted);\ncurRewardTokenData.feeBalance += amount;\nemit FeesDeposited(amount);\n}\n\n", "completion": "BkdLocker#depositFees() can be front run to steal the newly added rewardToken"}
{"prompt": "if (!addressProvider.removePool(pool)) {\nreturn false;\n}\naddress lpToken = ILiquidityPool(pool).getLpToken();\n\nif (address(inflationManager) != address(0)) {\n(bool exists, address stakerVault) = addressProvider.tryGetStakerVault(lpToken);\nif (exists) {\ninflationManager.removeStakerVaultFromInflation(stakerVault, lpToken);\n}\n}\n\nreturn true;\n}\n\n", "completion": "Fees from delisted pool still in reward handler will become stuck after delisting"}
{"prompt": "totalAvailableToNow += (currentTotalInflation * (block.timestamp - lastEvent));\nlastEvent = block.timestamp;\nif (block.timestamp >= lastInflationDecay + _INFLATION_DECAY_PERIOD) {\n", "completion": "Total Supply is not guaranteed and is not deterministic."}
{"prompt": "address beneficiary,\nuint256 startEpoch,\nuint256 endEpoch\n) internal view returns (uint256) {\nuint256 totalClaimable;\nfor (uint256 i = startEpoch; i < endEpoch; i = i.uncheckedInc()) {\ntotalClaimable += (\nkeeperRecords[beneficiary].feesInPeriod[i].scaledDiv(perPeriodTotalFees[i])\n).scaledMul(perPeriodTotalInflation[i]);\n}\nreturn totalClaimable;\n}\n}\n\n", "completion": "DoS on KeeperGauge due to division by zero"}
{"prompt": "if (totalStaked > 0) {\nammStakedIntegral += (currentRate * timeElapsed).scaledDiv(totalStaked);\n}\nfunction _userCheckpoint(address user) internal virtual returns (bool) {\npoolCheckpoint();\nperUserShare[user] += balances[user].scaledMul(\n", "completion": "The first AMM Staker will have control over how the shares are calculated."}
{"prompt": "function claimRewards(address beneficiary) external virtual override returns (uint256) {\nrequire(\nmsg.sender == beneficiary || _roleManager().hasRole(Roles.GAUGE_ZAP, msg.sender),\nfunction poolCheckpoint() public virtual override returns (bool) {\nif (killed) {\nreturn false;\n", "completion": "THE first AMM Staker may not receive according rewards because of poor checkpoints"}
{"prompt": "require(newTotalMintedToNow <= totalAvailableToNow, \"Mintable amount exceeded\");\ntotalMintedToNow = newTotalMintedToNow;\nlastEvent = block.timestamp;\nfunction _executeKeeperPoolWeight(\nbytes32 key,\naddress pool,\nfunction _executeLpPoolWeight(\nbytes32 key,\naddress lpToken,\nfunction _executeAmmTokenWeight(\naddress token,\nbytes32 key,\n", "completion": "Amount distributed can be inaccurate when updating weights"}
{"prompt": "poolTotalStaked\n);\n}\npoolLastUpdate = block.timestamp;\nreturn true;\nILpGauge(lpGauge).userCheckpoint(account);\n}\n\n", "completion": "Users can claim extremely large rewards or lock rewards from LpGauge due to uninitialised poolLastUpdate variable"}
{"prompt": "feeBurner.burnToTarget{value: ethBalance}(tokens, targetLpToken);\nuint256 burnedAmount = IERC20(targetLpToken).balanceOf(address(this));\nIERC20(targetLpToken).safeApprove(address(bkdLocker), burnedAmount);\n", "completion": "BkdLocker depositFees can be blocked"}
{"prompt": "ILiquidityPool newPool_ = _underlyingNewPools[underlying_];\nuint256 ethValue_ = underlying_ == address(0) ? underlyingAmount_ : 0;\nnewPool_.depositFor{value: ethValue_}(msg.sender, underlyingAmount_);\n_replacedRewardTokens.remove(newRewardToken);\n_replacedRewardTokens.set(rewardToken, block.timestamp);\nlastMigrationEvent = block.timestamp;\nrewardToken = newRewardToken;\n}\n\nfeeBurner.burnToTarget{value: ethBalance}(tokens, targetLpToken);\nuint256 burnedAmount = IERC20(targetLpToken).balanceOf(address(this));\nIERC20(targetLpToken).safeApprove(address(bkdLocker), burnedAmount);\n", "completion": "There are multiple ways for admins/governance to rug users"}
{"prompt": "payable(msg.sender).transfer(amountIn_);\n}\nemit Swapped(fromToken_, toToken_, amountIn_, amountIn_);\npayable(msg.sender).transfer(amount_);\nreturn amount_;\n}\n", "completion": "Usage of deprecated transfer to send ETH"}
{"prompt": "ammStakedIntegral_ +=\nIController(controller).inflationManager().getAmmRateForToken(ammToken) *\ntimeElapsed.scaledDiv(totalStaked);\n}\nreturn\nif (inflationRecipient == address(0)) {\nammStakedIntegral_ +=\n(IController(controller).inflationManager().getAmmRateForToken(ammToken)) *\n(timeElapsed).scaledDiv(totalStaked);\n}\ncrvStakedIntegral_ += (crvEarned).scaledDiv(totalStaked);\n", "completion": "Inconsistency in view functions can lead to users believing they\u2019re due for more BKD rewards"}
{"prompt": "address keeperGauge = _keeperGauges.get(pool);\nbytes32 key = _getKeeperGaugeKey(pool);\n_prepare(key, 0);\n_executeKeeperPoolWeight(key, pool, true);\n_keeperGauges.remove(pool);\nIKeeperGauge(keeperGauge).kill();\n// Do not delete from the gauges map to allow claiming of remaining balances\nemit KeeperGaugeDelisted(pool, keeperGauge);\n}\n\nrequire(!killed, Error.CONTRACT_PAUSED);\nif (!keeperRecords[beneficiary].firstEpochSet) {\nkeeperRecords[beneficiary].firstEpochSet = true;\nif (keeperGauge != address(0)) {\nIKeeperGauge(keeperGauge).reportFees(beneficiary, keeperAmount, lpTokenAddress);\n}\n\nIActionFeeHandler(feeHandler).payFees(payer, beneficiary, feeAmount, depositToken);\n}\n\n_payFees(payer, beneficiary, vars.depositTotalFeesAmount, position.depositToken);\nif (vars.removePosition) {\nif (position.depositTokenBalance > 0) {\n", "completion": "Potential DoS when removing keeper gauge"}
{"prompt": "uint256 startBoost,\nuint256 maxBoost,\nuint256 increasePeriod,\nuint256 withdrawDelay\n) external override onlyGovernance {\nrequire(currentUInts256[_START_BOOST] == 0, Error.CONTRACT_INITIALIZED);\n_setConfig(_START_BOOST, startBoost);\n_setConfig(_MAX_BOOST, maxBoost);\n_setConfig(_INCREASE_PERIOD, increasePeriod);\n_setConfig(_WITHDRAW_DELAY, withdrawDelay);\n}\n\n", "completion": "it\u2019s possible to initialize contract BkdLocker for multiple times by sending startBoost=0 and each time different values for other parameters"}
{"prompt": "//claim veAsset and extra rewards and disperse to reward contracts\nfunction _earmarkRewards(uint256 _pid) internal {\nPoolInfo storage pool = poolInfo[_pid];\n", "completion": "Gauge Rewards Stuck In VoterProxy Contract When ExtraRewardStashV3 Is Used Within Angle Deployment"}
{"prompt": "function withdraw(address _destination, uint256 _amount) external onlyOwner {\nveToken.safeTransfer(_destination, _amount);\n\n", "completion": "compromised owner can drain funds fromVeTokenMinter.sol"}
{"prompt": "extraRewards.push(_reward);\n}\n\n", "completion": "No check for existing extraRewards during push"}
{"prompt": "function clearExtraRewards() external {\nrequire(msg.sender == rewardManager, \"!authorized\");\ndelete extraRewards;\n", "completion": "User can lose extra rewards"}
{"prompt": "function addPool(\naddress _lptoken,\naddress _gauge,\n", "completion": "Duplicate LP token could lead to incorrect deposits"}
{"prompt": "address _staker,\naddress _minter,\naddress _veAsset,\naddress _escrow,\nuint256 _maxTime\n) {\nstaker = _staker;\nminter = _minter;\nveAsset = _veAsset;\nescrow = _escrow;\nfeeManager = msg.sender;\nmaxTime = _maxTime;\n}\n\n", "completion": "Incorrectly set _maxTime to be in line with the locking maxTime of each veToken could render the deposit of this contract to be unfunctional or even freeze assets inside the contract"}
{"prompt": "operators.remove(_operator);\n}\n\n\nuint256 _pid,\naddress _address,\nuint256 _amount\n) external returns (bool) {\naddress rewardContract = poolInfo[_pid].veAssetRewards;\nrequire(msg.sender == rewardContract || msg.sender == lockRewards, \"!auth\");\nITokenMinter veTokenMinter = ITokenMinter(minter);\n//calc the amount of veAssetEarned\nuint256 _veAssetEarned = _amount.mul(veTokenMinter.veAssetWeights(address(this))).div(\nveTokenMinter.totalWeight()\n);\n//mint reward tokens\nITokenMinter(minter).mint(_address, _veAssetEarned);\n\nreturn true;\n}\n}\n", "completion": "Not updating totalWeight when operator is removed in VeTokenMinter"}
{"prompt": "function mint(address _to, uint256 _amount) external {\nrequire(operators.contains(_msgSender()), \"not an operator\");\n\n", "completion": "Unable To Get Rewards If Admin Withdraws $VE3D tokens From VeTokenMinter Contract"}
{"prompt": "function setFeeInfo(uint256 _lockFeesIncentive, uint256 _stakerLockFeesIncentive) external {\nrequire(msg.sender == feeManager, \"!auth\");\n\nfunction earmarkFees() external returns (bool) {\n//claim fee rewards\nIStaker(staker).claimFees(feeDistro, feeToken);\n", "completion": "Misconfiguration of Fees Incentive Might Cause Tokens To Be Stuck In Booster Contract"}
{"prompt": "require(msg.sender == operator, \"!auth\");\nuint256 amount = balanceOfPool(_gauge).add(IERC20(_token).balanceOf(address(this)));\nwithdraw(_token, _gauge, amount);\nreturn true;\n}\n\naddress _to,\nuint256 _value,\nbytes calldata _data\n) external returns (bool, bytes memory) {\nrequire(msg.sender == operator, \"!auth\");\n\n(bool success, bytes memory result) = _to.call{value: _value}(_data);\nrequire(success, \"!success\");\n\nreturn (success, result);\n}\n}\n", "completion": "Malicious operator can rug pull"}
{"prompt": "if (totalSupply() == 0) {\nreturn rewardPerTokenStored;\n}\nreturn\nrewardPerTokenStored.add(\nlastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(\ntotalSupply()\n)\n);\n}\n\nuint256 supply = totalSupply();\nif (supply == 0) {\nreturn rewardTokenInfo[_rewardToken].rewardPerTokenStored;\n}\nreturn\nrewardTokenInfo[_rewardToken].rewardPerTokenStored.add(\nlastTimeRewardApplicable(_rewardToken)\n.sub(rewardTokenInfo[_rewardToken].lastUpdateTime)\n.mul(rewardTokenInfo[_rewardToken].rewardRate)\n.mul(1e18)\n.div(supply)\n);\n}\n\n", "completion": "Unused rewards(because of totalSupply()==0 for some period) will be locked forever in VE3DRewardPool and BaseRewardPool"}
{"prompt": "function setFeeManager(address _feeM) external {\nrequire(msg.sender == feeManager, \"!auth\");\nfeeManager = _feeM;\n", "completion": "Owner should be allowed to change feeManager"}
{"prompt": "function mint(address _to, uint256 _amount) external {\nrequire(operators.contains(_msgSender()), \"not an operator\");\n\n", "completion": "Admin Privilege in minting to arbitrary address allows operator to dilute tokens"}
{"prompt": "require(operators.contains(veAssetOperator), \"not an veAsset operator\");\ntotalWeight -= veAssetWeights[veAssetOperator];\nveAssetWeights[veAssetOperator] = newWeight;\ntotalWeight += newWeight;\n}\n\n", "completion": "Missing sane bounds on asset weights"}
{"prompt": "require(msg.sender == operator, \"!authorized\");\n\n_burn(_from, _amount);\n}\n}\n", "completion": "Governance can arbitrarily burn VeToken from any address"}
{"prompt": "uint256 ve3TokenBalance = IERC20(rewardTokenInfo[_rewardToken].ve3Token).balanceOf(\naddress(this)\n);\nif (_stake) {\n//lock immediately, transfer directly to staker to skip an erc20 transfer\nIERC20(veAsset).safeTransferFrom(msg.sender, staker, _amount);\n_lockVeAsset();\nif (incentiveVeAsset > 0) {\n//add the incentive tokens here so they can be staked together\n_amount = _amount.add(incentiveVeAsset);\nincentiveVeAsset = 0;\n}\n} else {\n//move tokens here\nIERC20(veAsset).safeTransferFrom(msg.sender, address(this), _amount);\n//defer lock cost to another user\nuint256 callIncentive = _amount.mul(lockIncentive).div(FEE_DENOMINATOR);\n_amount = _amount.sub(callIncentive);\n\n//add to a pool for lock caller\nincentiveVeAsset = incentiveVeAsset.add(callIncentive);\n}\n\n", "completion": "VE3DRewardPool claim in loop depend on pausable token"}
{"prompt": "function balanceOfPool(address _gauge) public view returns (uint256) {\nreturn IGauge(_gauge).balanceOf(address(this));\n}\nuint256 amount = balanceOfPool(_gauge).add(IERC20(_token).balanceOf(address(this)));\nwithdraw(_token, _gauge, amount);\nreturn true;\n", "completion": "VoterProxy incorrectly assumes a 1-1 mapping between the gauge and the LP tokens."}
{"prompt": "require(msg.sender == rewardManager, \"!authorized\");\nrequire(_reward != address(0), \"!reward setting\");\n\nextraRewards.push(_reward);\n}\n\nIRewards(extraRewards[i]).stake(msg.sender, _amount);\n}\n\nfunction addExtraReward(address _reward) external returns (bool) {\nrequire(msg.sender == rewardManager, \"!authorized\");\nrequire(_reward != address(0), \"!reward setting\");\n", "completion": "VE3DRewardPool allows the same reward address to be added multiple times to the extraRewards array"}
{"prompt": "_totalSupply = _totalSupply.add(_amount);\n_balances[msg.sender] = _balances[msg.sender].add(_amount);\n\nrewardPerTokenStored = rewardPerToken();\nlastUpdateTime = lastTimeRewardApplicable();\nif (account != address(0)) {\nrewards[account] = earned(account);\nuserRewardPerTokenPaid[account] = rewardPerTokenStored;\n}\nlastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(\ntotalSupply()\n)\n", "completion": "BaseRewardPool\u2019s rewardPerTokenStored can be inflated and rewards can be stolen"}
{"prompt": "function addReward(\naddress _rewardToken,\naddress _veAssetDeposits,\n", "completion": "User can lose funds"}
{"prompt": "IERC20(lptoken).safeTransferFrom(msg.sender, staker, _amount);\n\n//stake\nIERC20(_rewardToken).safeTransferFrom(msg.sender, address(this), _amount);\nrewardTokenInfo[_rewardToken].queuedRewards += _amount;\n}\n", "completion": "Consistently check account balance before and after transfers for Fee-On-Transfer discrepancies"}
{"prompt": "try IStaker(staker).withdrawAll(pool.lptoken, pool.gauge) {} catch {}\n\npool.shutdown = true;\ngaugeMap[pool.gauge] = false;\n\nemit PoolShuttedDown(_pid);\nreturn true;\n}\n\n", "completion": "Booster\u2019s shutdownPool can freeze user funds"}
{"prompt": "//take difference of before/after(only send new tokens)\nuint256 amount = IERC20(token).balanceOf(address(this));\namount = amount.sub(before);\n\n//send to arbitrator\naddress arb = IDeposit(operator).rewardArbitrator();\nif (arb != address(0)) {\nIERC20(token).safeTransfer(arb, amount);\n}\n}\n}\n", "completion": "ExtraRewardStashV2\u2019s stashRewards can become unavailable"}
{"prompt": "address _to,\nuint256 _value,\nbytes calldata _data\n) external returns (bool, bytes memory) {\nrequire(msg.sender == operator, \"!auth\");\n\n(bool success, bytes memory result) = _to.call{value: _value}(_data);\nrequire(success, \"!success\");\n\nreturn (success, result);\n}\n}\naddress _token,\naddress _gauge,\nuint256 _amount\n) public returns (bool) {\nrequire(msg.sender == operator, \"!auth\");\nuint256 _balance = IERC20(_token).balanceOf(address(this));\nif (_balance < _amount) {\n_amount = _withdrawSome(_gauge, _amount.sub(_balance));\n_amount = _amount.add(_balance);\n}\nIERC20(_token).safeTransfer(msg.sender, _amount);\nreturn true;\n}\n\nfunction withdrawAll(address _token, address _gauge) external returns (bool) {\nrequire(msg.sender == operator, \"!auth\");\nuint256 amount = balanceOfPool(_gauge).add(IERC20(_token).balanceOf(address(this)));\nwithdraw(_token, _gauge, amount);\nreturn true;\n}\n\n", "completion": "Centralisation RIsk: VoterProxy owner may set the operate to an address they own and drain all token balances"}
{"prompt": " logTransaction(\nawait poolManager.addPool(\n \"0x2bD9F7974Bc0E4Cb19B8813F8Be6034F3E772add\",\n \"0x26C2251801D2cfb5461751c984Dc3eAA358bdf0f\",\n \"0x3785Ce82be62a342052b9E5431e9D3a839cfB581\",\n boosterAdd,\n", "completion": "Incorrect deployment parameters"}
{"prompt": "function release(\nIERC20 token,\naddress recipient,\n", "completion": "Attacker could steal almost all the bonus tokens in BathBuddy Vesting Wallet"}
{"prompt": "uint256 _pool = IERC20(underlyingToken).balanceOf(address(this));\nreturn _pool.add(outstandingAmount);\n}\n}\n", "completion": "BathPair.sol#rebalancePair() can be front run to steal the pending rebalancing amount"}
{"prompt": "function handleStratOrderAtID(uint256 id) internal {\nStrategistTrade memory info = strategistTrades[id];\naddress _asset = info.askAsset;\nfunction removeFilledTradeAmount(uint256 amt) external onlyPair {\noutstandingAmount = outstandingAmount.sub(amt);\nemit LogRemoveFilledTradeAmount(\n", "completion": "Outstanding Amount Of A Pool Reduced Although Tokens Are Not Repaid"}
{"prompt": "require(_isApprovedOrOwner(msg.sender, _tokenId), \"caller is not owner nor approved\");\n\naddress owner = ownerOf(_tokenId);\n\n// Clear approval\napprove(address(0), _tokenId);\n// TODO add delegates\n// Remove token\n_removeTokenFrom(msg.sender, _tokenId);\nemit Transfer(owner, address(0), _tokenId);\n}\n\n", "completion": "Users can get unlimited votes"}
{"prompt": "_removeTokenFrom(msg.sender, _tokenId);\nemit Transfer(owner, address(0), _tokenId);\n}\n", "completion": "VotingEscrow\u2019s merge and withdraw aren\u2019t available for approved users"}
{"prompt": "bool prevVoteStatus = (_nCheckPoints > 0) ? checkpoints[account][_nCheckPoints].voted : false;\ncheckpoints[account][_nCheckPoints] = Checkpoint(_timestamp, balance, prevVoteStatus);\nnumCheckpoints[account] = _nCheckPoints + 1;\n", "completion": "User rewards stop accruing after any _writeCheckpoint calling action"}
{"prompt": " function getEpochStart(uint timestamp) public view returns (uint) {\nuint bribeStart = timestamp - (timestamp % (7 days)) + BRIBE_LAG;\nuint bribeEnd = bribeStart + DURATION - COOLDOWN;\n function notifyRewardAmount(address token, uint amount) external lock {\n require(amount > 0);\n if (!isReward[token]) {\nfunction distribute(address _gauge) public lock {\nrequire(isAlive[_gauge]); // killed gauges cannot distribute\nuint dayCalc = block.timestamp % (7 days);\nfunction deliverBribes() external lock {\nrequire(msg.sender == voter);\nIBribe sb = IBribe(bribe);\n function deliverReward(address token, uint epochStart) external lock returns (uint) {\nrequire(msg.sender == gauge);\nuint rewardPerEpoch = tokenRewardsPerEpoch[token][epochStart];\n", "completion": "Bribe Rewards Struck In Contract If Deposited During First Epoch"}
{"prompt": "checkpoints[account][nCheckpoints - 1].voted = voted;\n}\n}\nreward += cp0.balanceOf * (_rewardPerTokenStored1 - _rewardPerTokenStored0) / PRECISION;\n}\nreward += cp.balanceOf * (rewardPerToken(token) - Math.max(_rewardPerTokenStored, userRewardPerTokenStored[token][account])) / PRECISION;\n}\n", "completion": "Voting overwrites checkpoint.voted in last checkpoint, so users can just vote right before claiming rewards"}
{"prompt": "uint16 srcChainId,\nbytes memory srcAddress,\nuint64,\nbytes memory payload\n) external override {\nrequire(fantomSender != address(0), \"NOT_INITIALIZED\");\nrequire(\nmsg.sender == endpoint &&\nsrcChainId == fantomChainId &&\naddressFromPackedBytes(srcAddress) == fantomSender,\n\"UNAUTHORIZED_CALLER\"\n);\n\n(address redemptionAddress, uint256 amountWEVE) = abi.decode(\npayload,\n(address, uint256)\n);\n\nrequire(\n(redeemedWEVE += amountWEVE) <= eligibleWEVE,\n\"cannot redeem more than eligible\"\n);\n(uint256 shareOfUSDC, uint256 shareOfVELO) = previewRedeem(amountWEVE);\n\nrequire(\nUSDC.transfer(redemptionAddress, shareOfUSDC),\n\"USDC_TRANSFER_FAILED\"\n);\nrequire(\nVELO.transfer(redemptionAddress, shareOfVELO),\n\"VELO_TRANSFER_FAILED\"\n);\n}\n\n", "completion": "Attacker can block LayerZero channel"}
{"prompt": "require(gauge == address(0), \"gauge already set\");\ngauge = _gauge;\n }\n\n", "completion": "Gauge set can be front run if bribe and gauge constructors aren\u2019t run atomically"}
{"prompt": "require(_isApprovedOrOwner(msg.sender, _tokenId), \"caller is not owner nor approved\");\n\naddress owner = ownerOf(_tokenId);\n\n// Clear approval\napprove(address(0), _tokenId);\n// TODO add delegates\n// Remove token\n_removeTokenFrom(msg.sender, _tokenId);\nemit Transfer(owner, address(0), _tokenId);\n}\n\n", "completion": "Owner\u2019s delegates should be decreased in _burn()"}
{"prompt": "require(msg.sender == gauge);\nuint rewardPerEpoch = tokenRewardsPerEpoch[token][epochStart];\nif (rewardPerEpoch > 0) {\n _safeTransfer(token, address(gauge), rewardPerEpoch);\n}\nreturn rewardPerEpoch;\n }\n\n", "completion": "Wrong reward distribution in Bribe because deliverReward() won\u2019t set tokenRewardsPerEpoch[token][epochStart to 0"}
{"prompt": "uint adjustedTstamp = block.timestamp < bribeStart ? bribeStart : bribeStart + 7 days;\nif (rewardRate[token] == 0) _writeRewardPerTokenCheckpoint(token, 0, adjustedTstamp);\n(rewardPerTokenStored[token], lastUpdateTime[token]) = _updateRewardPerToken(token);\n_claimFees();\n\nif (block.timestamp >= periodFinish[token]) {\n_safeTransferFrom(token, msg.sender, address(this), amount);\nrewardRate[token] = amount / DURATION;\n} else {\nuint _remaining = periodFinish[token] - block.timestamp;\nuint _left = _remaining * rewardRate[token];\nrequire(amount > _left);\n_safeTransferFrom(token, msg.sender, address(this), amount);\nrewardRate[token] = (amount + _left) / DURATION;\n}\nrequire(rewardRate[token] > 0);\n", "completion": "Wrong calculation for the new rewardRate[token can cause some of the late users can not get their rewards"}
{"prompt": "internal\nreturns (uint256 shares)\n{\nuint256 _pool = underlyingBalance();\nuint256 _before = underlyingToken.balanceOf(address(this));\n\n// **Assume caller is depositor**\nunderlyingToken.transferFrom(msg.sender, address(this), assets);\nuint256 _after = underlyingToken.balanceOf(address(this));\nassets = _after.sub(_before); // Additional check for deflationary tokens\n\n(totalSupply == 0) ? shares = assets : shares = (\n", "completion": "BathToken.sol#_deposit() attacker can mint more shares with re-entrancy from hookable tokens"}
{"prompt": "public\nview\nreturns (uint256 assets)\n", "completion": "First depositor can break minting of shares"}
{"prompt": "bool public stopped;\n\nbool public buyEnabled = true; //buy enabled\nbool public matchingEnabled = true; //true: enable matching,\n//false: revert to expiring market\n/// @dev Below is variable to allow for a proxy-friendly constructor\nbool public initialized;\n\n/// @dev unused deprecated variable for applying a token distribution on top of a trade\nbool public AqueductDistributionLive;\n/// @dev unused deprecated variable for applying a token distribution of this token on top of a trade\naddress public AqueductAddress;\n\n", "completion": "No Storage Gap for Upgradeable Contracts"}
{"prompt": "abi.encode(\nkeccak256(\n\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n),\nkeccak256(bytes(name)),\nkeccak256(bytes(\"1\")),\nchainId,\naddress(this)\n)\n);\nname = string(abi.encodePacked(_symbol, (\" v1\")));\ndecimals = token.decimals(); // v1 Change - 4626 Adherence\n", "completion": "Wrong DOMAIN_SEPARATOR"}
{"prompt": "require(msg.sender == team, \"not team\");\nrequire(numerator <= MAX_PROPOSAL_NUMERATOR, \"numerator too high\");\nproposalNumerator = numerator;\n}\n\n", "completion": "VeloGovernor: proposalNumerator and team are updated by team, not governance"}
{"prompt": "uint256 pay_amt, //maker (ask) sell how much\n// ERC20 nativeETH, //maker (ask) sell which token\nuint256 buy_amt, //maker (ask) buy how much\nERC20 buy_gem, //maker (ask) buy which token\nuint256 pos //position to insert offer, 0 should be used if unknown\n) external payable returns (uint256) {\nrequire(\nmsg.value >= pay_amt,\n\"didnt send enough native ETH for WETH offer\"\n);\nuint256 _before = ERC20(buy_gem).balanceOf(address(this));\nWETH9(wethAddress).deposit{value: pay_amt}();\nuint256 id = RubiconMarket(RubiconMarketAddress).offer(\npay_amt,\nERC20(wethAddress),\nbuy_amt,\nbuy_gem,\npos\n);\nuint256 _after = ERC20(buy_gem).balanceOf(address(this));\nif (_after > _before) {\n//return any potential fill amount on the offer\nERC20(buy_gem).transfer(msg.sender, _after - _before);\n}\nreturn id;\n}\n\n", "completion": "RubiconRouter: Offers created through offerWithETH() can be cancelled by anyone"}
{"prompt": "uint256 pay_amt, //maker (ask) sell how much\nERC20 pay_gem, //maker (ask) sell which token\nuint256 buy_amt, //maker (ask) buy how much\n// ERC20 nativeETH, //maker (ask) buy which token\nuint256 pos //position to insert offer, 0 should be used if unknown\n) external returns (uint256) {\nERC20(pay_gem).transferFrom(msg.sender, address(this), pay_amt);\n\nuint256 _before = ERC20(wethAddress).balanceOf(address(this));\nuint256 id = RubiconMarket(RubiconMarketAddress).offer(\npay_amt,\npay_gem,\nbuy_amt,\nERC20(wethAddress),\npos\n);\nuint256 _after = ERC20(wethAddress).balanceOf(address(this));\nif (_after > _before) {\n//return any potential fill amount on the offer as native ETH\nuint256 delta = _after - _before;\nWETH9(wethAddress).withdraw(delta);\nmsg.sender.transfer(delta);\n}\nreturn id;\n}\n\n", "completion": "RubiconRouter: Offers created through offerForETH cannot be cancelled"}
{"prompt": "function distributeBonusTokenRewards(\naddress receiver,\nuint256 sharesWithdrawn,\n", "completion": "BathToken LPs Unable To Receive Bonus Token Due To Lack Of Wallet Setter Method"}
{"prompt": "function placeMarketMakingTrades(\naddress[2] memory tokenPair, // ASSET, Then Quote\nuint256 askNumerator, // Quote / Asset\nfunction enforceReserveRatio(\naddress underlyingAsset,\naddress underlyingQuote\n", "completion": "Ineffective ReserveRatio Enforcement"}
{"prompt": "msg.sender.transfer(delta);\n}\n}\nmsg.sender.transfer(buy_amt); // Return native ETH\n// Return unspent coins to sender\nif (max_fill_amount > fill) {\nmsg.sender.transfer(delta);\n}\nreturn id;\nmsg.sender.transfer(pay_amt);\n}\n\nmsg.sender.transfer(withdrawnWETH);\n}\n\nmsg.sender.transfer(fill);\n}\n}\n", "completion": "Use call() instead of transfer() when transferring ETH in RubiconRouter"}
{"prompt": "ERC20(route[route.length - 1]).transfer(to, currentAmount);\n}\n\n", "completion": "Use safeTransfer()/safeTransferFrom() instead of transfer()/transferFrom()"}
{"prompt": "ERC20 buy_gem,\nuint256 buy_amt,\nuint256 max_fill_amount,\nuint256 expectedMarketFeeBPS\n) external payable returns (uint256 fill) {\naddress _weth = address(wethAddress);\nuint256 _before = ERC20(_weth).balanceOf(address(this));\nuint256 max_fill_withFee = max_fill_amount.add(\nmax_fill_amount.mul(expectedMarketFeeBPS).div(10000)\n);\nrequire(\nmsg.value >= max_fill_withFee,\n\"must send as much ETH as max_fill_withFee\"\n);\nWETH9(wethAddress).deposit{value: max_fill_withFee}(); // Pay with native ETH -> WETH\n", "completion": "RubiconRouter: Excess ether did not return to the user"}
{"prompt": "function _deposit(uint256 assets, address receiver)\ninternal\nreturns (uint256 shares)\n", "completion": "Inconsistent Order Book Accounting When Working With Transfer-On-Fee or Deflationary Tokens"}
{"prompt": "desiredPairedAsset.approve(\npairedPool,\ninitialLiquidityExistingBathToken\nERC20(toApprove).approve(RubiconMarketAddress, 2**256 - 1);\n}\n\nunderlyingToken.approve(RubiconMarketAddress, 2**256 - 1);\n}\n\n", "completion": "USDT is not supported because of approval mechanism"}
{"prompt": "receive() external payable {}\n\n/**\n", "completion": "BathBuddy locks up Ether it receives"}
{"prompt": "amountWithdrawn = assets.sub(_fee);\nshares = convertToShares(amountWithdrawn);\n}\n", "completion": "previewWithdraw calculates shares wrongly"}
{"prompt": "function adminWriteBathToken(ERC20 overwriteERC20, address newBathToken)\nexternal\nonlyAdmin\n{\ntokenToBathToken[address(overwriteERC20)] = newBathToken;\nemit LogNewBathToken(\naddress(overwriteERC20),\nnewBathToken,\naddress(0),\nblock.timestamp,\nmsg.sender\n);\n}\n\nfunction setMarket(address newMarket) external onlyAdmin {\nRubiconMarketAddress = newMarket;\n}\n\nfunction setBonusToken(address newBonusERC20) external onlyBathHouse {\nbonusTokens.push(newBonusERC20);\n}\n\n", "completion": "Admin rug vectors"}
{"prompt": "function setBonusToken(address newBonusERC20) external onlyBathHouse {\nbonusTokens.push(newBonusERC20);\n}\nfunction distributeBonusTokenRewards(\naddress receiver,\nuint256 sharesWithdrawn,\naddress(token),\nuint64(block.timestamp)\n) - released(address(token));\nif (releasable > 0) {\n", "completion": "Early funds withdrawers can get bonus in multiples of vested bonus tokens (e.g. 2-times, 3-times, etc.)"}
{"prompt": "feeBPS = _newFeeBPS;\nreturn true;\n}\nfeeBPS = _feeBPS;\n}\n\namountWithdrawn = assets.sub(_fee);\nshares = convertToShares(amountWithdrawn);\n", "completion": "No cap on fees can result in a DOS in BathToken.withdraw()"}
{"prompt": "address destination,\naddress filledAssetToRebalance, /* sister or fill asset */\nuint256 stratProportion,\nuint256 rebalAmt\n) external onlyPair {\nuint256 stratReward = (stratProportion.mul(rebalAmt)).div(10000);\nIERC20(filledAssetToRebalance).transfer(\ndestination,\nrebalAmt.sub(stratReward)\n);\nIERC20(filledAssetToRebalance).transfer(msg.sender, stratReward);\n\nemit LogRebalance(\nIERC20(underlyingToken),\ndestination,\nIERC20(filledAssetToRebalance),\nrebalAmt,\nstratReward,\nunderlyingBalance(),\noutstandingAmount,\ntotalSupply\n);\n}\n\n", "completion": "Centralized risks allows rogue pool behavior in BathToken."}
{"prompt": "function placeMarketMakingTrades(\naddress[2] memory tokenPair, // ASSET, Then Quote\nuint256 askNumerator, // Quote / Asset\n", "completion": "Strategist can transfer user funds to themselves"}
{"prompt": "function approveStrategist(address strategist) public onlyAdmin {\napprovedStrategists[strategist] = true;\n}\n", "completion": "Strategists can\u2019t be removed"}
{"prompt": "function swapForETH(\nuint256 pay_amt,\nuint256 buy_amt_min,\n", "completion": "User will loose funds"}
{"prompt": "IAqueduct(AqueductAddress).distributeToMakerAndTaker(\ngetOwner(id),\nmsg.sender\n);\n}\nfunction(uint256, uint256) returns (bool) fn = matchingEnabled\n", "completion": "Deprecated variables may cause DoS"}
{"prompt": "token.transfer(recipient, amountWithdrawn);\n\n_erc20Released[address(token)] += amount;\n", "completion": "Possible token reentrancy in release() of BathBuddy.sol"}
{"prompt": "pay_amt * 1 ether <\nwdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)\n) {\npay_amt * 10**9,\nrdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)\n) / 10**9;\nbuy_amt * 1 ether <\nwdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)\n) {\nbuy_amt * 10**9,\nrdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)\n) / 10**9\npay_amt * 10**9,\nrdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)\n) / 10**9\nbuy_amt * 10**9,\nrdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)\n) / 10**9\n", "completion": "Multiple Unsafe Arithmetic Operations"}
{"prompt": "address newOne = _createBathToken(newBathTokenUnderlying, address(0)); // NOTE: address(0) as feeAdmin means fee is paid to pool holders\n\n// Deposit initial liquidity posted of newBathTokenUnderlying\nIERC20(address(token)).approve(RubiconMarketAddress, 2**256 - 1);\nemit LogInit(block.timestamp);\n\n", "completion": "Malicious pools can be deployed through BathHouse"}
{"prompt": "_offer.buy_gem.transferFrom(msg.sender, feeTo, fee),\n\"Insufficient funds to cover fee\"\n);\n\n", "completion": "RubiconMarket.feeTo set to zero-address can DoS buy function"}
{"prompt": "function maxSellAllAmount(\nERC20 pay_gem,\nERC20 buy_gem,\n", "completion": "RubiconRouter maxSellAllAmount does not transfer user\u2019s fund into its address, causing calls to always revert"}
{"prompt": "function maxBuyAllAmount(\nERC20 buy_gem,\nERC20 pay_gem,\nfunction maxSellAllAmount(\nERC20 pay_gem,\nERC20 buy_gem,\n", "completion": "maxSellAllAmount and maxBuyAllAmount functions can be unintentionally paused (always revert)."}
{"prompt": "initialTotalSupply\n);\nfunction vestedAmount(address token, uint64 timestamp)\npublic\nview\n", "completion": "BathBuddy contract\u2019s vestedAmount function includes fees leading to users being disproportionately rewarded after whale withdraws"}
{"prompt": "// Make a new offer. Takes funds from the caller into market escrow.\n//\n// If matching is enabled:\nfunction insert(\nuint256 id, //maker (ask) id\nuint256 pos //position to insert into\n", "completion": "Lack of Access Control for offer(uint, ERC20, uint, ERC20) and insert(uint, unint)"}
{"prompt": "if (isOfferSorted(id)) {\nrequire(_unsort(id));\n} else {\nrequire(_hide(id));\n}\n}\nreturn super.cancel(id); //delete the offer.\n", "completion": "Changing matchingEnabled in RubiconMarket breaks protocol"}
{"prompt": "RubiconMarketAddress = IBathHouse(_bathHouse).getMarket();\n\n// Shape variables for dynamic inventory management\nRubiconMarketAddress = newMarket;\n}\n\n", "completion": "RubiconMarketAddress in BathPair can\u2019t be updated"}
{"prompt": "if (isOfferSorted(id)) {\n//offers[id] must be removed from sorted list because all of it is bought\n_unsort(id);\n", "completion": "RubiconMarket buys can not be disabled if offer matching is disabled"}
{"prompt": "require(fantomSender == address(0), \"ALREADY_INITIALIZED\");\nrequire(\nUSDC.transferFrom(msg.sender, address(this), _redeemableUSDC),\n", "completion": "Alter velo receptions computation"}
{"prompt": " require(amount > 0);\n if (!isReward[token]) {\nrequire(rewards.length < MAX_REWARD_TOKENS, \"too many rewards tokens\");\n }\n // bribes kick in at the start of next bribe period\n uint adjustedTstamp = getEpochStart(block.timestamp);\n uint epochRewards = tokenRewardsPerEpoch[token][adjustedTstamp];\n\n _safeTransferFrom(token, msg.sender, address(this), amount);\n tokenRewardsPerEpoch[token][adjustedTstamp] = epochRewards + amount;\n\n if (!isReward[token]) {\n isReward[token] = true;\n rewards.push(token);\n IGauge(gauge).addBribeRewardToken(token);\n }\n\n emit NotifyReward(msg.sender, token, adjustedTstamp, amount);\n }\n\n", "completion": "Malicious user can populate rewards array with tokens of their interest reaching limits of MAX_REWARD_TOKENS"}
{"prompt": " tokenRewardsPerEpoch[token][adjustedTstamp] = epochRewards + amount;\n\nrequire(msg.sender == gauge);\nuint rewardPerEpoch = tokenRewardsPerEpoch[token][epochStart];\nif (rewardPerEpoch > 0) {\n _safeTransfer(token, address(gauge), rewardPerEpoch);\n}\nreturn rewardPerEpoch;\n }\n\n", "completion": "Bribe.sol is not meant to handle fee-on-transfer tokens"}
{"prompt": "ILayerZeroEndpoint(endpoint).send{value: msg.value}(\noptimismChainId,\nabi.encodePacked(optimismReceiver),\n", "completion": "RedemptionSender should estimate fees to prevent failed transactions"}
{"prompt": "_updateRewardForAllTokens();\n\nuint tokenId = 0;\nif (amount == balanceOf[msg.sender]) {\ntokenId = tokenIds[msg.sender];\n}\nwithdrawToken(amount, tokenId);\n}\n\nfunction withdrawToken(uint amount, uint tokenId) public lock {\ntotalSupply -= amount;\nbalanceOf[msg.sender] -= amount;\n_safeTransfer(stake, msg.sender, amount);\n\n", "completion": "Rewards aren\u2019t updated before user\u2019s balance change in Gauge\u2019s withdrawToken"}
{"prompt": "function notifyRewardAmount(address token, uint amount) external lock {\nrequire(token != stake);\nrequire(amount > 0);\n", "completion": "Griefing Attack By Extending The Reward Duration"}
{"prompt": "require(isAlive[_gauge]); // killed gauges cannot distribute\nuint dayCalc = block.timestamp % (7 days);\nrequire((dayCalc < BRIBE_LAG) || (dayCalc > (DURATION + BRIBE_LAG)), \"cannot claim during votes period\");\nIMinter(minter).update_period();\n_updateFor(_gauge);\nuint _claimable = claimable[_gauge];\nif (_claimable > IGauge(_gauge).left(base) && _claimable / DURATION > 0) {\nclaimable[_gauge] = 0;\nIGauge(_gauge).notifyRewardAmount(base, _claimable);\nemit DistributeReward(msg.sender, _gauge, _claimable);\n// distribute bribes & fees too\nIGauge(_gauge).deliverBribes();\n}\n}\n\n", "completion": "Rewards can be locked in Bribe contract because distributing them depends on base token reward amount and Gauge.deliverBribes() is not always called by Voter.distribute()"}
{"prompt": " function notifyRewardAmount(address token, uint amount) external lock {\n require(amount > 0);\n if (!isReward[token]) {\nfunction deliverBribes() external lock {\nrequire(msg.sender == voter);\nIBribe sb = IBribe(bribe);\n", "completion": "Bribe Rewards Not Collected In Current Period Will Be Lost Forever"}
{"prompt": "_orderStatus[orderHash].numerator = uint120(\nfilledNumerator + numerator\n);\n_orderStatus[orderHash].denominator = uint120(denominator);\n}\n} else {\n_orderStatus[orderHash].numerator = uint120(numerator);\n_orderStatus[orderHash].denominator = uint120(denominator);\n}\n_orderStatus[orderHash].denominator = uint120(denominator);\n}\n\n", "completion": "Truncation in OrderValidator can lead to resetting the fill and selling more tokens"}
{"prompt": "_verifyProof(\ncriteriaResolver.identifier,\nidentifierOrCriteria,\n", "completion": "Merkle Tree criteria can be resolved by wrong tokenIDs"}
{"prompt": "errorBuffer := or(\n errorBuffer,\n or(\n", "completion": "_aggregateValidFulfillmentOfferItems() can be tricked to accept invalid inputs"}
{"prompt": "parameters.additionalRecipients.length + 1,\nparameters.totalOriginalAdditionalRecipients\n);\n\n", "completion": "Wrong items length assertion in basic order"}
{"prompt": " require(sent, Errors.VT_COLLATERAL_WITHDRAW_INVALID);\n} else {\n // Case of stETH withdraw request from user, so directly send\n", "completion": "The check for value transfer success is made after the return statement in _withdrawFromYieldPool of LidoVault"}
{"prompt": "require(withdrawAmount >= _amount.percentMul(99_00), Errors.VT_WITHDRAW_AMOUNT_MISMATCH);\n\nemit WithdrawCollateral(_asset, _to, _amount);\n_addressesProvider,\n_addressesProvider.getAddress('STETH_ETH_POOL'),\nLIDO,\nETH,\n_amount,\n200\n );\n\n", "completion": "Hard-coded slippage may freeze user funds during market turbulence"}
{"prompt": " uint256 decimal = IERC20Detailed(_asset).decimals();\n _amount = _amountToWithdraw.mul(this.pricePerShare()).div(10**decimal);\n}\nrequire(withdrawAmount >= _amount.percentMul(99_00), Errors.VT_WITHDRAW_AMOUNT_MISMATCH);\n", "completion": "Withdrawing ETH collateral with max uint256 amount value reverts transaction"}
{"prompt": " uint256 public constant UNISWAP_FEE = 10000; // 1%\n uint256 public constant SLIPPAGE = 500; // 5%\n\n UNISWAP_FEE,\n SLIPPAGE\n);\n", "completion": "UNISWAP_FEE is hardcoded which will lead to significant losses compared to optimal routing"}
{"prompt": "for (uint256 i = 0; i < extraRewardsLength; i++) {\n address _extraReward = IConvexBaseRewardPool(baseRewardPool).extraRewards(i);\n address _rewardToken = IRewards(_extraReward).rewardToken();\n _transferYield(_rewardToken);\n}\n }\nfor (uint256 i = 0; i < assetYields.length; i++) {\n if (assetYields[i].amount > 0) {\nuint256 _amount = _convertToStableCoin(assetYields[i].asset, assetYields[i].amount);\n// 3. deposit Yield to pool for suppliers\n_depositYield(assetYields[i].asset, _amount);\n }\n}\n }\n", "completion": "processYield() and distributeYield() may run out of gas and revert due to long list of extra rewards/yields"}
{"prompt": "if (_vaultFee > 0) {\n uint256 treasuryAmount = _processTreasury(_asset, yieldAmount);\n yieldAmount = yieldAmount.sub(treasuryAmount);\n}\n\n// transfer to yieldManager\naddress yieldManager = _addressesProvider.getAddress('YIELD_MANAGER');\nTransferHelper.safeTransfer(_asset, yieldManager, yieldAmount);\n\n", "completion": "ConvexCurveLPVault\u2019s _transferYield can become stuck with zero reward transfer"}
{"prompt": "for (uint256 i = 0; i < assetYields.length; i++) {\n if (assetYields[i].amount > 0) {\nuint256 _amount = _convertToStableCoin(assetYields[i].asset, assetYields[i].amount);\n// 3. deposit Yield to pool for suppliers\n_depositYield(assetYields[i].asset, _amount);\n }\n volumes[i].mul(PercentageMath.PERCENTAGE_FACTOR).div(totalVolume)\n);\n", "completion": "Yield can be unfairly divided because of MEV/Just-in-time stablecoin deposits"}
{"prompt": "IPriceOracle.OracleAverageQuery[] memory queries = new IPriceOracle.OracleAverageQuery[](1);\n\nqueries[0].variable = IPriceOracle.Variable.BPT_PRICE;\nqueries[0].secs = 3600; // last hour\nqueries[0].ago = 0; // now\n\n// Gets the balancer time weighted average price denominated in BAL\nreturn IPriceOracle(BALANCER_POOL_TOKEN).getTimeWeightedAverage(queries)[0];\n}\n\n", "completion": "CrvDepositorWrapper.sol relies on oracle that isn\u2019t frequently updated"}
{"prompt": "uint256 unlockInWeeks = (unlockAt/WEEK)*WEEK;\n\n//increase time too if over 2 week buffer\nif(unlockInWeeks.sub(unlockTime) > 2){\nIStaker(staker).increaseTime(unlockAt);\nunlockTime = unlockInWeeks;\n}\n}\n", "completion": "CrvDepositor.sol Wrong implementation of the 2-week buffer for lock"}
{"prompt": "function getReward(\naddress _account,\naddress _token,\n", "completion": "User can forfeit other user rewards"}
{"prompt": "reward = uint256(locks[length - 1].amount).mul(rRate).div(denominator);\n}\n} else {\n", "completion": "AuraLocker kick reward only takes last locked amount into consideration, instead of whole balance"}
{"prompt": "require(len == 0 || rewardEpochs[_token][len - 1] < _epoch, \"Cannot backdate to this epoch\");\n\n_addReward(_token, _amount, _epoch);\n", "completion": "Users can grief reward distribution"}
{"prompt": "_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)\n.sub(rewardData[_rewardsToken].lastUpdateTime)\n.mul(rewardData[_rewardsToken].rewardRate)\n", "completion": "Rewards distribution can be delayed/never distributed on AuraLocker.sol#L848"}
{"prompt": "//only claimable after rewards are \"locked in\"\nif (rewardEpochs[_token][i] < latestEpoch) {\nclaimableTokens += _claimableRewards(_account, _token, rewardEpochs[_token][i]);\n//return index user claims should be set to\nepochIndex = i + 1;\n}\n}\nreturn (claimableTokens, epochIndex);\nuint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);\nepochs.push(Epoch({ supply: 0, date: uint32(nextEpochDate) }));\n}\n}\n", "completion": "Reward may be locked forever if user doesn\u2019t claim reward for a very long time such that too many epochs have been passed"}
{"prompt": "function _lock(address _account, uint256 _amount) internal {\nrequire(_amount > 0, \"Cannot stake 0\");\nrequire(!isShutdown, \"shutdown\");\n", "completion": "Locking up AURA Token does not increase voting power of individual"}
{"prompt": "function fund(address[] calldata _recipient, uint256[] calldata _amount) external nonReentrant {\nrequire(!initialised, \"initialised already\");\n\n", "completion": "Reward can be vested even after endTime"}
{"prompt": "address _token,\nuint256 _amount,\nuint256 _epoch\n) internal nonReentrant {\n// Pull before reward accrual\nIERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);\n\n//convert to reward per token\nuint256 supply = auraLocker.totalSupplyAtEpoch(_epoch);\nuint256 rPerT = (_amount * 1e20) / supply;\nrewardData[_token][_epoch] += rPerT;\n\n", "completion": "Users may lose rewards to other users if rewards are given as fee-on-transfer tokens"}
{"prompt": "uint256 _allocPoint,\nIERC20 _lpToken,\nIRewarder _rewarder,\nbool _withUpdate\n) public onlyOwner {\nif (_withUpdate) {\nmassUpdatePools();\n}\nuint256 lastRewardBlock = block.number > startBlock\n? block.number\n: startBlock;\ntotalAllocPoint = totalAllocPoint.add(_allocPoint);\npoolInfo.push(\nPoolInfo({\nlpToken: _lpToken,\nallocPoint: _allocPoint,\nlastRewardBlock: lastRewardBlock,\naccCvxPerShare: 0,\nrewarder: _rewarder\n})\n);\n}\n\n", "completion": "ConvexMasterChef: When _lpToken is cvx, reward calculation is incorrect"}
{"prompt": "rewardData[token].rewardPerTokenStored = newRewardPerToken.to96();\nrewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to32();\nif (lockedSupply == 0) {\nreturn rewardData[_rewardsToken].rewardPerTokenStored;\n}\nreturn\nuint256(rewardData[_rewardsToken].rewardPerTokenStored).add(\n_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)\n.sub(rewardData[_rewardsToken].lastUpdateTime)\n.mul(rewardData[_rewardsToken].rewardRate)\n.mul(1e18)\n.div(lockedSupply)\n);\n}\n\nrdata.rewardRate = _reward.div(rewardsDuration).to96();\n} else {\nuint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);\n", "completion": "Integer overflow will lock all rewards in AuraLocker"}
{"prompt": "uint256 cvxBal = cvx.balanceOf(address(this));\nif (_amount > cvxBal) {\ncvx.safeTransfer(_to, cvxBal);\n} else {\ncvx.safeTransfer(_to, _amount);\n}\n}\n\n", "completion": "ConvexMasterChef: safeRewardTransfer can cause loss of funds"}
{"prompt": "uint256 bal = tkn.balanceOf(address(this));\nrequire(bal > 0 && bal == _request.maxAmountsIn[i], \"!bal\");\n\nrequire(bal > 0 && bal == _request.maxAmountsIn[i], \"!bal\");\n\ntkn.safeApprove(address(bVault), 0);\n", "completion": "DDOS in BalLiquidityProvider"}
{"prompt": "PoolInfo storage pool = poolInfo[_pid];\nUserInfo storage user = userInfo[_pid][msg.sender];\nupdatePool(_pid);\nif (user.amount > 0) {\nuint256 pending = user\n.amount\n.mul(pool.accCvxPerShare)\n.div(1e12)\n.sub(user.rewardDebt);\nsafeRewardTransfer(msg.sender, pending);\n}\npool.lpToken.safeTransferFrom(\naddress(msg.sender),\nPoolInfo storage pool = poolInfo[_pid];\nUserInfo storage user = userInfo[_pid][msg.sender];\nrequire(user.amount >= _amount, \"withdraw: not good\");\nupdatePool(_pid);\nuint256 pending = user.amount.mul(pool.accCvxPerShare).div(1e12).sub(\nuser.rewardDebt\n);\nsafeRewardTransfer(msg.sender, pending);\nuser.amount = user.amount.sub(_amount);\nuser.rewardDebt = user.amount.mul(pool.accCvxPerShare).div(1e12);\npool.lpToken.safeTransfer(address(msg.sender), _amount);\n\n", "completion": "ConvexMasterChef\u2019s deposit and withdraw can be reentered drawing all reward funds from the contract if reward token allows for transfer flow control"}
{"prompt": "uint256 reward = rewards[msg.sender];\nif (reward > 0) {\nrewards[msg.sender] = 0;\nif (_lock) {\nauraLocker.lock(msg.sender, reward);\n} else {\nuint256 penalty = (reward * 2) / 10;\npendingPenalty += penalty;\nrewardToken.safeTransfer(msg.sender, reward - penalty);\n}\nemit RewardPaid(msg.sender, reward, _lock);\n", "completion": "AuraBalRewardPool charges a penalty to all users in the pool if the AuraLocker has been shut down"}
{"prompt": "uint256 length = poolInfo.length;\nfor (uint256 pid = 0; pid < length; ++pid) {\nupdatePool(pid);\n}\n}\n\n", "completion": "massUpdatePools() is susceptible to DoS with block gas limit"}
{"prompt": "uint256 _allocPoint,\nIERC20 _lpToken,\nIRewarder _rewarder,\nbool _withUpdate\n) public onlyOwner {\nif (_withUpdate) {\nmassUpdatePools();\n}\nuint256 lastRewardBlock = block.number > startBlock\n? block.number\n: startBlock;\ntotalAllocPoint = totalAllocPoint.add(_allocPoint);\npoolInfo.push(\nPoolInfo({\nlpToken: _lpToken,\nallocPoint: _allocPoint,\nlastRewardBlock: lastRewardBlock,\naccCvxPerShare: 0,\nrewarder: _rewarder\n})\n);\n}\n\n// Update the given pool's CVX allocation point. Can only be called by the owner.\nfunction set(\nuint256 _pid,\nuint256 _allocPoint,\nIRewarder _rewarder,\nbool _withUpdate,\nbool _updateRewarder\n) public onlyOwner {\nif (_withUpdate) {\nmassUpdatePools();\n}\ntotalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(\n_allocPoint\n);\npoolInfo[_pid].allocPoint = _allocPoint;\nif(_updateRewarder){\npoolInfo[_pid].rewarder = _rewarder;\n}\n}\n\n", "completion": "ConvexMasterChef: When using add() and set(), it should always call massUpdatePools() to update all pools"}
{"prompt": "function add(\nuint256 _allocPoint,\nIERC20 _lpToken,\n", "completion": "Duplicate LP token could lead to incorrect reward distribution"}
{"prompt": "? ERC721(vault.token).transferFrom(msg.sender, address(this), vault.tokenIdOrAmount)\n: ERC20(vault.token).safeTransferFrom(msg.sender, address(this), vault.tokenIdOrAmount);\n}\n", "completion": "no-revert-on-transfer ERC20 tokens can be drained"}
{"prompt": "uint256 startingStrike,\nuint32 auctionEndTimestamp,\nuint256 reserveStrike\n) public view returns (uint256 strike) {\n/*\ndelta = max(auctionEnd - currentTimestamp, 0)\nprogress = delta / auctionDuration\nauctionStrike = progress^2 * startingStrike\nstrike = max(auctionStrike, reserveStrike)\n*/\nuint256 delta = auctionEndTimestamp > block.timestamp ? auctionEndTimestamp - block.timestamp : 0;\nuint256 progress = (1e18 * delta) / AUCTION_DURATION;\nuint256 auctionStrike = (progress * progress * startingStrike) / (1e18 * 1e18);\n\n// max(auctionStrike, reserveStrike)\nstrike = auctionStrike > reserveStrike ? auctionStrike : reserveStrike;\n}\n\n", "completion": "Inefficiency in the Dutch Auction due to lower duration"}
{"prompt": "/// @param feeRate_ The new fee rate: fee = 1% = (1 / 100) * 1e18\nfunction setFee(uint256 feeRate_) external onlyOwner {\nfeeRate = feeRate_;\n}\n\n", "completion": "Owner can modify the feeRate on existing vaults and steal the strike value on exercise"}
{"prompt": "_mint(msg.sender, vaultId);\n\nemit NewVault(vaultId, msg.sender, token);\n? ERC721(vault.token).transferFrom(msg.sender, address(this), vault.tokenIdOrAmount)\n: ERC20(vault.token).safeTransferFrom(msg.sender, address(this), vault.tokenIdOrAmount);\n}\n", "completion": "It shouldn\u2019t be possible to create a vault with Cally\u2019 own token"}
{"prompt": "require(msg.value >= premium, \"Incorrect ETH amount sent\");\n\n", "completion": "User\u2019s may accidentally overpay in buyOption() and the excess will be paid to the vault creator"}
{"prompt": ": ERC20(vault.token).safeTransfer(msg.sender, vault.tokenIdOrAmount);\n}\n\n", "completion": "Vaults steal rebasing tokens\u2019 rewards"}
{"prompt": "vault.currentExpiration = uint32(block.timestamp) + (vault.durationDays * 1 days);\n\n// update the vault with the new option expiration and strike\n", "completion": "Expiration calculation overflows if call option duration \u2265 195 days"}
{"prompt": "ethBalance[getVaultBeneficiary(vaultId)] += msg.value - fee;\n\n", "completion": "Owner can set the feeRate to be greater than 100% and cause all future calls to exercise to revert"}
{"prompt": ": ERC20(vault.token).safeTransferFrom(msg.sender, address(this), vault.tokenIdOrAmount);\n}\n\n", "completion": "Lack of 0 amount check allows malicious user to create infinite vaults"}
{"prompt": "? ERC721(vault.token).transferFrom(msg.sender, address(this), vault.tokenIdOrAmount)\n: ERC20(vault.token).safeTransferFrom(msg.sender, address(this), vault.tokenIdOrAmount);\n}\n? ERC721(vault.token).transferFrom(address(this), msg.sender, vault.tokenIdOrAmount)\n: ERC20(vault.token).safeTransfer(msg.sender, vault.tokenIdOrAmount);\n}\n? ERC721(vault.token).transferFrom(address(this), msg.sender, vault.tokenIdOrAmount)\n: ERC20(vault.token).safeTransfer(msg.sender, vault.tokenIdOrAmount);\n}\n", "completion": "Vault is Not Compatible with Fee Tokens and Vaults with Such Tokens Could Be Exploited"}
{"prompt": "? ERC721(vault.token).transferFrom(msg.sender, address(this), vault.tokenIdOrAmount)\n: ERC20(vault.token).safeTransferFrom(msg.sender, address(this), vault.tokenIdOrAmount);\n}\n? ERC721(vault.token).transferFrom(address(this), msg.sender, vault.tokenIdOrAmount)\n: ERC20(vault.token).safeTransfer(msg.sender, vault.tokenIdOrAmount);\n}\n? ERC721(vault.token).transferFrom(address(this), msg.sender, vault.tokenIdOrAmount)\n: ERC20(vault.token).safeTransfer(msg.sender, vault.tokenIdOrAmount);\n}\n", "completion": "Use safeTransferFrom instead of transferFrom for ERC721 transfers"}
{"prompt": "IAlchemistV2(alchemist).depositUnderlying(\ntoken,\namount,\naddress(this),\n0\n);\n}\n\n", "completion": "TransmuterBuffer.sol calls depositUnderlying with no slippage bounds"}
{"prompt": "if (paused[msg.sender]) {\n revert IllegalState();\n}\n\nuint256 total = amount + totalMinted[msg.sender];\nif (total > mintCeiling[msg.sender]) {\n revert IllegalState();\n}\n\ntotalMinted[msg.sender] = total;\n\n_mint(recipient, amount);\n }\n\ntotalMinted[msg.sender] = totalMinted[msg.sender] - amount;\n }\n\n", "completion": "Alchemist can mint AlTokens above their assigned ceiling by calling lowerHasMinted()"}
{"prompt": "if ((error = ICERC20(token).mint(amount)) != NO_ERROR) {\nrevert FuseError(error);\n}\nif ((error = ICERC20(token).redeem(amount)) != NO_ERROR) {\nrevert FuseError(error);\n}\n", "completion": "DoS in wrap and unwrap"}
{"prompt": "uint256 private constant MAXIMUM_SLIPPAGE = 10000;\nstring public constant override version = \"2.1.0\";\n\nuint256 amountWithdrawn = IYearnVaultV2(token).withdraw(amount, recipient, MAXIMUM_SLIPPAGE);\n\nuint256 balanceAfter = TokenUtils.safeBalanceOf(token, address(this));\n", "completion": "YearnTokenAdapter allows a maximum loss of 100% when withdrawing"}
{"prompt": "contract AlchemicTokenV2Base is ERC20Upgradeable, AccessControlUpgradeable, IERC3156FlashLender, ReentrancyGuardUpgradeable {\n /// @notice The identifier of the role which maintains other roles.\n bytes32 public constant ADMIN_ROLE = keccak256(\"ADMIN\");\ncontract CrossChainCanonicalBase is ERC20PermitUpgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable {\n\n// Constants for various precisions\ncontract TransmuterV2 is ITransmuterV2, Initializable, ReentrancyGuardUpgradeable, AccessControlUpgradeable {\n using FixedPointMath for FixedPointMath.Number;\n using Tick for Tick.Cache;\ncontract CrossChainCanonicalAlchemicTokenV2 is CrossChainCanonicalBase, AlchemicTokenV2Base {\n function initialize(\n string memory name, \n", "completion": "No Storage Gap for Upgradeable Contract Might Lead to Storage Slot Collision"}
{"prompt": "uint256[NUM_META_COINS] calldata amounts\n) internal returns (uint256 minted) {\nIERC20[NUM_META_COINS] memory tokens = _metaPoolAssetCache;\n\nuint256 total = 0;\nfor (uint256 i = 0; i < NUM_META_COINS; i++) {\nif (amounts[i] == 0) continue;\n\ntotal += amounts[i];\n\nfor (uint256 i = 0; i < NUM_META_COINS; i++) {\n// Skip over approving WETH since we are directly swapping ETH.\nif (i == uint256(MetaPoolAsset.ETH)) continue;\n\nif (amounts[i] == 0) continue;\n\ntotal += amounts[i];\n\n", "completion": "EthAssetManager and ThreePoolAssetManager don\u2019t control Meta tokens decimals"}
{"prompt": "IERC20(token).approve(spender, type(uint256).max);\n}\n\n", "completion": "AutoleverageBase: Must approve 0 first"}
{"prompt": "TokenUtils.safeTransferFrom(underlyingToken, msg.sender, address(this), amount);\nTokenUtils.safeApprove(underlyingToken, token, amount);\n\n", "completion": "YearnTokenAdapter\u2019s wrap can become stuck as it uses one step approval for an arbitrary underlying"}
{"prompt": "sources[alchemist] = false;\nsources[_alchemist] = true;\n\nif (alchemist != address(0)) {\nfor (uint256 i = 0; i < registeredUnderlyings.length; i++) {\nTokenUtils.safeApprove(registeredUnderlyings[i], alchemist, 0);\n}\nTokenUtils.safeApprove(debtToken, alchemist, 0);\n}\n\nalchemist = _alchemist;\nfor (uint256 i = 0; i < registeredUnderlyings.length; i++) {\nTokenUtils.safeApprove(registeredUnderlyings[i], alchemist, type(uint256).max);\n}\nTokenUtils.safeApprove(debtToken, alchemist, type(uint256).max);\n\nemit SetAlchemist(alchemist);\n}\n\n", "completion": "TransmuterBuffer\u2019s setAlchemist will freeze deposited funds"}
{"prompt": "_mint(msg.sender, gAmount);\nemit Stake(msg.sender, gAmount, amount);\n// Claim from pool\npools.claim(poolId);\n// Bump exchange rate\nuint balance = alcx.balanceOf(address(this));\n\nif (balance > 0) {\nexchangeRate += (balance * exchangeRatePrecision) / totalSupply;\nemit ExchangeRateChange(exchangeRate);\n", "completion": "New gALCX token denomination can be depressed by the first depositor"}
{"prompt": "\nif (balance > 0) {\nexchangeRate += (balance * exchangeRatePrecision) / totalSupply;\nemit ExchangeRateChange(exchangeRate);\n", "completion": "[gALCX.sol Attacker can make the contract unusable when totalSupply is 0"}
{"prompt": "revert IllegalState();\n}\n\n", "completion": "registerAsset misuse can permanently disable TransmuterBuffer and break the system"}
{"prompt": "uint8 decimals = TokenUtils.expectDecimals(token);\nuint256 pricePerShare = IAlchemistV2(alchemist).getUnderlyingTokensPerShare(token);\nuint256 wantShares = amountUnderlying * 10**decimals / pricePerShare;\n(uint256 availableShares, uint256 lastAccruedWeight) = IAlchemistV2(alchemist).positions(address(this), token);\nif (wantShares > availableShares) {\nwantShares = availableShares;\n}\n// Allow 1% slippage\nuint256 minimumAmountOut = amountUnderlying - amountUnderlying * 100 / 10000;\nif (wantShares > 0) {\nIAlchemistV2(alchemist).withdrawUnderlying(token, wantShares, address(this), minimumAmountOut);\n}\n}\n\n", "completion": "TransmuterBuffer\u2019s _alchemistWithdraw use hard coded slippage that can lead to user losses"}
{"prompt": "_onlyWhitelisted();\n_checkArgument(amount > 0);\n_checkArgument(recipient != address(0));\n\n// Mint tokens from the message sender's account to the recipient.\n_mint(msg.sender, amount, recipient);\n}\n\nfunction burn(uint256 amount, address recipient) external override lock returns (uint256) {\n_onlyWhitelisted();\n\nfunction decrease(LinearGrowthLimiter storage self, uint256 amount) internal {\nuint256 value = self.get();\nself.lastValue = value - amount;\n", "completion": "A well financed attacker could prevent any other users from minting synthetic tokens"}
{"prompt": "return IWstETH(token).getStETHByWstETH(10**SafeERC20.expectDecimals(token));\n}\n\n", "completion": "Lido adapter incorrectly calculates the price of the underlying token"}
{"prompt": "YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];\n\nuint256 unlockedCredit = _calculateUnlockedCredit(yieldToken);\nif (unlockedCredit == 0) {\nreturn;\n}\n\nyieldTokenParams.accruedWeight += unlockedCredit * FIXED_POINT_SCALAR / yieldTokenParams.totalShares;\nyieldTokenParams.distributedCredit += unlockedCredit;\n}\n\nyieldTokenParams.accruedWeight += unlockedCredit * FIXED_POINT_SCALAR / yieldTokenParams.totalShares;\n}\n\n? unlockedCredit * FIXED_POINT_SCALAR / _yieldTokens[yieldToken].totalShares\n: 0;\n\n_yieldTokens[yieldToken].accruedWeight += amount * FIXED_POINT_SCALAR / shares;\n_accounts[msg.sender].lastAccruedWeights[yieldToken] = _yieldTokens[yieldToken].accruedWeight;\n\nreturn (shares * _calculateUnrealizedActiveBalance(yieldToken)) / totalShares;\n}\n\n", "completion": "If totalShares for a token falls to zero while there is pendingCredit the contract will become stuck"}
{"prompt": "function _normalizeUnderlyingTokensToDebt(address underlyingToken, uint256 amount) internal view returns (uint256) {\nreturn amount * _underlyingTokens[underlyingToken].conversionFactor;\n}\n\n", "completion": "Debt can be repaid with a depegged underlyingToken, which can be exploited by arbitrageurs and drives the market price of alToken to match the worst depegged underlyingToken"}
{"prompt": "uint price = getCost(index);\nrequire(msg.value >= price, 'Please send more ETH');\n\n// bump up the price\nGate storage gate = gates[index];\n// multiply by the price increase factor\ngate.lastPrice = (price * gate.priceIncreaseFactor) / gate.priceIncreaseDenominator;\n// move up the reference\ngate.lastPurchaseBlock = block.number;\n\n// pass thru the ether\nif (msg.value > 0) {\n// use .call so we can send to contracts, for example gnosis safe, re-entrance is not a threat here\n(bool sent, bytes memory data) = gate.beneficiary.call{value: msg.value}(\"\");\nrequire(sent, 'ETH transfer failed');\n}\n}\n}\n", "completion": "SpeedBumpPriceGate: Excess ether did not return to the user"}
{"prompt": "require(pool.totalDepositsWei == 0, 'Cannot withdraw until all deposits are withdrawn');\nrequire(block.timestamp > pool.endTime, 'Contract must reach maturity');\n\n", "completion": "DoS: Attacker may significantly increase the cost of withdrawExcessRewards() by creating a significant number of excess receipts"}
{"prompt": "IERC20(tree.tokenAddress).transfer(destination, currentWithdrawal);\nemit WithdrawalOccurred(treeIndex, destination, currentWithdrawal, tranche.currentCoins);\n}\n", "completion": "MerkleVesting withdrawal does not verify that tokens were transferred successfully"}
{"prompt": "gate.priceIncreaseDenominator = priceIncreaseDenominator;\ngate.beneficiary = beneficiary;\n}\n", "completion": "SpeedBumpPriceGate.sol#addGate() Lack of input validation may casue div by 0 error"}
{"prompt": "success = success && IERC20(pool.rewardTokens[i]).transfer(receipt.owner, transferAmount);\n}\n\n", "completion": "Malicious token reward could disable withdrawals"}
{"prompt": "success = success && IERC20(pool.rewardTokens[i]).transferFrom(msg.sender, address(this), amount);\n// bookkeeping to make sure pools don't share tokens\npool.rewardFunding[i] += amount;\n", "completion": "safeTransferFrom is recommended instead of transfer (1)"}
{"prompt": "if (a < b) {\nreturn keccak256(abi.encode(a, b));\n} else {\nreturn keccak256(abi.encode(b, a));\n}\n}\n\nbytes32 leaf = keccak256(abi.encode(destination, value));\n// storage because we edit\nMerkleTree storage tree = merkleTrees[treeIndex];\n", "completion": "Merkle leaves are the same length as the parents that are hashed"}
{"prompt": "// storage since we are editing\nMerkleTree storage merkleTree = merkleTrees[treeIndex];\n\n// bookkeeping to make sure trees don't share tokens\nmerkleTree.tokenBalance += value;\n\n// transfer tokens, if this is a malicious token, then this whole tree is malicious\n// but it does not effect the other trees\nrequire(IERC20(merkleTree.tokenAddress).transferFrom(msg.sender, address(this), value), \"ERC20 transfer failed\");\nemit TokensDeposited(treeIndex, merkleTree.tokenAddress, value);\n}\n\n", "completion": "MerkleDropFactory.depositTokens() does not require the tree to exist"}
{"prompt": "require(merkleIndex <= numTrees, 'merkleIndex out of range');\n\n// verify that the metadata is real\nMerkleTree storage tree = merkleTrees[++numTrees];\ntree.metadataMerkleRoot = metadataMerkleRoot;\ntree.ipfsHash = ipfsHash;\n", "completion": "wrong out of range check"}
{"prompt": "Pool storage pool = pools[poolId];\nReceipt memory receipt = pool.receipts[receiptId];\nrequire(pool.id == poolId, 'Uninitialized pool');\nrequire(receipt.id == receiptId, 'Uninitialized receipt');\nuint nowish = block.timestamp;\nif (nowish > pool.endTime) {\nnowish = pool.endTime;\n}\n\nuint secondsDiff = nowish - receipt.timeDeposited;\nuint[] memory rewardsLocal = new uint[](pool.rewardsWeiPerSecondPerToken.length);\nfor (uint i = 0; i < pool.rewardsWeiPerSecondPerToken.length; i++) {\nrewardsLocal[i] = (secondsDiff * pool.rewardsWeiPerSecondPerToken[i] * receipt.amountDepositedWei) / 1e18;\n}\n\nreturn rewardsLocal;\n}\n\n", "completion": "getRewards() in PermissionlessBasicPoolFactory calculate wrong reward amount for receiptId==0"}
{"prompt": "IERC20(tree.tokenAddress).transfer(destination, currentWithdrawal);\nemit WithdrawalOccurred(treeIndex, destination, currentWithdrawal, tranche.currentCoins);\n}\n", "completion": "A transfer that is not validated its result."}
{"prompt": "merkleTree.tokenBalance += value;\n\n// transfer tokens, if this is a malicious token, then this whole tree is malicious\n// but it does not effect the other trees\nrequire(IERC20(merkleTree.tokenAddress).transferFrom(msg.sender, address(this), value), \"ERC20 transfer failed\");\nemit TokensDeposited(treeIndex, merkleTree.tokenAddress, value);\n", "completion": "Rebasing tokens go to the pool owner, or remain locked in the various contracts"}
{"prompt": "pool.rewardsWeiClaimed[i] += rewards[i];\npool.rewardFunding[i] -= rewards[i];\nuint tax = (pool.taxPerCapita * rewards[i]) / 1000;\nuint transferAmount = rewards[i] - tax;\ntaxes[poolId][i] += tax;\nsuccess = success && IERC20(pool.rewardTokens[i]).transfer(receipt.owner, transferAmount);\n}\n\n", "completion": "Unbounded loop in withdraw() may cause rewards to be locked in the contract"}
{"prompt": "/// @dev Anyone may call this, it just moves the taxes from this contract to the globalBeneficiary\n/// @param poolId which pool are we talking about?\nfunction withdrawTaxes(uint poolId) external {\nPool storage pool = pools[poolId];\nrequire(pool.id == poolId, 'Uninitialized pool');\n\nbool success = true;\nfor (uint i = 0; i < pool.rewardTokens.length; i++) {\nuint tax = taxes[poolId][i];\ntaxes[poolId][i] = 0;\nsuccess = success && IERC20(pool.rewardTokens[i]).transfer(globalBeneficiary, tax);\n}\nrequire(success, 'Token transfer failed');\n}\n\n", "completion": "Pool owners can prevent the payment of taxes"}
{"prompt": "}\n\nsuccess = success && IERC20(pool.depositToken).transfer(receipt.owner, receipt.amountDepositedWei);\nrequire(success, 'Token transfer failed');\n\n", "completion": "Pool owners can prevent withdrawals of specific receipts"}
{"prompt": "Pool storage pool = pools[poolId];\nbool success = true;\nuint amount;\nfor (uint i = 0; i < pool.rewardFunding.length; i++) {\namount = getMaximumRewards(poolId, i);\n// transfer the tokens from pool-creator to this contract\nsuccess = success && IERC20(pool.rewardTokens[i]).transferFrom(msg.sender, address(this), amount);\n// bookkeeping to make sure pools don't share tokens\npool.rewardFunding[i] += amount;\n}\nrequire(success, 'Token deposits failed');\n}\n\n", "completion": "amount requires to be updated to contract balance increase (1)"}
{"prompt": "bytes32 leaf = keccak256(abi.encode(destination, value));\n// storage because we edit\nMerkleTree storage tree = merkleTrees[treeIndex];\n", "completion": "Merkle-tree-related contracts vulnerable to cross-chain-replay attacks"}
{"prompt": "rewardsLocal[i] = (secondsDiff * pool.rewardsWeiPerSecondPerToken[i] * receipt.amountDepositedWei) / 1e18;\n}\n\nreturn pool.rewardsWeiPerSecondPerToken[rewardIndex] * pool.maximumDepositWei * (pool.endTime - pool.startTime) / 1e18;\n}\n\n", "completion": "ERC20 tokens with different decimals than 18 leads to loss of funds"}
{"prompt": "Pool storage pool = pools[poolId];\nrequire(pool.id == poolId, 'Uninitialized pool');\n\nbool success = true;\nfor (uint i = 0; i < pool.rewardTokens.length; i++) {\nuint tax = taxes[poolId][i];\ntaxes[poolId][i] = 0;\nsuccess = success && IERC20(pool.rewardTokens[i]).transfer(globalBeneficiary, tax);\n}\nrequire(success, 'Token transfer failed');\n}\n\n", "completion": "Owner of a pool may prevent any taxes being withdrawn"}
{"prompt": "require(msg.sender == globalBeneficiary, 'Only globalBeneficiary can set tax');\nrequire(newTaxPerCapita < 1000, 'Tax too high');\nglobalTaxPerCapita = newTaxPerCapita;\n}\n}\n", "completion": "Centralisation Risk: Owner may abuse the tax rate to claim 99.9% of pools"}
{"prompt": "uint coinsPerSecond = (totalCoins * (uint(100) - tree.pctUpFront)) / (vestingTime * 100);\n\n// vestingTime is relative to initialization point\nuint startTime = block.timestamp + vestingTime - (totalCoins / coinsPerSecond);\n\nreturn (true, totalCoins, coinsPerSecond, startTime);\n", "completion": "MerkleResistor: zero coinsPerSecond will brick tranche initialization and withdrawals"}
{"prompt": "initialized[destination][treeIndex] = true;\n// precompute how many coins are released per second\nuint coinsPerSecond = totalCoins / (endTime - startTime);\nrequire(!withdrawn[destination][treeIndex], \"You have already withdrawn your entitled token.\");\n// compute merkle leaf, this is first element of proof\nbytes32 leaf = keccak256(abi.encode(destination, value));\n", "completion": "Verification should be leafed based and not address based"}
{"prompt": "function setDaPriceCurveLength(uint256 _newTime) public onlyOwner {\ndaPriceCurveLength = _newTime;\n}\nfunction setDaDropInterval(uint256 _newTime) public onlyOwner {\ndaDropInterval = _newTime;\n}\nfunction setLowestPrice(uint256 _newPrice) public onlyOwner {\nlowestPrice = _newPrice;\n}\nfunction setDaDropInterval(uint256 _newTime) public onlyOwner {\ndaDropInterval = _newTime;\n}\n", "completion": "Critical variables shouldn\u2019t be changed after they are set"}
{"prompt": "require(payable(vault).send(_amount));\n}\n\nrequire(payable(vault).send(address(this).balance));\n}\n\nrequire(payable(msg.sender).send(address(this).balance));\n}\n\n", "completion": "Use of .send() May Revert if The Recipient\u2019s Fallback Function Consumes More Than 2300 Gas"}
{"prompt": "if (!daStarted()) {\nreturn startPrice;\n}\nif (block.timestamp >= daStartTime + daPriceCurveLength) {\n// end of the curve\nreturn lowestPrice;\n}\n\nuint256 dropPerStep = (startPrice - lowestPrice) /\n(daPriceCurveLength / daDropInterval);\n\nuint256 elapsed = block.timestamp - daStartTime;\nuint256 steps = elapsed / daDropInterval;\nuint256 stepDeduction = steps * dropPerStep;\n\n// don't go negative in the next step\nif (stepDeduction > startPrice) {\nreturn lowestPrice;\n}\nuint256 currentPrice = startPrice - stepDeduction;\nreturn currentPrice > lowestPrice ? currentPrice : lowestPrice;\n}\n\n", "completion": "Many unbounded and under-constrained variables in the system can lead to unfair price or DoS"}
{"prompt": "require(address(msg.sender) != address(0));\ntoken.transfer(msg.sender, amount);\n}\n}\nrequire(address(msg.sender) != address(0));\ntoken.transfer(msg.sender, amount);\n}\n}\n", "completion": "IERC20.transfer does not support all ERC20 token"}
{"prompt": "require(address(vault) != address(0), 'no vault');\nrequire(payable(vault).send(address(this).balance));\n}\n\n", "completion": "Contract may not have enough fund to cover refund"}
{"prompt": "function teamSummon(address recipient, uint256 count) external onlyOwner {\nrequire(address(recipient) != address(0), 'address req');\nfor (uint256 i = 0; i < count; i++) {\n", "completion": "The owner can mint all of the NFTs."}
{"prompt": "revert(\"CNFT: Use safeBatchTransferFrom instead\");\n}\n\n", "completion": "CNft.sol - revert inside safeTransferFrom will break composability & standard behaviour"}
{"prompt": "if (usdcPrice <= 0) {\nreturn 0;\n", "completion": "Chainlink pricer is using a deprecated API"}
{"prompt": "to.transfer(amount);\n}\n\n", "completion": "call() should be used instead of transfer() on an address payable"}
{"prompt": "address _tokenAddress) \nexternal {\nrequire(cudosAccessControls.hasAdminRole(msg.sender), \"Recipient is not an admin\");\nuint256 totalBalance = IERC20(_tokenAddress).balanceOf(address(this));\nIERC20(_tokenAddress).safeTransfer(msg.sender , totalBalance);\n}\n\naddress _tokenContract,\nbytes32 _destination,\nuint256 _amount\n) public nonReentrant {\nIERC20(_tokenContract).safeTransferFrom(msg.sender, address(this), _amount);\nstate_lastEventNonce = state_lastEventNonce.add(1);\nemit SendToCosmosEvent(\n_tokenContract,\nmsg.sender,\n_destination,\n_amount,\nstate_lastEventNonce\n);\n}\n\n", "completion": "Admin drains all ERC based user funds using withdrawERC20()"}
{"prompt": "function verifySig(\naddress _signer,\nbytes32 _theHash,\n", "completion": "The Gravity.sol should have pause/unpause functionality"}
{"prompt": "IERC20(_tokenContract).safeTransferFrom(msg.sender, address(this), _amount);\nstate_lastEventNonce = state_lastEventNonce.add(1);\nemit SendToCosmosEvent(\n", "completion": "Protocol doesn\u2019t handle fee on transfer tokens"}
{"prompt": "IERC20(_tokenContract).safeTransfer(_destinations[i], _amounts[i]);\ntotalFee = totalFee.add(_fees[i]);\n}\n\nIERC20(_args.transferTokenContracts[i]).safeTransfer(\n_args.logicContractAddress,\n_args.transferAmounts[i]\n);\n}\n\nIERC20(_args.feeTokenContracts[i]).safeTransfer(msg.sender, _args.feeAmounts[i]);\n}\n\n", "completion": "Calls inside loops that may address DoS"}
{"prompt": "address _tokenContract,\nbytes32 _destination,\nuint256 _amount\n) public nonReentrant {\nIERC20(_tokenContract).safeTransferFrom(msg.sender, address(this), _amount);\nstate_lastEventNonce = state_lastEventNonce.add(1);\nemit SendToCosmosEvent(\n_tokenContract,\nmsg.sender,\n_destination,\n_amount,\nstate_lastEventNonce\n);\n}\n\n", "completion": "Non-Cudos Erc20 funds sent through sendToCosmos() will be lost."}
{"prompt": "uint256 _shares = _tokenToShares(_depositAmount);\nrequire(_shares > 0, \"AaveV3YS/shares-gt-zero\");\n\naddress _underlyingAssetAddress = _tokenAddress();\nIERC20(_underlyingAssetAddress).safeTransferFrom(msg.sender, address(this), _depositAmount);\n_pool().supply(_underlyingAssetAddress, _depositAmount, address(this), REFERRAL_CODE);\n\n_mint(_to, _shares);\n\nemit SuppliedTokenTo(msg.sender, _shares, _depositAmount, _to);\n }\n\nuint256 _supply = totalSupply();\n\n// shares = (tokens * totalShares) / yieldSourceATokenTotalSupply\nreturn _supply == 0 ? _tokens : _tokens.mul(_supply).div(aToken.balanceOf(address(this)));\n }\n\n", "completion": "User fund loss in supplyTokenTo() because of rounding"}
{"prompt": "uint256 _shares = _tokenToShares(_depositAmount);\nrequire(_shares > 0, \"AaveV3YS/shares-gt-zero\");\n\naddress _underlyingAssetAddress = _tokenAddress();\nIERC20(_underlyingAssetAddress).safeTransferFrom(msg.sender, address(this), _depositAmount);\n_pool().supply(_underlyingAssetAddress, _depositAmount, address(this), REFERRAL_CODE);\n\n_mint(_to, _shares);\n\nemit SuppliedTokenTo(msg.sender, _shares, _depositAmount, _to);\n }\n\n", "completion": "_depositAmount requires to be updated to contract balance increase"}
{"prompt": "require(_to != address(0), \"AaveV3YS/payee-not-zero-address\");\n\naddress[] memory _assets = new address[](1);\n_assets[0] = address(aToken);\n\n(address[] memory _rewardsList, uint256[] memory _claimedAmounts) = rewardsController\n .claimAllRewards(_assets, _to);\n\n", "completion": "Owner or Managers can rug Aave rewards"}
{"prompt": " * @notice Calculates the number of shares that should be minted or burnt when a user deposit or withdraw.\n * @param _tokens Amount of asset tokens\n * @return Number of shares.\n */\n function _tokenToShares(uint256 _tokens) internal view returns (uint256) {\nuint256 _supply = totalSupply();\n\n// shares = (tokens * totalShares) / yieldSourceATokenTotalSupply\nreturn _supply == 0 ? _tokens : _tokens.mul(_supply).div(aToken.balanceOf(address(this)));\n }\n\n /**\n * @notice Calculates the number of asset tokens a user has in the yield source.\n * @param _shares Amount of shares\n * @return Number of asset tokens.\n */\n function _sharesToToken(uint256 _shares) internal view returns (uint256) {\nuint256 _supply = totalSupply();\n\n// tokens = (shares * yieldSourceATokenTotalSupply) / totalShares\nreturn _supply == 0 ? _shares : _shares.mul(aToken.balanceOf(address(this))).div(_supply);\n }\n\n", "completion": "Yield source does not correctly calculate share conversions"}
{"prompt": "router.call(dexTxData);\n_par.safeTransfer(msg.sender, _liquidateCallerReward);\nrequire(_par.balanceOf(address(this)) > parBalanceBefore, \"LM104\");\nTransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n}\nfunction swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n(bool success, ) = to.call{value: value}(new bytes(0));\nrequire(success, 'TransferHelper::safeTransferETH: ETH transfer failed');\n}\n}\n", "completion": "User can call liquidate() and steal all collateral due to arbitrary router call"}
{"prompt": "address[] calldata assets,\nuint256[] calldata amounts,\nuint256[] calldata premiums,\naddress,\nbytes calldata params\n ) external returns (bool) {\nrequire(msg.sender == address(lendingPool), \"SV002\");\n(Operation operation, bytes memory operationParams) = abi.decode(params, (Operation, bytes));\nIERC20 asset = IERC20(assets[0]);\nuint256 flashloanRepayAmount = amounts[0] + premiums[0];\nif (operation == Operation.LEVERAGE) {\n leverageOperation(asset, flashloanRepayAmount, operationParams);\n}\nif (operation == Operation.REBALANCE) {\n rebalanceOperation(asset, amounts[0], flashloanRepayAmount, operationParams);\n}\nif (operation == Operation.EMPTY) {\n emptyVaultOperation(asset, amounts[0], flashloanRepayAmount, operationParams);\n}\n\nasset.approve(address(lendingPool), flashloanRepayAmount);\nreturn true;\n }\n\n", "completion": "Fund loss or theft by attacker with creating a flash loan and setting SuperVault as receiver so executeOperation() will be get called by lendingPool but with attackers specified params"}
{"prompt": "_tokenDecimalsOffsetA = 10**(18 - decimalsA);\n\nuint256 decimalsB = ERC20(_pool.token1()).decimals();\n_tokenDecimalsOffsetB = 10**(18 - decimalsB);\n }\n\n", "completion": "Decimal token underflow could produce loss of funds"}
{"prompt": "Reapplies the boost of the user, useful a whale's vMIMO has decreased but their boost is still the original value\n */\n function updateBoost(address _user) public {\nUserInfo memory userInfo = _users[_user];\n_updateBoost(_user, userInfo);\n }\n\nReapplies the boost of the user, useful if a whale's vMIMO has decreased but their boost is still the original value\n */\n function updateBoost(address _user) public {\nUserInfo memory userInfo = _users[_user];\n_updateBoost(_user, userInfo);\n }\n\n", "completion": "Users can use updateBoost function to claim unfairly large rewards from liquidity mining contracts for themselves at cost of other users."}
{"prompt": " function leverageSwap(bytes memory params, IERC20 token) internal {\n(uint256 parToSell, bytes memory dexTxData, uint dexIndex) = abi.decode(\n params,\n (uint256, bytes, uint )\n);\ntoken.approve(address(a.core()), 2**256 - 1);\na.core().depositAndBorrow(address(token), token.balanceOf(address(this)), parToSell);\npar.approve(address(a.core()), par.balanceOf(address(this)));\n\n", "completion": "SuperVault\u2019s leverageSwap and emptyVaultOperation can become stuck"}
{"prompt": "asset.approve(address(lendingPool), flashloanRepayAmount);\nreturn true;\n }\n", "completion": "Non-standard ERC20 Tokens are Not Supported"}
{"prompt": " result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1);\n require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n", "completion": "ABDKMath64 performs multiplication on results of division"}
{"prompt": "params.valuation == accepted.valuation &&\nparams.duration <= accepted.duration &&\nparams.annualInterestBPS >= accepted.annualInterestBPS &&\nparams.ltvBPS >= accepted.ltvBPS,\n\"NFTPair: bad params\"\n);\n\n", "completion": "Avoidance of Liquidation Via Malicious Oracle"}
{"prompt": "(, uint256 rate) = loanParams.oracle.get(address(this), tokenId);\nrequire(rate.mul(loanParams.ltvBPS) / BPS < amount, \"NFT is still valued\");\n}\n// The lender can change terms so long as the changes are strictly\n// the same or better for the borrower:\nrequire(msg.sender == loan.lender, \"NFTPair: not the lender\");\nTokenLoanParams memory cur = tokenLoanParams[tokenId];\nrequire(\nparams.duration >= cur.duration &&\nparams.valuation <= cur.valuation &&\nparams.annualInterestBPS <= cur.annualInterestBPS &&\nparams.ltvBPS <= cur.ltvBPS,\n\"NFTPair: worse params\"\n);\n} else if (loan.status == LOAN_REQUESTED) {\n", "completion": "Critical Oracle Manipulation Risk by Lender"}
{"prompt": "params.ltvBPS >= accepted.ltvBPS,\n\"NFTPair: bad params\"\n);\n", "completion": "Mistake while checking LTV to lender accepted LTV"}
{"prompt": "collateral.transferFrom(collateralProvider, address(this), tokenId);\n}\nTokenLoan memory loan;\ncollateral.transferFrom(collateralProvider, address(this), tokenId);\n}\nTokenLoan memory loan;\n", "completion": "Reentrancy at _requestLoan allows requesting a loan without supplying collateral"}
{"prompt": "if (_deprecatedGauges.contains(gauge)) revert InvalidGaugeError();\nunchecked {\nif (cycle - block.timestamp <= incrementFreezeWindow) revert IncrementFreezeError();\n", "completion": "ERC20Gauges: The _incrementGaugeWeight function does not check the gauge parameter enough, so the user may lose rewards"}
{"prompt": "uint256 internal constant _MAX_SWAPPER_SLIPPAGE = 0.95 * 1e18;\n\nIController public immutable controller;\n_setConfig(_MAX_SWAPPER_SLIPPAGE_KEY, _MAX_SWAPPER_SLIPPAGE);\nfor (uint256 i = 0; i < protocols.length; i++) {\nbytes32 protocolKey = _getProtocolKey(protocols[i]);\n", "completion": "Position owner should set allowed slippage"}
{"prompt": "if (vars.removePosition) {\ngasBank.withdrawUnused(payer);\n}\n", "completion": "Malicious Stakers can grief Keepers"}
{"prompt": "super.beforeWithdraw(amount, shares);\nstoredTotalAssets -= amount;\n}\n\n", "completion": "xERC4626.sol Some users may not be able to withdraw until rewardsCycleEnd the due to underflow in beforeWithdraw()"}
{"prompt": "return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n}\n\n", "completion": "First xERC4626 deposit exploit can break share calculation"}
{"prompt": "return (quantity * weight) / total;\n}\n\nif (_deprecatedGauges.contains(gauge)) revert InvalidGaugeError();\nunchecked {\nif (cycle - block.timestamp <= incrementFreezeWindow) revert IncrementFreezeError();\nreturn _incrementUserAndGlobalWeights(msg.sender, weight, currentCycle);\n}\n\nweight = _getGaugeWeight[gauge].currentWeight;\nif (weight > 0) {\n_writeGaugeWeight(_totalWeight, _add, weight, currentCycle);\n}\n\n", "completion": "In ERC20Gauges, contribution to total weight is double-counted when incrementGauge is called before addGauge for a given gauge."}
{"prompt": "function setFlywheelRewards(IFlywheelRewards newFlywheelRewards) external requiresAuth {\nuint256 oldRewardBalance = rewardToken.balanceOf(address(flywheelRewards));\nif (oldRewardBalance > 0) {\nrewardToken.safeTransferFrom(address(flywheelRewards), address(newFlywheelRewards), oldRewardBalance);\n}\n\nflywheelRewards = newFlywheelRewards;\n\n", "completion": "FlywheelCore\u2019s setFlywheelRewards can remove access to reward funds from current users"}
{"prompt": "? flywheelBooster.boostedBalanceOf(strategy, user)\n: strategy.balanceOf(user);\n\n// accumulate rewards by multiplying user tokens by rewardsPerToken index and adding on unclaimed\nuint256 supplierDelta = (supplierTokens * deltaIndex) / ONE;\nuint256 supplierAccrued = rewardsAccrued[user] + supplierDelta;\n\nrewardsAccrued[user] = supplierAccrued;\n\n", "completion": "FlywheelCore.setBooster() can be used to steal unclaimed rewards"}
{"prompt": "balances[account] += amount;\n\naddress lpGauge = currentAddresses[_LP_GAUGE];\nif (lpGauge != address(0)) {\nILpGauge(lpGauge).userCheckpoint(msg.sender);\nILpGauge(lpGauge).userCheckpoint(account);\n}\n\n", "completion": "User can steal all rewards due to checkpoint after transfer"}
{"prompt": "uint256 balance = stakerVault.balanceOf(payer);\nuint256 allowance = stakerVault.allowance(payer, address(this));\nuint256 availableFunds = balance < allowance ? balance : allowance;\nif (availableFunds >= amountLeft) {\nstakerVault.transferFrom(payer, address(this), amountLeft);\namountLeft = 0;\n}\n}\n\n", "completion": "function lockFunds in TopUpActionLibrary can cause serious fund lose. fee and Capped bypass. It\u2019s not calling stakerVault.increaseActionLockedBalance when transfers stakes."}
{"prompt": "IERC20(underlying).safeApprove(address(ctoken), amount);\nerr = ctoken.mint(amount);\n}\nIERC20(underlying).safeApprove(address(ctoken), debt);\nerr = ctoken.repayBorrowBehalf(account, debt);\n}\nIERC20(underlying).safeApprove(address(lendingPool), amount);\n\nif (repayDebt) {\nIERC20(depositToken).safeApprove(feeHandler, feeAmount);\nIActionFeeHandler(feeHandler).payFees(payer, beneficiary, feeAmount, depositToken);\n}\n", "completion": "Customers cannot be topUp()ed a second time"}
{"prompt": "staker.transfer(payer, position.depositTokenBalance);\n}\n\nto.transfer(amount);\n}\n\npayable(vault).transfer(amount);\nemit Withdraw(amount);\nreturn true;\npayable(vault).transfer(amount);\nreturn true;\n}\npayable(vault).transfer(underlyingBalance);\nreturn underlyingBalance;\n}\npayable(to).transfer(amount);\n}\n\npayable(addressProvider.getTreasury()).transfer(amount);\n}\n\npayable(msg.sender).transfer(amount);\n} else {\nIERC20(token).safeTransfer(msg.sender, amount);\n", "completion": "call() should be used instead of transfer() on an address payable"}
{"prompt": "require(getRoleMemberCount(Roles.GOVERNANCE) > 1, Error.CANNOT_REVOKE_ROLE);\n_revokeRole(Roles.GOVERNANCE, msg.sender);\n}\n\nif (\nrole == Roles.ADDRESS_PROVIDER || role == Roles.POOL_FACTORY || role == Roles.CONTROLLER\n) {\nreturn 1;\n}\nif (role == Roles.POOL) {\nreturn addressProvider.poolsCount();\n}\nif (role == Roles.VAULT) {\nreturn addressProvider.vaultsCount();\n}\nreturn _roleMembers[role].length();\n}\n\n", "completion": "Its possible to lose total governance control by mistake"}
{"prompt": "IERC20(token).safeApprove(stakerVaultAddress, depositAmount);\nstakerVault.stake(depositAmount);\nstakerVault.increaseActionLockedBalance(payer, depositAmount);\nIERC20(lpToken_).safeApprove(staker_, type(uint256).max);\n}\n\n", "completion": "Lack of safeApprove(0) prevents some registrations, and the changing of stakers and LP tokens"}
{"prompt": "_CRV_INDEX,\n_CVX_CRV_INDEX,\ncurrentBalance,\n0\n);\n} else {\n", "completion": "CvxCrvRewardsLocker implements a swap without a slippage check that can result in a loss of funds through MEV"}
{"prompt": "(, int256 answer, , uint256 updatedAt, ) = AggregatorV2V3Interface(feed).latestRoundData();\n\nrequire(block.timestamp <= updatedAt + stalePriceDelay, Error.STALE_PRICE);\n", "completion": "Chainlink\u2019s latestRoundData might return stale or incorrect results"}
{"prompt": "_doTransferIn(msg.sender, depositAmount);\nuint256 mintedLp = depositAmount.scaledDiv(rate);\nrequire(mintedLp >= minTokenAmount, Error.INVALID_AMOUNT);\n", "completion": "ERC777 tokens can bypass depositCap guard"}
{"prompt": "Authorization(IAddressProvider(addressProvider_).getRoleManager())\n{\n_addressProvider = IAddressProvider(addressProvider_);\nslippageTolerance = slippageTolerance_;\n}\n\nrequire(slippageTolerance_ <= ScaledMath.ONE, Error.INVALID_SLIPPAGE_TOLERANCE);\nrequire(slippageTolerance_ > 0.8e18, Error.INVALID_SLIPPAGE_TOLERANCE);\nslippageTolerance = slippageTolerance_;\nemit SetSlippageTolerance(slippageTolerance_);\n}\n\n", "completion": "Inconsistency between constructor and setting method for slippageTolerance"}
{"prompt": "return 10**(18 - IERC20Full(token_).decimals());\n}\n\n.scaledDiv(_addressProvider.getOracleProvider().getPriceETH(token_))\n.scaledMul(slippageTolerance) / _decimalMultiplier(token_);\n}\n.scaledMul(_addressProvider.getOracleProvider().getPriceETH(token_))\n.scaledMul(slippageTolerance) * _decimalMultiplier(token_);\n}\n", "completion": "_decimalMultiplier doesn\u2019t account for tokens with decimals higher than 18"}
{"prompt": "return feeRatio - (feeRatio - minFeePercentage).scaledMul(elapsedShare);\n}\n\n", "completion": "getNewCurrentFees reverts when minFeePercentage > feeRatio"}
{"prompt": "meta.timeToWait = uint64(getWithdrawalFeeDecreasePeriod());\nmeta.lastActionTimestamp = uint64(_getTime());\n}\n", "completion": "Griefer can extend period of higher withdrawal fees"}
{"prompt": "(uint err,) = mintInternal(msg.value);\nrequireNoError(err, \"mint failed\");\n}\n\n", "completion": "CompoundHandler#topUp() Using the wrong function selector makes native token topUp() always revert"}
{"prompt": "external\npayable\nreturns (uint256);\n\n", "completion": "CEthInterface#repayBorrowBehalf() reading non-existing returns makes _repayAnyDebt() with CEther always revert"}
{"prompt": "function mint() external payable returns (uint256);\n\nfunction redeem(uint256 redeemTokens) external returns (uint256);\n", "completion": "CEthInterface#mint() reading non-existing returns makes topUp() with native token always revert"}
{"prompt": "uint amountInAsset = IERC20(assets.at(i)).balanceOf(address(vToken)) - vToken.lastBalance();\nuint weightedPrice = assetPerBaseInUQ * weightOf[assets.at(i)];\nuint _minAmountInBase = amountInAsset.mulDiv(FixedPoint112.Q112 * IndexLibrary.MAX_WEIGHT, weightedPrice);\n", "completion": "IndexLogic: An attacker can mint tokens for himself using assets deposited by other users"}
{"prompt": "(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = address(pair).currentCumulativePrices();\nuint32 timeElapsed = blockTimestamp - blockTimestampLast;\n\n", "completion": "UniswapV2PriceOracle.sol currentCumulativePrices() will revert when priceCumulative addition overflow"}
{"prompt": ") external override nonReentrant onlyRole(ORDERER_ROLE) {\n_transfer(_from, _to, _shares);\n}\n", "completion": "Index managers can rug user funds"}
{"prompt": "(, int quotePrice, , , ) = assetInfo.aggregator.latestRoundData();\n\n", "completion": "Chainlink\u2019s latestRoundData might return stale or incorrect results"}
{"prompt": "if (containsBlacklistedAssets && IAccessControl(registry).hasRole(SKIPPED_ASSET_ROLE, asset)) {\ncontinue;\n}\n", "completion": "Inactive skipped assets can be drained from the index"}
{"prompt": "_updatedAssets.length <= IIndexRegistry(registry).maxComponents(),\n\"ManagedIndex: INVALID\"\n);\n/// @notice Maximum assets for an index\n/// @return Returns maximum assets for an index\nfunction maxComponents() external view returns (uint);\n", "completion": "Wrong requirement in reweight function (ManagedIndexReweightingLogic.sol)"}
{"prompt": "function addAsset(address _asset, address _assetAggregator) external override {\nrequire(registry.hasRole(ASSET_MANAGER_ROLE, msg.sender), \"ChainlinkPriceOracle: FORBIDDEN\");\nrequire(_asset != address(0), \"ChainlinkPriceOracle: ZERO\");\n", "completion": "Asset Manager can update existing _assetAggregator"}
{"prompt": "assets.add(asset);\n\nemit UpdateAnatomy(asset, weight);\nassets.add(asset);\n_totalWeight += weight;\nemit UpdateAnatomy(asset, weight);\nassets.add(asset);\nif (asset != maxCapitalizationAsset) {\nemit UpdateAnatomy(asset, weight);\n", "completion": "Duplicate asset can be added"}
{"prompt": "if (_totalSupply > 0) {\nuint _balance = _NAV.balanceOf[_account];\nuint _assetBalance = totalAssetSupply();\n", "completion": "Wrong shareChange() function (vToken.sol)"}
{"prompt": "address recipient,\nuint256 _amount,\nuint256 _pool\n) internal {\nuint256 shares;\nif (totalSupply() == 0) {\nshares = _amount;\n} else {\nshares = (_amount * totalSupply()) / _pool;\n}\n_mint(recipient, shares);\n}\nreturn token.balanceOf(address(this));\n}\n\n", "completion": "StakedCitadel depositors can be attacked by the first depositor with depressing of vault token denomination"}
{"prompt": "/// @return Balance of token handled by the sett.\nfunction balance() public view returns (uint256) {\nreturn token.balanceOf(address(this));\n}\n\nuint256 _before = token.balanceOf(address(this));\ntoken.safeTransferFrom(msg.sender, address(this), _amount);\nuint256 _after = token.balanceOf(address(this));\n_mintSharesFor(_recipient, _after - _before, _pool);\n}\naddress recipient,\nuint256 _amount,\nuint256 _pool\n) internal {\nuint256 shares;\nif (totalSupply() == 0) {\nshares = _amount;\n} else {\nshares = (_amount * totalSupply()) / _pool;\n}\n_mint(recipient, shares);\n}\n\n", "completion": "StakedCitadel doesn\u2019t use correct balance for internal accounting"}
{"prompt": "IVesting(vesting).setupVesting(msg.sender, _amount, block.timestamp);\ntoken.safeTransfer(vesting, _amount);\n\n", "completion": "StakedCitadel: wrong setupVesting function name"}
{"prompt": "IERC20Upgradeable(address(citadelToken)).safeTransfer(address(cachedXCitadel), stakingAmount);\nemit CitadelDistributionToStaking(\ncachedLastMintTimestamp,\n", "completion": "Guaranteed citadel profit"}
{"prompt": "citadelAmount_ = getAmountOut(_assetAmountIn);\nrequire(citadelAmount_ >= _minCitadelOut, \"minCitadelOut\");\n\nfunction getAmountOut(uint256 _assetAmountIn)\npublic\nview\nxCitadel.depositFor(msg.sender, citadelAmount_);\n\nemit Deposit(\nrequire(_amount != 0, \"Amount 0\");\nrequire(!pausedDeposit, \"pausedDeposit\"); // dev: deposits are paused\n\n", "completion": "Funding.deposit() doesn\u2019t work if there is no discount set"}
{"prompt": "vesting[recipient].unlockBegin = _unlockBegin;\nvesting[recipient].unlockEnd = _unlockBegin + vestingDuration;\n\nuint256 locked = vesting[recipient].lockedAmounts;\nuint256 claimed = vesting[recipient].claimedAmounts;\nif (block.timestamp >= vesting[recipient].unlockEnd) {\n", "completion": "New vest reset unlockBegin of existing vest without removing vested amount"}
{"prompt": "citadelPriceFlag = true;\nemit CitadelPriceFlag(\n_citadelPriceInAsset,\nminCitadelPriceInAsset,\nmaxCitadelPriceInAsset\n);\n} else {\ncitadelPriceInAsset = _citadelPriceInAsset;\n", "completion": "Stale price used when citadelPriceFlag is cleared"}
{"prompt": "shares = _amount;\n} else {\n//balanceBefore can't be 0 if totalSupply is > 0\nshares = (_amount * supply) / balanceBefore;\n}\n_mint(msg.sender, shares);\n", "completion": "yVault: First depositor can break minting of shares"}