file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // LC->07.08.2018 facts гл_предл language=Russian { arity=3 //violation_score=-5 generic return=boolean } #define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{} #region Предлог_В // ------------------- С ПРЕДЛОГОМ 'В' --------------------------- #region Предложный // Глаголы и отглагольные части речи, присоединяющие // предложное дополнение с предлогом В и сущ. в предложном падеже. wordentry_set Гл_В_Предл = { rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль // вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб rus_verbs:воевать{}, // Воевал во Франции. rus_verbs:устать{}, // Устали в дороге? rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения. rus_verbs:решить{}, // Что решат в правительстве? rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает. rus_verbs:обстоять{}, // В действительности же дело обстояло не так. rus_verbs:подыматься{}, rus_verbs:поехать{}, // поедем в такси! rus_verbs:уехать{}, // он уехал в такси rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей rus_verbs:ОБЛАЧИТЬ{}, rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло. rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ) rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ) rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ) rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ) rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ) rus_verbs:ЗАМАЯЧИТЬ{}, rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ) rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ) rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ) rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ) rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ) rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ) rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ) rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ) rus_verbs:ПоТЕРЯТЬ{}, rus_verbs:УТЕРЯТЬ{}, rus_verbs:РАСТЕРЯТЬ{}, rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.) rus_verbs:СОМКНУТЬСЯ{}, rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ) rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ) rus_verbs:ВЫСТОЯТЬ{}, rus_verbs:ПОСТОЯТЬ{}, rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ) rus_verbs:ВЗВЕШИВАТЬ{}, rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ) прилагательное:быстрый{}, // Кисель быстр в приготовлении rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень rus_verbs:призывать{}, rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ) rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ) rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ) rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ) rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ) rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ) rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ) rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ) rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ) rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ) rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ) rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ) rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ) rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ) rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ) rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ) rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ) rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ) rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ) rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ) rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ) rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ) rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ) rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ) rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ) rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ) rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ) rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ) инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан глагол:проводить{ вид:несоверш }, деепричастие:проводя{}, rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл) rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл) rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл) rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл) rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл) rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл) rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл) rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл) rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл) rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл) rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл) rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл) rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл) rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл) rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл) прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В) rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл) rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл) rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл) rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл) rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл) rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл) rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл) rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл) rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В) rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В) rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл) rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В) rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл) rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл) rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В) rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл) rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл) rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В) rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл) rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В) rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В) rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В) rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В) rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл) rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В) частица:нет{}, // В этом нет сомнения. частица:нету{}, // В этом нету сомнения. rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов. прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В) rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В) rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В) rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В) rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл) rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В) rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в) rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В) rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В) rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В) rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В) rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В) rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В) rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В) rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В) rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В) rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В) rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В) rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В) rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В) rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:РАСКЛАДЫВАТЬСЯ{}, rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В) rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В) rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В) rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В) rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл) rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В) rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В) инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В) глагол:НАПИСАТЬ{ aux stress="напис^ать" }, прилагательное:НАПИСАННЫЙ{}, rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В) rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В) rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В) rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В) rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В) rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В) rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл) rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл) rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В) безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в) rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В) rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В) rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В) rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В) rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В) rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В) rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В) rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В) rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В) rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В) rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В) rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В) rus_verbs:объявить{}, // В газете объявили о конкурсе. rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В) rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В) rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в) rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в) rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в) rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в) инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В) глагол:ПАРИТЬ{ aux stress="пар^ить"}, деепричастие:паря{ aux stress="пар^я" }, прилагательное:ПАРЯЩИЙ{}, прилагательное:ПАРИВШИЙ{}, rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В) rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В) rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в) rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В) rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В) rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В) rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В) rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В) rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В) rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в) rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в) rus_verbs:принять{}, // Документ принят в следующей редакции (принять в) rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в) rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В) rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в) rus_verbs:звучать{}, // в доме звучала музыка (звучать в) rus_verbs:колебаться{}, // колеблется в выборе (колебаться в) rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в) rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в) rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в) rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в) rus_verbs:вычитывать{}, // вычитывать в книге rus_verbs:гудеть{}, // У него в ушах гудит. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки. rus_verbs:разойтись{}, // Они разошлись в темноте. rus_verbs:прибежать{}, // Мальчик прибежал в слезах. rus_verbs:биться{}, // Она билась в истерике. rus_verbs:регистрироваться{}, // регистрироваться в системе rus_verbs:считать{}, // я буду считать в уме rus_verbs:трахаться{}, // трахаться в гамаке rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке rus_verbs:разрушать{}, // разрушать в дробилке rus_verbs:засидеться{}, // засидеться в гостях rus_verbs:засиживаться{}, // засиживаться в гостях rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке) rus_verbs:навестить{}, // навестить в доме престарелых rus_verbs:запомнить{}, // запомнить в кэше rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.) rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка) rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику. rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.) rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу rus_verbs:оглядываться{}, // оглядываться в зеркале rus_verbs:нарисовать{}, // нарисовать в тетрадке rus_verbs:пробить{}, // пробить отверствие в стене rus_verbs:повертеть{}, // повертеть в руке rus_verbs:вертеть{}, // Я вертел в руках rus_verbs:рваться{}, // Веревка рвется в месте надреза rus_verbs:распространяться{}, // распространяться в среде наркоманов rus_verbs:попрощаться{}, // попрощаться в здании морга rus_verbs:соображать{}, // соображать в уме инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот) rus_verbs:разобрать{}, // разобрать в гараже rus_verbs:помереть{}, // помереть в пути rus_verbs:различить{}, // различить в темноте rus_verbs:рисовать{}, // рисовать в графическом редакторе rus_verbs:проследить{}, // проследить в записях камер слежения rus_verbs:совершаться{}, // Правосудие совершается в суде rus_verbs:задремать{}, // задремать в кровати rus_verbs:ругаться{}, // ругаться в комнате rus_verbs:зазвучать{}, // зазвучать в радиоприемниках rus_verbs:задохнуться{}, // задохнуться в воде rus_verbs:порождать{}, // порождать в неокрепших умах rus_verbs:отдыхать{}, // отдыхать в санатории rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении rus_verbs:образовать{}, // образовать в пробирке темную взвесь rus_verbs:отмечать{}, // отмечать в списке rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте rus_verbs:плясать{}, // плясать в откружении незнакомых людей rus_verbs:повысить{}, // повысить в звании rus_verbs:поджидать{}, // поджидать в подъезде rus_verbs:отказать{}, // отказать в пересмотре дела rus_verbs:раствориться{}, // раствориться в бензине rus_verbs:отражать{}, // отражать в стихах rus_verbs:дремать{}, // дремать в гамаке rus_verbs:применяться{}, // применяться в домашних условиях rus_verbs:присниться{}, // присниться во сне rus_verbs:трястись{}, // трястись в драндулете rus_verbs:сохранять{}, // сохранять в неприкосновенности rus_verbs:расстрелять{}, // расстрелять в ложбине rus_verbs:рассчитать{}, // рассчитать в программе rus_verbs:перебирать{}, // перебирать в руке rus_verbs:разбиться{}, // разбиться в аварии rus_verbs:поискать{}, // поискать в углу rus_verbs:мучиться{}, // мучиться в тесной клетке rus_verbs:замелькать{}, // замелькать в телевизоре rus_verbs:грустить{}, // грустить в одиночестве rus_verbs:крутить{}, // крутить в банке rus_verbs:объявиться{}, // объявиться в городе rus_verbs:подготовить{}, // подготовить в тайне rus_verbs:различать{}, // различать в смеси rus_verbs:обнаруживать{}, // обнаруживать в крови rus_verbs:киснуть{}, // киснуть в захолустье rus_verbs:оборваться{}, // оборваться в начале фразы rus_verbs:запутаться{}, // запутаться в веревках rus_verbs:общаться{}, // общаться в интимной обстановке rus_verbs:сочинить{}, // сочинить в ресторане rus_verbs:изобрести{}, // изобрести в домашней лаборатории rus_verbs:прокомментировать{}, // прокомментировать в своем блоге rus_verbs:давить{}, // давить в зародыше rus_verbs:повториться{}, // повториться в новом обличье rus_verbs:отставать{}, // отставать в общем зачете rus_verbs:разработать{}, // разработать в лаборатории rus_verbs:качать{}, // качать в кроватке rus_verbs:заменить{}, // заменить в двигателе rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере rus_verbs:забегать{}, // забегать в спешке rus_verbs:наделать{}, // наделать в решении ошибок rus_verbs:исказиться{}, // исказиться в кривом зеркале rus_verbs:тушить{}, // тушить в помещении пожар rus_verbs:охранять{}, // охранять в здании входы rus_verbs:приметить{}, // приметить в кустах rus_verbs:скрыть{}, // скрыть в складках одежды rus_verbs:удерживать{}, // удерживать в заложниках rus_verbs:увеличиваться{}, // увеличиваться в размере rus_verbs:красоваться{}, // красоваться в новом платье rus_verbs:сохраниться{}, // сохраниться в тепле rus_verbs:лечить{}, // лечить в стационаре rus_verbs:смешаться{}, // смешаться в баке rus_verbs:прокатиться{}, // прокатиться в троллейбусе rus_verbs:договариваться{}, // договариваться в закрытом кабинете rus_verbs:опубликовать{}, // опубликовать в официальном блоге rus_verbs:охотиться{}, // охотиться в прериях rus_verbs:отражаться{}, // отражаться в окне rus_verbs:понизить{}, // понизить в должности rus_verbs:обедать{}, // обедать в ресторане rus_verbs:посидеть{}, // посидеть в тени rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете rus_verbs:свершиться{}, // свершиться в суде rus_verbs:ночевать{}, // ночевать в гостинице rus_verbs:темнеть{}, // темнеть в воде rus_verbs:гибнуть{}, // гибнуть в застенках rus_verbs:усиливаться{}, // усиливаться в направлении главного удара rus_verbs:расплыться{}, // расплыться в улыбке rus_verbs:превышать{}, // превышать в несколько раз rus_verbs:проживать{}, // проживать в отдельной коморке rus_verbs:голубеть{}, // голубеть в тепле rus_verbs:исследовать{}, // исследовать в естественных условиях rus_verbs:обитать{}, // обитать в лесу rus_verbs:скучать{}, // скучать в одиночестве rus_verbs:сталкиваться{}, // сталкиваться в воздухе rus_verbs:таиться{}, // таиться в глубине rus_verbs:спасать{}, // спасать в море rus_verbs:заблудиться{}, // заблудиться в лесу rus_verbs:создаться{}, // создаться в новом виде rus_verbs:пошарить{}, // пошарить в кармане rus_verbs:планировать{}, // планировать в программе rus_verbs:отбить{}, // отбить в нижней части rus_verbs:отрицать{}, // отрицать в суде свою вину rus_verbs:основать{}, // основать в пустыне новый город rus_verbs:двоить{}, // двоить в глазах rus_verbs:устоять{}, // устоять в лодке rus_verbs:унять{}, // унять в ногах дрожь rus_verbs:отзываться{}, // отзываться в обзоре rus_verbs:притормозить{}, // притормозить в траве rus_verbs:читаться{}, // читаться в глазах rus_verbs:житься{}, // житься в деревне rus_verbs:заиграть{}, // заиграть в жилах rus_verbs:шевелить{}, // шевелить в воде rus_verbs:зазвенеть{}, // зазвенеть в ушах rus_verbs:зависнуть{}, // зависнуть в библиотеке rus_verbs:затаить{}, // затаить в душе обиду rus_verbs:сознаться{}, // сознаться в совершении rus_verbs:протекать{}, // протекать в легкой форме rus_verbs:выясняться{}, // выясняться в ходе эксперимента rus_verbs:скрестить{}, // скрестить в неволе rus_verbs:наводить{}, // наводить в комнате порядок rus_verbs:значиться{}, // значиться в документах rus_verbs:заинтересовать{}, // заинтересовать в получении результатов rus_verbs:познакомить{}, // познакомить в непринужденной обстановке rus_verbs:рассеяться{}, // рассеяться в воздухе rus_verbs:грохнуть{}, // грохнуть в подвале rus_verbs:обвинять{}, // обвинять в вымогательстве rus_verbs:столпиться{}, // столпиться в фойе rus_verbs:порыться{}, // порыться в сумке rus_verbs:ослабить{}, // ослабить в верхней части rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки rus_verbs:спастись{}, // спастись в хижине rus_verbs:прерваться{}, // прерваться в середине фразы rus_verbs:применять{}, // применять в повседневной работе rus_verbs:строиться{}, // строиться в зоне отчуждения rus_verbs:путешествовать{}, // путешествовать в самолете rus_verbs:побеждать{}, // побеждать в честной битве rus_verbs:погубить{}, // погубить в себе артиста rus_verbs:рассматриваться{}, // рассматриваться в следующей главе rus_verbs:продаваться{}, // продаваться в специализированном магазине rus_verbs:разместиться{}, // разместиться в аудитории rus_verbs:повидать{}, // повидать в жизни rus_verbs:настигнуть{}, // настигнуть в пригородах rus_verbs:сгрудиться{}, // сгрудиться в центре загона rus_verbs:укрыться{}, // укрыться в доме rus_verbs:расплакаться{}, // расплакаться в суде rus_verbs:пролежать{}, // пролежать в канаве rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде rus_verbs:поскользнуться{}, // поскользнуться в коридоре rus_verbs:таскать{}, // таскать в руках rus_verbs:нападать{}, // нападать в вольере rus_verbs:просматривать{}, // просматривать в браузере rus_verbs:обдумать{}, // обдумать в дороге rus_verbs:обвинить{}, // обвинить в измене rus_verbs:останавливать{}, // останавливать в дверях rus_verbs:теряться{}, // теряться в догадках rus_verbs:погибать{}, // погибать в бою rus_verbs:обозначать{}, // обозначать в списке rus_verbs:запрещать{}, // запрещать в парке rus_verbs:долететь{}, // долететь в вертолёте rus_verbs:тесниться{}, // тесниться в каморке rus_verbs:уменьшаться{}, // уменьшаться в размере rus_verbs:издавать{}, // издавать в небольшом издательстве rus_verbs:хоронить{}, // хоронить в море rus_verbs:перемениться{}, // перемениться в лице rus_verbs:установиться{}, // установиться в северных областях rus_verbs:прикидывать{}, // прикидывать в уме rus_verbs:затаиться{}, // затаиться в траве rus_verbs:раздобыть{}, // раздобыть в аптеке rus_verbs:перебросить{}, // перебросить в товарном составе rus_verbs:погружаться{}, // погружаться в батискафе rus_verbs:поживать{}, // поживать в одиночестве rus_verbs:признаваться{}, // признаваться в любви rus_verbs:захватывать{}, // захватывать в здании rus_verbs:покачиваться{}, // покачиваться в лодке rus_verbs:крутиться{}, // крутиться в колесе rus_verbs:помещаться{}, // помещаться в ящике rus_verbs:питаться{}, // питаться в столовой rus_verbs:отдохнуть{}, // отдохнуть в пансионате rus_verbs:кататься{}, // кататься в коляске rus_verbs:поработать{}, // поработать в цеху rus_verbs:подразумевать{}, // подразумевать в задании rus_verbs:ограбить{}, // ограбить в подворотне rus_verbs:преуспеть{}, // преуспеть в бизнесе rus_verbs:заерзать{}, // заерзать в кресле rus_verbs:разъяснить{}, // разъяснить в другой статье rus_verbs:продвинуться{}, // продвинуться в изучении rus_verbs:поколебаться{}, // поколебаться в начале rus_verbs:засомневаться{}, // засомневаться в честности rus_verbs:приникнуть{}, // приникнуть в уме rus_verbs:скривить{}, // скривить в усмешке rus_verbs:рассечь{}, // рассечь в центре опухоли rus_verbs:перепутать{}, // перепутать в роддоме rus_verbs:посмеяться{}, // посмеяться в перерыве rus_verbs:отмечаться{}, // отмечаться в полицейском участке rus_verbs:накопиться{}, // накопиться в отстойнике rus_verbs:уносить{}, // уносить в руках rus_verbs:навещать{}, // навещать в больнице rus_verbs:остыть{}, // остыть в проточной воде rus_verbs:запереться{}, // запереться в комнате rus_verbs:обогнать{}, // обогнать в первом круге rus_verbs:убеждаться{}, // убеждаться в неизбежности rus_verbs:подбирать{}, // подбирать в магазине rus_verbs:уничтожать{}, // уничтожать в полете rus_verbs:путаться{}, // путаться в показаниях rus_verbs:притаиться{}, // притаиться в темноте rus_verbs:проплывать{}, // проплывать в лодке rus_verbs:засесть{}, // засесть в окопе rus_verbs:подцепить{}, // подцепить в баре rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок rus_verbs:оправдаться{}, // оправдаться в суде rus_verbs:созреть{}, // созреть в естественных условиях rus_verbs:раскрываться{}, // раскрываться в подходящих условиях rus_verbs:ожидаться{}, // ожидаться в верхней части rus_verbs:одеваться{}, // одеваться в дорогих бутиках rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта rus_verbs:грабить{}, // грабить в подворотне rus_verbs:ужинать{}, // ужинать в ресторане rus_verbs:гонять{}, // гонять в жилах rus_verbs:уверить{}, // уверить в безопасности rus_verbs:потеряться{}, // потеряться в лесу rus_verbs:устанавливаться{}, // устанавливаться в комнате rus_verbs:предоставлять{}, // предоставлять в суде rus_verbs:протянуться{}, // протянуться в стене rus_verbs:допрашивать{}, // допрашивать в бункере rus_verbs:проработать{}, // проработать в кабинете rus_verbs:сосредоточить{}, // сосредоточить в своих руках rus_verbs:утвердить{}, // утвердить в должности rus_verbs:сочинять{}, // сочинять в дороге rus_verbs:померкнуть{}, // померкнуть в глазах rus_verbs:показываться{}, // показываться в окошке rus_verbs:похудеть{}, // похудеть в талии rus_verbs:проделывать{}, // проделывать в стене rus_verbs:прославиться{}, // прославиться в интернете rus_verbs:сдохнуть{}, // сдохнуть в нищете rus_verbs:раскинуться{}, // раскинуться в степи rus_verbs:развить{}, // развить в себе способности rus_verbs:уставать{}, // уставать в цеху rus_verbs:укрепить{}, // укрепить в земле rus_verbs:числиться{}, // числиться в списке rus_verbs:образовывать{}, // образовывать в смеси rus_verbs:екнуть{}, // екнуть в груди rus_verbs:одобрять{}, // одобрять в своей речи rus_verbs:запить{}, // запить в одиночестве rus_verbs:забыться{}, // забыться в тяжелом сне rus_verbs:чернеть{}, // чернеть в кислой среде rus_verbs:размещаться{}, // размещаться в гараже rus_verbs:соорудить{}, // соорудить в гараже rus_verbs:развивать{}, // развивать в себе rus_verbs:пастись{}, // пастись в пойме rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы rus_verbs:ослабнуть{}, // ослабнуть в сочленении rus_verbs:таить{}, // таить в себе инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке rus_verbs:приостановиться{}, // приостановиться в конце rus_verbs:топтаться{}, // топтаться в грязи rus_verbs:громить{}, // громить в финале rus_verbs:заменять{}, // заменять в основном составе rus_verbs:подъезжать{}, // подъезжать в колясках rus_verbs:вычислить{}, // вычислить в уме rus_verbs:заказывать{}, // заказывать в магазине rus_verbs:осуществить{}, // осуществить в реальных условиях rus_verbs:обосноваться{}, // обосноваться в дупле rus_verbs:пытать{}, // пытать в камере rus_verbs:поменять{}, // поменять в магазине rus_verbs:совершиться{}, // совершиться в суде rus_verbs:пролетать{}, // пролетать в вертолете rus_verbs:сбыться{}, // сбыться во сне rus_verbs:разговориться{}, // разговориться в отделении rus_verbs:преподнести{}, // преподнести в красивой упаковке rus_verbs:напечатать{}, // напечатать в типографии rus_verbs:прорвать{}, // прорвать в центре rus_verbs:раскачиваться{}, // раскачиваться в кресле rus_verbs:задерживаться{}, // задерживаться в дверях rus_verbs:угощать{}, // угощать в кафе rus_verbs:проступать{}, // проступать в глубине rus_verbs:шарить{}, // шарить в математике rus_verbs:увеличивать{}, // увеличивать в конце rus_verbs:расцвести{}, // расцвести в оранжерее rus_verbs:закипеть{}, // закипеть в баке rus_verbs:подлететь{}, // подлететь в вертолете rus_verbs:рыться{}, // рыться в куче rus_verbs:пожить{}, // пожить в гостинице rus_verbs:добираться{}, // добираться в попутном транспорте rus_verbs:перекрыть{}, // перекрыть в коридоре rus_verbs:продержаться{}, // продержаться в барокамере rus_verbs:разыскивать{}, // разыскивать в толпе rus_verbs:освобождать{}, // освобождать в зале суда rus_verbs:подметить{}, // подметить в человеке rus_verbs:передвигаться{}, // передвигаться в узкой юбке rus_verbs:продумать{}, // продумать в уме rus_verbs:извиваться{}, // извиваться в траве rus_verbs:процитировать{}, // процитировать в статье rus_verbs:прогуливаться{}, // прогуливаться в парке rus_verbs:защемить{}, // защемить в двери rus_verbs:увеличиться{}, // увеличиться в объеме rus_verbs:проявиться{}, // проявиться в результатах rus_verbs:заскользить{}, // заскользить в ботинках rus_verbs:пересказать{}, // пересказать в своем выступлении rus_verbs:протестовать{}, // протестовать в здании парламента rus_verbs:указываться{}, // указываться в путеводителе rus_verbs:копошиться{}, // копошиться в песке rus_verbs:проигнорировать{}, // проигнорировать в своей работе rus_verbs:купаться{}, // купаться в речке rus_verbs:подсчитать{}, // подсчитать в уме rus_verbs:разволноваться{}, // разволноваться в классе rus_verbs:придумывать{}, // придумывать в своем воображении rus_verbs:предусмотреть{}, // предусмотреть в программе rus_verbs:завертеться{}, // завертеться в колесе rus_verbs:зачерпнуть{}, // зачерпнуть в ручье rus_verbs:очистить{}, // очистить в химической лаборатории rus_verbs:прозвенеть{}, // прозвенеть в коридорах rus_verbs:уменьшиться{}, // уменьшиться в размере rus_verbs:колыхаться{}, // колыхаться в проточной воде rus_verbs:ознакомиться{}, // ознакомиться в автобусе rus_verbs:ржать{}, // ржать в аудитории rus_verbs:раскинуть{}, // раскинуть в микрорайоне rus_verbs:разлиться{}, // разлиться в воде rus_verbs:сквозить{}, // сквозить в словах rus_verbs:задушить{}, // задушить в объятиях rus_verbs:осудить{}, // осудить в особом порядке rus_verbs:разгромить{}, // разгромить в честном поединке rus_verbs:подслушать{}, // подслушать в кулуарах rus_verbs:проповедовать{}, // проповедовать в сельских районах rus_verbs:озарить{}, // озарить во сне rus_verbs:потирать{}, // потирать в предвкушении rus_verbs:описываться{}, // описываться в статье rus_verbs:качаться{}, // качаться в кроватке rus_verbs:усилить{}, // усилить в центре rus_verbs:прохаживаться{}, // прохаживаться в новом костюме rus_verbs:полечить{}, // полечить в больничке rus_verbs:сниматься{}, // сниматься в римейке rus_verbs:сыскать{}, // сыскать в наших краях rus_verbs:поприветствовать{}, // поприветствовать в коридоре rus_verbs:подтвердиться{}, // подтвердиться в эксперименте rus_verbs:плескаться{}, // плескаться в теплой водичке rus_verbs:расширяться{}, // расширяться в первом сегменте rus_verbs:мерещиться{}, // мерещиться в тумане rus_verbs:сгущаться{}, // сгущаться в воздухе rus_verbs:храпеть{}, // храпеть во сне rus_verbs:подержать{}, // подержать в руках rus_verbs:накинуться{}, // накинуться в подворотне rus_verbs:планироваться{}, // планироваться в закрытом режиме rus_verbs:пробудить{}, // пробудить в себе rus_verbs:побриться{}, // побриться в ванной rus_verbs:сгинуть{}, // сгинуть в пучине rus_verbs:окрестить{}, // окрестить в церкви инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления rus_verbs:замкнуться{}, // замкнуться в себе rus_verbs:прибавлять{}, // прибавлять в весе rus_verbs:проплыть{}, // проплыть в лодке rus_verbs:растворяться{}, // растворяться в тумане rus_verbs:упрекать{}, // упрекать в небрежности rus_verbs:затеряться{}, // затеряться в лабиринте rus_verbs:перечитывать{}, // перечитывать в поезде rus_verbs:перелететь{}, // перелететь в вертолете rus_verbs:оживать{}, // оживать в теплой воде rus_verbs:заглохнуть{}, // заглохнуть в полете rus_verbs:кольнуть{}, // кольнуть в боку rus_verbs:копаться{}, // копаться в куче rus_verbs:развлекаться{}, // развлекаться в клубе rus_verbs:отливать{}, // отливать в кустах rus_verbs:зажить{}, // зажить в деревне rus_verbs:одолжить{}, // одолжить в соседнем кабинете rus_verbs:заклинать{}, // заклинать в своей речи rus_verbs:различаться{}, // различаться в мелочах rus_verbs:печататься{}, // печататься в типографии rus_verbs:угадываться{}, // угадываться в контурах rus_verbs:обрывать{}, // обрывать в начале rus_verbs:поглаживать{}, // поглаживать в кармане rus_verbs:подписывать{}, // подписывать в присутствии понятых rus_verbs:добывать{}, // добывать в разломе rus_verbs:скопиться{}, // скопиться в воротах rus_verbs:повстречать{}, // повстречать в бане rus_verbs:совпасть{}, // совпасть в упрощенном виде rus_verbs:разрываться{}, // разрываться в точке спайки rus_verbs:улавливать{}, // улавливать в датчике rus_verbs:повстречаться{}, // повстречаться в лифте rus_verbs:отразить{}, // отразить в отчете rus_verbs:пояснять{}, // пояснять в примечаниях rus_verbs:накормить{}, // накормить в столовке rus_verbs:поужинать{}, // поужинать в ресторане инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить в молоке rus_verbs:освоить{}, // освоить в работе rus_verbs:зародиться{}, // зародиться в голове rus_verbs:отплыть{}, // отплыть в старой лодке rus_verbs:отстаивать{}, // отстаивать в суде rus_verbs:осуждать{}, // осуждать в своем выступлении rus_verbs:переговорить{}, // переговорить в перерыве rus_verbs:разгораться{}, // разгораться в сердце rus_verbs:укрыть{}, // укрыть в шалаше rus_verbs:томиться{}, // томиться в застенках rus_verbs:клубиться{}, // клубиться в воздухе rus_verbs:сжигать{}, // сжигать в топке rus_verbs:позавтракать{}, // позавтракать в кафешке rus_verbs:функционировать{}, // функционировать в лабораторных условиях rus_verbs:смять{}, // смять в руке rus_verbs:разместить{}, // разместить в интернете rus_verbs:пронести{}, // пронести в потайном кармане rus_verbs:руководствоваться{}, // руководствоваться в работе rus_verbs:нашарить{}, // нашарить в потемках rus_verbs:закрутить{}, // закрутить в вихре rus_verbs:просматриваться{}, // просматриваться в дальней перспективе rus_verbs:распознать{}, // распознать в незнакомце rus_verbs:повеситься{}, // повеситься в камере rus_verbs:обшарить{}, // обшарить в поисках наркотиков rus_verbs:наполняться{}, // наполняется в карьере rus_verbs:засвистеть{}, // засвистеть в воздухе rus_verbs:процветать{}, // процветать в мягком климате rus_verbs:шуршать{}, // шуршать в простенке rus_verbs:подхватывать{}, // подхватывать в полете инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе прилагательное:роившийся{}, прилагательное:роящийся{}, // деепричастие:роясь{ aux stress="ро^ясь" }, rus_verbs:преобладать{}, // преобладать в тексте rus_verbs:посветлеть{}, // посветлеть в лице rus_verbs:игнорировать{}, // игнорировать в рекомендациях rus_verbs:обсуждаться{}, // обсуждаться в кулуарах rus_verbs:отказывать{}, // отказывать в визе rus_verbs:ощупывать{}, // ощупывать в кармане rus_verbs:разливаться{}, // разливаться в цеху rus_verbs:расписаться{}, // расписаться в получении rus_verbs:учинить{}, // учинить в казарме rus_verbs:плестись{}, // плестись в хвосте rus_verbs:объявляться{}, // объявляться в группе rus_verbs:повышаться{}, // повышаться в первой части rus_verbs:напрягать{}, // напрягать в паху rus_verbs:разрабатывать{}, // разрабатывать в студии rus_verbs:хлопотать{}, // хлопотать в мэрии rus_verbs:прерывать{}, // прерывать в самом начале rus_verbs:каяться{}, // каяться в грехах rus_verbs:освоиться{}, // освоиться в кабине rus_verbs:подплыть{}, // подплыть в лодке rus_verbs:замигать{}, // замигать в темноте rus_verbs:оскорблять{}, // оскорблять в выступлении rus_verbs:торжествовать{}, // торжествовать в душе rus_verbs:поправлять{}, // поправлять в прологе rus_verbs:угадывать{}, // угадывать в размытом изображении rus_verbs:потоптаться{}, // потоптаться в прихожей rus_verbs:переправиться{}, // переправиться в лодочке rus_verbs:увериться{}, // увериться в невиновности rus_verbs:забрезжить{}, // забрезжить в конце тоннеля rus_verbs:утвердиться{}, // утвердиться во мнении rus_verbs:завывать{}, // завывать в трубе rus_verbs:заварить{}, // заварить в заварнике rus_verbs:скомкать{}, // скомкать в руке rus_verbs:перемещаться{}, // перемещаться в капсуле инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле rus_verbs:праздновать{}, // праздновать в баре rus_verbs:мигать{}, // мигать в темноте rus_verbs:обучить{}, // обучить в мастерской rus_verbs:орудовать{}, // орудовать в кладовке rus_verbs:упорствовать{}, // упорствовать в заблуждении rus_verbs:переминаться{}, // переминаться в прихожей rus_verbs:подрасти{}, // подрасти в теплице rus_verbs:предписываться{}, // предписываться в законе rus_verbs:приписать{}, // приписать в конце rus_verbs:задаваться{}, // задаваться в своей статье rus_verbs:чинить{}, // чинить в домашних условиях rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке rus_verbs:пообедать{}, // пообедать в ресторанчике rus_verbs:жрать{}, // жрать в чуланчике rus_verbs:исполняться{}, // исполняться в антракте rus_verbs:гнить{}, // гнить в тюрьме rus_verbs:глодать{}, // глодать в конуре rus_verbs:прослушать{}, // прослушать в дороге rus_verbs:истратить{}, // истратить в кабаке rus_verbs:стареть{}, // стареть в одиночестве rus_verbs:разжечь{}, // разжечь в сердце rus_verbs:совещаться{}, // совещаться в кабинете rus_verbs:покачивать{}, // покачивать в кроватке rus_verbs:отсидеть{}, // отсидеть в одиночке rus_verbs:формировать{}, // формировать в умах rus_verbs:захрапеть{}, // захрапеть во сне rus_verbs:петься{}, // петься в хоре rus_verbs:объехать{}, // объехать в автобусе rus_verbs:поселить{}, // поселить в гостинице rus_verbs:предаться{}, // предаться в книге rus_verbs:заворочаться{}, // заворочаться во сне rus_verbs:напрятать{}, // напрятать в карманах rus_verbs:очухаться{}, // очухаться в незнакомом месте rus_verbs:ограничивать{}, // ограничивать в движениях rus_verbs:завертеть{}, // завертеть в руках rus_verbs:печатать{}, // печатать в редакторе rus_verbs:теплиться{}, // теплиться в сердце rus_verbs:увязнуть{}, // увязнуть в зыбучем песке rus_verbs:усмотреть{}, // усмотреть в обращении rus_verbs:отыскаться{}, // отыскаться в запасах rus_verbs:потушить{}, // потушить в горле огонь rus_verbs:поубавиться{}, // поубавиться в размере rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти rus_verbs:смыть{}, // смыть в ванной rus_verbs:заместить{}, // заместить в кресле rus_verbs:угасать{}, // угасать в одиночестве rus_verbs:сразить{}, // сразить в споре rus_verbs:фигурировать{}, // фигурировать в бюллетене rus_verbs:расплываться{}, // расплываться в глазах rus_verbs:сосчитать{}, // сосчитать в уме rus_verbs:сгуститься{}, // сгуститься в воздухе rus_verbs:цитировать{}, // цитировать в своей статье rus_verbs:помяться{}, // помяться в давке rus_verbs:затрагивать{}, // затрагивать в процессе выполнения rus_verbs:обтереть{}, // обтереть в гараже rus_verbs:подстрелить{}, // подстрелить в пойме реки rus_verbs:растереть{}, // растереть в руке rus_verbs:подавлять{}, // подавлять в зародыше rus_verbs:смешиваться{}, // смешиваться в чане инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке rus_verbs:сократиться{}, // сократиться в обхвате rus_verbs:занервничать{}, // занервничать в кабинете rus_verbs:соприкоснуться{}, // соприкоснуться в полете rus_verbs:обозначить{}, // обозначить в объявлении rus_verbs:обучаться{}, // обучаться в училище rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы rus_verbs:лелеять{}, // лелеять в сердце rus_verbs:поддерживаться{}, // поддерживаться в суде rus_verbs:уплыть{}, // уплыть в лодочке rus_verbs:резвиться{}, // резвиться в саду rus_verbs:поерзать{}, // поерзать в гамаке rus_verbs:оплатить{}, // оплатить в ресторане rus_verbs:похвастаться{}, // похвастаться в компании rus_verbs:знакомиться{}, // знакомиться в классе rus_verbs:приплыть{}, // приплыть в подводной лодке rus_verbs:зажигать{}, // зажигать в классе rus_verbs:смыслить{}, // смыслить в математике rus_verbs:закопать{}, // закопать в огороде rus_verbs:порхать{}, // порхать в зарослях rus_verbs:потонуть{}, // потонуть в бумажках rus_verbs:стирать{}, // стирать в холодной воде rus_verbs:подстерегать{}, // подстерегать в придорожных кустах rus_verbs:погулять{}, // погулять в парке rus_verbs:предвкушать{}, // предвкушать в воображении rus_verbs:ошеломить{}, // ошеломить в бою rus_verbs:удостовериться{}, // удостовериться в безопасности rus_verbs:огласить{}, // огласить в заключительной части rus_verbs:разбогатеть{}, // разбогатеть в деревне rus_verbs:грохотать{}, // грохотать в мастерской rus_verbs:реализоваться{}, // реализоваться в должности rus_verbs:красть{}, // красть в магазине rus_verbs:нарваться{}, // нарваться в коридоре rus_verbs:застывать{}, // застывать в неудобной позе rus_verbs:толкаться{}, // толкаться в тесной комнате rus_verbs:извлекать{}, // извлекать в аппарате rus_verbs:обжигать{}, // обжигать в печи rus_verbs:запечатлеть{}, // запечатлеть в кинохронике rus_verbs:тренироваться{}, // тренироваться в зале rus_verbs:поспорить{}, // поспорить в кабинете rus_verbs:рыскать{}, // рыскать в лесу rus_verbs:надрываться{}, // надрываться в шахте rus_verbs:сняться{}, // сняться в фильме rus_verbs:закружить{}, // закружить в танце rus_verbs:затонуть{}, // затонуть в порту rus_verbs:побыть{}, // побыть в гостях rus_verbs:почистить{}, // почистить в носу rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре rus_verbs:подслушивать{}, // подслушивать в классе rus_verbs:сгорать{}, // сгорать в танке rus_verbs:разочароваться{}, // разочароваться в артисте инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках rus_verbs:мять{}, // мять в руках rus_verbs:подраться{}, // подраться в классе rus_verbs:замести{}, // замести в прихожей rus_verbs:откладываться{}, // откладываться в печени rus_verbs:обозначаться{}, // обозначаться в перечне rus_verbs:просиживать{}, // просиживать в интернете rus_verbs:соприкасаться{}, // соприкасаться в точке rus_verbs:начертить{}, // начертить в тетрадке rus_verbs:уменьшать{}, // уменьшать в поперечнике rus_verbs:тормозить{}, // тормозить в облаке rus_verbs:затевать{}, // затевать в лаборатории rus_verbs:затопить{}, // затопить в бухте rus_verbs:задерживать{}, // задерживать в лифте rus_verbs:прогуляться{}, // прогуляться в лесу rus_verbs:прорубить{}, // прорубить во льду rus_verbs:очищать{}, // очищать в кислоте rus_verbs:полулежать{}, // полулежать в гамаке rus_verbs:исправить{}, // исправить в задании rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи rus_verbs:замучить{}, // замучить в плену rus_verbs:разрушаться{}, // разрушаться в верхней части rus_verbs:ерзать{}, // ерзать в кресле rus_verbs:покопаться{}, // покопаться в залежах rus_verbs:раскаяться{}, // раскаяться в содеянном rus_verbs:пробежаться{}, // пробежаться в парке rus_verbs:полежать{}, // полежать в гамаке rus_verbs:позаимствовать{}, // позаимствовать в книге rus_verbs:снижать{}, // снижать в несколько раз rus_verbs:черпать{}, // черпать в поэзии rus_verbs:заверять{}, // заверять в своей искренности rus_verbs:проглядеть{}, // проглядеть в сумерках rus_verbs:припарковать{}, // припарковать во дворе rus_verbs:сверлить{}, // сверлить в стене rus_verbs:здороваться{}, // здороваться в аудитории rus_verbs:рожать{}, // рожать в воде rus_verbs:нацарапать{}, // нацарапать в тетрадке rus_verbs:затопать{}, // затопать в коридоре rus_verbs:прописать{}, // прописать в правилах rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах rus_verbs:снизить{}, // снизить в несколько раз rus_verbs:заблуждаться{}, // заблуждаться в своей теории rus_verbs:откопать{}, // откопать в отвалах rus_verbs:смастерить{}, // смастерить в лаборатории rus_verbs:замедлиться{}, // замедлиться в парафине rus_verbs:избивать{}, // избивать в участке rus_verbs:мыться{}, // мыться в бане rus_verbs:сварить{}, // сварить в кастрюльке rus_verbs:раскопать{}, // раскопать в снегу rus_verbs:крепиться{}, // крепиться в держателе rus_verbs:дробить{}, // дробить в мельнице rus_verbs:попить{}, // попить в ресторанчике rus_verbs:затронуть{}, // затронуть в душе rus_verbs:лязгнуть{}, // лязгнуть в тишине rus_verbs:заправлять{}, // заправлять в полете rus_verbs:размножаться{}, // размножаться в неволе rus_verbs:потопить{}, // потопить в Тихом Океане rus_verbs:кушать{}, // кушать в столовой rus_verbs:замолкать{}, // замолкать в замешательстве rus_verbs:измеряться{}, // измеряться в дюймах rus_verbs:сбываться{}, // сбываться в мечтах rus_verbs:задернуть{}, // задернуть в комнате rus_verbs:затихать{}, // затихать в темноте rus_verbs:прослеживаться{}, // прослеживается в журнале rus_verbs:прерываться{}, // прерывается в начале rus_verbs:изображаться{}, // изображается в любых фильмах rus_verbs:фиксировать{}, // фиксировать в данной точке rus_verbs:ослаблять{}, // ослаблять в поясе rus_verbs:зреть{}, // зреть в теплице rus_verbs:зеленеть{}, // зеленеть в огороде rus_verbs:критиковать{}, // критиковать в статье rus_verbs:облететь{}, // облететь в частном вертолете rus_verbs:разбросать{}, // разбросать в комнате rus_verbs:заразиться{}, // заразиться в людном месте rus_verbs:рассеять{}, // рассеять в бою rus_verbs:печься{}, // печься в духовке rus_verbs:поспать{}, // поспать в палатке rus_verbs:заступиться{}, // заступиться в драке rus_verbs:сплетаться{}, // сплетаться в середине rus_verbs:поместиться{}, // поместиться в мешке rus_verbs:спереть{}, // спереть в лавке // инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде // инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш }, rus_verbs:проваляться{}, // проваляться в постели rus_verbs:лечиться{}, // лечиться в стационаре rus_verbs:определиться{}, // определиться в честном бою rus_verbs:обработать{}, // обработать в растворе rus_verbs:пробивать{}, // пробивать в стене rus_verbs:перемешаться{}, // перемешаться в чане rus_verbs:чесать{}, // чесать в паху rus_verbs:пролечь{}, // пролечь в пустынной местности rus_verbs:скитаться{}, // скитаться в дальних странах rus_verbs:затрудняться{}, // затрудняться в выборе rus_verbs:отряхнуться{}, // отряхнуться в коридоре rus_verbs:разыгрываться{}, // разыгрываться в лотерее rus_verbs:помолиться{}, // помолиться в церкви rus_verbs:предписывать{}, // предписывать в рецепте rus_verbs:порваться{}, // порваться в слабом месте rus_verbs:греться{}, // греться в здании rus_verbs:опровергать{}, // опровергать в своем выступлении rus_verbs:помянуть{}, // помянуть в своем выступлении rus_verbs:допросить{}, // допросить в прокуратуре rus_verbs:материализоваться{}, // материализоваться в соседнем здании rus_verbs:рассеиваться{}, // рассеиваться в воздухе rus_verbs:перевозить{}, // перевозить в вагоне rus_verbs:отбывать{}, // отбывать в тюрьме rus_verbs:попахивать{}, // попахивать в отхожем месте rus_verbs:перечислять{}, // перечислять в заключении rus_verbs:зарождаться{}, // зарождаться в дебрях rus_verbs:предъявлять{}, // предъявлять в своем письме rus_verbs:распространять{}, // распространять в сети rus_verbs:пировать{}, // пировать в соседнем селе rus_verbs:начертать{}, // начертать в летописи rus_verbs:расцветать{}, // расцветать в подходящих условиях rus_verbs:царствовать{}, // царствовать в южной части материка rus_verbs:накопить{}, // накопить в буфере rus_verbs:закрутиться{}, // закрутиться в рутине rus_verbs:отработать{}, // отработать в забое rus_verbs:обокрасть{}, // обокрасть в автобусе rus_verbs:прокладывать{}, // прокладывать в снегу rus_verbs:ковырять{}, // ковырять в носу rus_verbs:копить{}, // копить в очереди rus_verbs:полечь{}, // полечь в степях rus_verbs:щебетать{}, // щебетать в кустиках rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении rus_verbs:посеять{}, // посеять в огороде rus_verbs:разъезжать{}, // разъезжать в кабриолете rus_verbs:замечаться{}, // замечаться в лесу rus_verbs:просчитать{}, // просчитать в уме rus_verbs:маяться{}, // маяться в командировке rus_verbs:выхватывать{}, // выхватывать в тексте rus_verbs:креститься{}, // креститься в деревенской часовне rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты rus_verbs:настигать{}, // настигать в огороде rus_verbs:разгуливать{}, // разгуливать в роще rus_verbs:насиловать{}, // насиловать в квартире rus_verbs:побороть{}, // побороть в себе rus_verbs:учитывать{}, // учитывать в расчетах rus_verbs:искажать{}, // искажать в заметке rus_verbs:пропить{}, // пропить в кабаке rus_verbs:катать{}, // катать в лодочке rus_verbs:припрятать{}, // припрятать в кармашке rus_verbs:запаниковать{}, // запаниковать в бою rus_verbs:рассыпать{}, // рассыпать в траве rus_verbs:застревать{}, // застревать в ограде rus_verbs:зажигаться{}, // зажигаться в сумерках rus_verbs:жарить{}, // жарить в масле rus_verbs:накапливаться{}, // накапливаться в костях rus_verbs:распуститься{}, // распуститься в горшке rus_verbs:проголосовать{}, // проголосовать в передвижном пункте rus_verbs:странствовать{}, // странствовать в автомобиле rus_verbs:осматриваться{}, // осматриваться в хоромах rus_verbs:разворачивать{}, // разворачивать в спортзале rus_verbs:заскучать{}, // заскучать в самолете rus_verbs:напутать{}, // напутать в расчете rus_verbs:перекусить{}, // перекусить в столовой rus_verbs:спасаться{}, // спасаться в автономной капсуле rus_verbs:посовещаться{}, // посовещаться в комнате rus_verbs:доказываться{}, // доказываться в статье rus_verbs:познаваться{}, // познаваться в беде rus_verbs:загрустить{}, // загрустить в одиночестве rus_verbs:оживить{}, // оживить в памяти rus_verbs:переворачиваться{}, // переворачиваться в гробу rus_verbs:заприметить{}, // заприметить в лесу rus_verbs:отравиться{}, // отравиться в забегаловке rus_verbs:продержать{}, // продержать в клетке rus_verbs:выявить{}, // выявить в костях rus_verbs:заседать{}, // заседать в совете rus_verbs:расплачиваться{}, // расплачиваться в первой кассе rus_verbs:проломить{}, // проломить в двери rus_verbs:подражать{}, // подражать в мелочах rus_verbs:подсчитывать{}, // подсчитывать в уме rus_verbs:опережать{}, // опережать во всем rus_verbs:сформироваться{}, // сформироваться в облаке rus_verbs:укрепиться{}, // укрепиться в мнении rus_verbs:отстоять{}, // отстоять в очереди rus_verbs:развертываться{}, // развертываться в месте испытания rus_verbs:замерзать{}, // замерзать во льду rus_verbs:утопать{}, // утопать в снегу rus_verbs:раскаиваться{}, // раскаиваться в содеянном rus_verbs:организовывать{}, // организовывать в пионерлагере rus_verbs:перевестись{}, // перевестись в наших краях rus_verbs:смешивать{}, // смешивать в блендере rus_verbs:ютиться{}, // ютиться в тесной каморке rus_verbs:прождать{}, // прождать в аудитории rus_verbs:подыскивать{}, // подыскивать в женском общежитии rus_verbs:замочить{}, // замочить в сортире rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке rus_verbs:растирать{}, // растирать в ступке rus_verbs:замедлять{}, // замедлять в парафине rus_verbs:переспать{}, // переспать в палатке rus_verbs:рассекать{}, // рассекать в кабриолете rus_verbs:отыскивать{}, // отыскивать в залежах rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке rus_verbs:укрываться{}, // укрываться в землянке rus_verbs:запечься{}, // запечься в золе rus_verbs:догорать{}, // догорать в темноте rus_verbs:застилать{}, // застилать в коридоре rus_verbs:сыскаться{}, // сыскаться в деревне rus_verbs:переделать{}, // переделать в мастерской rus_verbs:разъяснять{}, // разъяснять в своей лекции rus_verbs:селиться{}, // селиться в центре rus_verbs:оплачивать{}, // оплачивать в магазине rus_verbs:переворачивать{}, // переворачивать в закрытой банке rus_verbs:упражняться{}, // упражняться в остроумии rus_verbs:пометить{}, // пометить в списке rus_verbs:припомниться{}, // припомниться в завещании rus_verbs:приютить{}, // приютить в амбаре rus_verbs:натерпеться{}, // натерпеться в темнице rus_verbs:затеваться{}, // затеваться в клубе rus_verbs:уплывать{}, // уплывать в лодке rus_verbs:скиснуть{}, // скиснуть в бидоне rus_verbs:заколоть{}, // заколоть в боку rus_verbs:замерцать{}, // замерцать в темноте rus_verbs:фиксироваться{}, // фиксироваться в протоколе rus_verbs:запираться{}, // запираться в комнате rus_verbs:съезжаться{}, // съезжаться в каретах rus_verbs:толочься{}, // толочься в ступе rus_verbs:потанцевать{}, // потанцевать в клубе rus_verbs:побродить{}, // побродить в парке rus_verbs:назревать{}, // назревать в коллективе rus_verbs:дохнуть{}, // дохнуть в питомнике rus_verbs:крестить{}, // крестить в деревенской церквушке rus_verbs:рассчитаться{}, // рассчитаться в банке rus_verbs:припарковаться{}, // припарковаться во дворе rus_verbs:отхватить{}, // отхватить в магазинчике rus_verbs:остывать{}, // остывать в холодильнике rus_verbs:составляться{}, // составляться в атмосфере тайны rus_verbs:переваривать{}, // переваривать в тишине rus_verbs:хвастать{}, // хвастать в казино rus_verbs:отрабатывать{}, // отрабатывать в теплице rus_verbs:разлечься{}, // разлечься в кровати rus_verbs:прокручивать{}, // прокручивать в голове rus_verbs:очертить{}, // очертить в воздухе rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей rus_verbs:выявлять{}, // выявлять в боевых условиях rus_verbs:караулить{}, // караулить в лифте rus_verbs:расставлять{}, // расставлять в бойницах rus_verbs:прокрутить{}, // прокрутить в голове rus_verbs:пересказывать{}, // пересказывать в первой главе rus_verbs:задавить{}, // задавить в зародыше rus_verbs:хозяйничать{}, // хозяйничать в холодильнике rus_verbs:хвалиться{}, // хвалиться в детском садике rus_verbs:оперировать{}, // оперировать в полевом госпитале rus_verbs:формулировать{}, // формулировать в следующей главе rus_verbs:застигнуть{}, // застигнуть в неприглядном виде rus_verbs:замурлыкать{}, // замурлыкать в тепле rus_verbs:поддакивать{}, // поддакивать в споре rus_verbs:прочертить{}, // прочертить в воздухе rus_verbs:отменять{}, // отменять в городе коменданский час rus_verbs:колдовать{}, // колдовать в лаборатории rus_verbs:отвозить{}, // отвозить в машине rus_verbs:трахать{}, // трахать в гамаке rus_verbs:повозиться{}, // повозиться в мешке rus_verbs:ремонтировать{}, // ремонтировать в центре rus_verbs:робеть{}, // робеть в гостях rus_verbs:перепробовать{}, // перепробовать в деле инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш }, rus_verbs:покаяться{}, // покаяться в церкви rus_verbs:попрыгать{}, // попрыгать в бассейне rus_verbs:умалчивать{}, // умалчивать в своем докладе rus_verbs:ковыряться{}, // ковыряться в старой технике rus_verbs:расписывать{}, // расписывать в деталях rus_verbs:вязнуть{}, // вязнуть в песке rus_verbs:погрязнуть{}, // погрязнуть в скандалах rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу rus_verbs:зажимать{}, // зажимать в углу rus_verbs:стискивать{}, // стискивать в ладонях rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса rus_verbs:израсходовать{}, // израсходовать в полете rus_verbs:клокотать{}, // клокотать в жерле rus_verbs:обвиняться{}, // обвиняться в растрате rus_verbs:уединиться{}, // уединиться в кладовке rus_verbs:подохнуть{}, // подохнуть в болоте rus_verbs:кипятиться{}, // кипятиться в чайнике rus_verbs:уродиться{}, // уродиться в лесу rus_verbs:продолжиться{}, // продолжиться в баре rus_verbs:расшифровать{}, // расшифровать в специальном устройстве rus_verbs:посапывать{}, // посапывать в кровати rus_verbs:скрючиться{}, // скрючиться в мешке rus_verbs:лютовать{}, // лютовать в отдаленных селах rus_verbs:расписать{}, // расписать в статье rus_verbs:публиковаться{}, // публиковаться в научном журнале rus_verbs:зарегистрировать{}, // зарегистрировать в комитете rus_verbs:прожечь{}, // прожечь в листе rus_verbs:переждать{}, // переждать в окопе rus_verbs:публиковать{}, // публиковать в журнале rus_verbs:морщить{}, // морщить в уголках глаз rus_verbs:спиться{}, // спиться в одиночестве rus_verbs:изведать{}, // изведать в гареме rus_verbs:обмануться{}, // обмануться в ожиданиях rus_verbs:сочетать{}, // сочетать в себе rus_verbs:подрабатывать{}, // подрабатывать в магазине rus_verbs:репетировать{}, // репетировать в студии rus_verbs:рябить{}, // рябить в глазах rus_verbs:намочить{}, // намочить в луже rus_verbs:скатать{}, // скатать в руке rus_verbs:одевать{}, // одевать в магазине rus_verbs:испечь{}, // испечь в духовке rus_verbs:сбрить{}, // сбрить в подмышках rus_verbs:зажужжать{}, // зажужжать в ухе rus_verbs:сберечь{}, // сберечь в тайном месте rus_verbs:согреться{}, // согреться в хижине инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш }, rus_verbs:переплыть{}, // переплыть в лодочке rus_verbs:передохнуть{}, // передохнуть в тени rus_verbs:отсвечивать{}, // отсвечивать в зеркалах rus_verbs:переправляться{}, // переправляться в лодках rus_verbs:накупить{}, // накупить в магазине rus_verbs:проторчать{}, // проторчать в очереди rus_verbs:проскальзывать{}, // проскальзывать в сообщениях rus_verbs:застукать{}, // застукать в солярии rus_verbs:наесть{}, // наесть в отпуске rus_verbs:подвизаться{}, // подвизаться в новом деле rus_verbs:вычистить{}, // вычистить в саду rus_verbs:кормиться{}, // кормиться в лесу rus_verbs:покурить{}, // покурить в саду rus_verbs:понизиться{}, // понизиться в ранге rus_verbs:зимовать{}, // зимовать в избушке rus_verbs:проверяться{}, // проверяться в службе безопасности rus_verbs:подпирать{}, // подпирать в первом забое rus_verbs:кувыркаться{}, // кувыркаться в постели rus_verbs:похрапывать{}, // похрапывать в постели rus_verbs:завязнуть{}, // завязнуть в песке rus_verbs:трактовать{}, // трактовать в исследовательской статье rus_verbs:замедляться{}, // замедляться в тяжелой воде rus_verbs:шастать{}, // шастать в здании rus_verbs:заночевать{}, // заночевать в пути rus_verbs:наметиться{}, // наметиться в исследованиях рака rus_verbs:освежить{}, // освежить в памяти rus_verbs:оспаривать{}, // оспаривать в суде rus_verbs:умещаться{}, // умещаться в ячейке rus_verbs:искупить{}, // искупить в бою rus_verbs:отсиживаться{}, // отсиживаться в тылу rus_verbs:мчать{}, // мчать в кабриолете rus_verbs:обличать{}, // обличать в своем выступлении rus_verbs:сгнить{}, // сгнить в тюряге rus_verbs:опробовать{}, // опробовать в деле rus_verbs:тренировать{}, // тренировать в зале rus_verbs:прославить{}, // прославить в академии rus_verbs:учитываться{}, // учитываться в дипломной работе rus_verbs:повеселиться{}, // повеселиться в лагере rus_verbs:поумнеть{}, // поумнеть в карцере rus_verbs:перестрелять{}, // перестрелять в воздухе rus_verbs:проведать{}, // проведать в больнице rus_verbs:измучиться{}, // измучиться в деревне rus_verbs:прощупать{}, // прощупать в глубине rus_verbs:изготовлять{}, // изготовлять в сарае rus_verbs:свирепствовать{}, // свирепствовать в популяции rus_verbs:иссякать{}, // иссякать в источнике rus_verbs:гнездиться{}, // гнездиться в дупле rus_verbs:разогнаться{}, // разогнаться в спортивной машине rus_verbs:опознавать{}, // опознавать в неизвестном rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках rus_verbs:редактировать{}, // редактировать в редакторе rus_verbs:покупаться{}, // покупаться в магазине rus_verbs:промышлять{}, // промышлять в роще rus_verbs:растягиваться{}, // растягиваться в коридоре rus_verbs:приобретаться{}, // приобретаться в антикварных лавках инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш }, rus_verbs:запечатлеться{}, // запечатлеться в мозгу rus_verbs:укрывать{}, // укрывать в подвале rus_verbs:закрепиться{}, // закрепиться в первой башне rus_verbs:освежать{}, // освежать в памяти rus_verbs:громыхать{}, // громыхать в ванной инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш }, rus_verbs:добываться{}, // добываться в шахтах rus_verbs:растворить{}, // растворить в кислоте rus_verbs:приплясывать{}, // приплясывать в гримерке rus_verbs:доживать{}, // доживать в доме престарелых rus_verbs:отпраздновать{}, // отпраздновать в ресторане rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях rus_verbs:помыть{}, // помыть в проточной воде инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш }, прилагательное:увязавший{ вид:несоверш }, rus_verbs:наличествовать{}, // наличествовать в запаснике rus_verbs:нащупывать{}, // нащупывать в кармане rus_verbs:повествоваться{}, // повествоваться в рассказе rus_verbs:отремонтировать{}, // отремонтировать в техцентре rus_verbs:покалывать{}, // покалывать в правом боку rus_verbs:сиживать{}, // сиживать в саду rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях rus_verbs:укрепляться{}, // укрепляться в мнении rus_verbs:разниться{}, // разниться во взглядах rus_verbs:сполоснуть{}, // сполоснуть в водичке rus_verbs:скупать{}, // скупать в магазине rus_verbs:почесывать{}, // почесывать в паху rus_verbs:оформлять{}, // оформлять в конторе rus_verbs:распускаться{}, // распускаться в садах rus_verbs:зарябить{}, // зарябить в глазах rus_verbs:загореть{}, // загореть в Испании rus_verbs:очищаться{}, // очищаться в баке rus_verbs:остудить{}, // остудить в холодной воде rus_verbs:разбомбить{}, // разбомбить в горах rus_verbs:издохнуть{}, // издохнуть в бедности rus_verbs:проехаться{}, // проехаться в новой машине rus_verbs:задействовать{}, // задействовать в анализе rus_verbs:произрастать{}, // произрастать в степи rus_verbs:разуться{}, // разуться в прихожей rus_verbs:сооружать{}, // сооружать в огороде rus_verbs:зачитывать{}, // зачитывать в суде rus_verbs:состязаться{}, // состязаться в остроумии rus_verbs:ополоснуть{}, // ополоснуть в молоке rus_verbs:уместиться{}, // уместиться в кармане rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом rus_verbs:стираться{}, // стираться в стиральной машине rus_verbs:искупаться{}, // искупаться в прохладной реке rus_verbs:курировать{}, // курировать в правительстве rus_verbs:закупить{}, // закупить в магазине rus_verbs:плодиться{}, // плодиться в подходящих условиях rus_verbs:горланить{}, // горланить в парке rus_verbs:першить{}, // першить в горле rus_verbs:пригрезиться{}, // пригрезиться во сне rus_verbs:исправлять{}, // исправлять в тетрадке rus_verbs:расслабляться{}, // расслабляться в гамаке rus_verbs:скапливаться{}, // скапливаться в нижней части rus_verbs:сплетничать{}, // сплетничают в комнате rus_verbs:раздевать{}, // раздевать в кабинке rus_verbs:окопаться{}, // окопаться в лесу rus_verbs:загорать{}, // загорать в Испании rus_verbs:подпевать{}, // подпевать в церковном хоре rus_verbs:прожужжать{}, // прожужжать в динамике rus_verbs:изучаться{}, // изучаться в дикой природе rus_verbs:заклубиться{}, // заклубиться в воздухе rus_verbs:подметать{}, // подметать в зале rus_verbs:подозреваться{}, // подозреваться в совершении кражи rus_verbs:обогащать{}, // обогащать в специальном аппарате rus_verbs:издаться{}, // издаться в другом издательстве rus_verbs:справить{}, // справить в кустах нужду rus_verbs:помыться{}, // помыться в бане rus_verbs:проскакивать{}, // проскакивать в словах rus_verbs:попивать{}, // попивать в кафе чай rus_verbs:оформляться{}, // оформляться в регистратуре rus_verbs:чирикать{}, // чирикать в кустах rus_verbs:скупить{}, // скупить в магазинах rus_verbs:переночевать{}, // переночевать в гостинице rus_verbs:концентрироваться{}, // концентрироваться в пробирке rus_verbs:одичать{}, // одичать в лесу rus_verbs:ковырнуть{}, // ковырнуть в ухе rus_verbs:затеплиться{}, // затеплиться в глубине души rus_verbs:разгрести{}, // разгрести в задачах залежи rus_verbs:застопориться{}, // застопориться в начале списка rus_verbs:перечисляться{}, // перечисляться во введении rus_verbs:покататься{}, // покататься в парке аттракционов rus_verbs:изловить{}, // изловить в поле rus_verbs:прославлять{}, // прославлять в стихах rus_verbs:промочить{}, // промочить в луже rus_verbs:поделывать{}, // поделывать в отпуске rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии rus_verbs:подстеречь{}, // подстеречь в подъезде rus_verbs:прикупить{}, // прикупить в магазине rus_verbs:перемешивать{}, // перемешивать в кастрюле rus_verbs:тискать{}, // тискать в углу rus_verbs:купать{}, // купать в теплой водичке rus_verbs:завариться{}, // завариться в стакане rus_verbs:притулиться{}, // притулиться в углу rus_verbs:пострелять{}, // пострелять в тире rus_verbs:навесить{}, // навесить в больнице инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш }, rus_verbs:нежиться{}, // нежится в постельке rus_verbs:притомиться{}, // притомиться в школе rus_verbs:раздвоиться{}, // раздвоиться в глазах rus_verbs:навалить{}, // навалить в углу rus_verbs:замуровать{}, // замуровать в склепе rus_verbs:поселяться{}, // поселяться в кроне дуба rus_verbs:потягиваться{}, // потягиваться в кровати rus_verbs:укачать{}, // укачать в поезде rus_verbs:отлеживаться{}, // отлеживаться в гамаке rus_verbs:разменять{}, // разменять в кассе rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде rus_verbs:ржаветь{}, // ржаветь в воде rus_verbs:уличить{}, // уличить в плагиате rus_verbs:мутиться{}, // мутиться в голове rus_verbs:растворять{}, // растворять в бензоле rus_verbs:двоиться{}, // двоиться в глазах rus_verbs:оговорить{}, // оговорить в договоре rus_verbs:подделать{}, // подделать в документе rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети rus_verbs:растолстеть{}, // растолстеть в талии rus_verbs:повоевать{}, // повоевать в городских условиях rus_verbs:прибраться{}, // гнушаться прибраться в хлеву rus_verbs:поглощаться{}, // поглощаться в металлической фольге rus_verbs:ухать{}, // ухать в лесу rus_verbs:подписываться{}, // подписываться в петиции rus_verbs:покатать{}, // покатать в машинке rus_verbs:излечиться{}, // излечиться в клинике rus_verbs:трепыхаться{}, // трепыхаться в мешке rus_verbs:кипятить{}, // кипятить в кастрюле rus_verbs:понастроить{}, // понастроить в прибрежной зоне rus_verbs:перебывать{}, // перебывать во всех европейских столицах rus_verbs:оглашать{}, // оглашать в итоговой части rus_verbs:преуспевать{}, // преуспевать в новом бизнесе rus_verbs:консультироваться{}, // консультироваться в техподдержке rus_verbs:накапливать{}, // накапливать в печени rus_verbs:перемешать{}, // перемешать в контейнере rus_verbs:наследить{}, // наследить в коридоре rus_verbs:выявиться{}, // выявиться в результе rus_verbs:забулькать{}, // забулькать в болоте rus_verbs:отваривать{}, // отваривать в молоке rus_verbs:запутываться{}, // запутываться в веревках rus_verbs:нагреться{}, // нагреться в микроволновой печке rus_verbs:рыбачить{}, // рыбачить в открытом море rus_verbs:укорениться{}, // укорениться в сознании широких народных масс rus_verbs:умывать{}, // умывать в тазике rus_verbs:защекотать{}, // защекотать в носу rus_verbs:заходиться{}, // заходиться в плаче инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш }, деепричастие:искупав{}, деепричастие:искупая{}, rus_verbs:заморозить{}, // заморозить в холодильнике rus_verbs:закреплять{}, // закреплять в металлическом держателе rus_verbs:расхватать{}, // расхватать в магазине rus_verbs:истязать{}, // истязать в тюремном подвале rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете rus_verbs:подогреть{}, // подогрей в микроволновке rus_verbs:подогревать{}, rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку rus_verbs:проделать{}, // проделать в стене дыру инфинитив:жениться{ вид:соверш }, // жениться в Техасе инфинитив:жениться{ вид:несоверш }, глагол:жениться{ вид:соверш }, глагол:жениться{ вид:несоверш }, деепричастие:женившись{}, деепричастие:женясь{}, прилагательное:женатый{}, прилагательное:женившийся{вид:соверш}, прилагательное:женящийся{}, rus_verbs:всхрапнуть{}, // всхрапнуть во сне rus_verbs:всхрапывать{}, // всхрапывать во сне rus_verbs:ворочаться{}, // Собака ворочается во сне rus_verbs:воссоздаваться{}, // воссоздаваться в памяти rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу инфинитив:атаковать{ вид:соверш }, глагол:атаковать{ вид:несоверш }, глагол:атаковать{ вид:соверш }, прилагательное:атакованный{}, прилагательное:атаковавший{}, прилагательное:атакующий{}, инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени инфинитив:аккумулировать{вид:соверш}, глагол:аккумулировать{вид:несоверш}, глагол:аккумулировать{вид:соверш}, прилагательное:аккумулированный{}, прилагательное:аккумулирующий{}, //прилагательное:аккумулировавший{ вид:несоверш }, прилагательное:аккумулировавший{ вид:соверш }, rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию rus_verbs:вырасти{}, // Он вырос в глазах коллег. rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо. rus_verbs:убить{}, // убить в себе зверя инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани инфинитив:абсорбироваться{ вид:несоверш }, глагол:абсорбироваться{ вид:соверш }, глагол:абсорбироваться{ вид:несоверш }, rus_verbs:поставить{}, // поставить в углу rus_verbs:сжимать{}, // сжимать в кулаке rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы инфинитив:активизироваться{ вид:соверш }, глагол:активизироваться{ вид:несоверш }, глагол:активизироваться{ вид:соверш }, rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе rus_verbs:базировать{}, // установка будет базирована в лесу rus_verbs:барахтаться{}, // дети барахтались в воде rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины rus_verbs:блуждать{}, // Туристы блуждали в лесу rus_verbs:брать{}, // Жена берет деньги в тумбочке rus_verbs:бродить{}, // парочки бродили в парке rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде rus_verbs:вариться{}, // Курица варится в кастрюле rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году rus_verbs:прокручиваться{}, // Ключ прокручивается в замке rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке rus_verbs:храниться{}, // Настройки хранятся в текстовом файле rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле rus_verbs:витать{}, // Мальчик витает в облаках rus_verbs:владычествовать{}, // Король владычествует в стране rus_verbs:властвовать{}, // Олигархи властвовали в стране rus_verbs:возбудить{}, // возбудить в сердце тоску rus_verbs:возбуждать{}, // возбуждать в сердце тоску rus_verbs:возвыситься{}, // возвыситься в глазах современников rus_verbs:возжечь{}, // возжечь в храме огонь rus_verbs:возжечься{}, // Огонь возжёгся в храме rus_verbs:возжигать{}, // возжигать в храме огонь rus_verbs:возжигаться{}, // Огонь возжигается в храме rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь rus_verbs:вознамериться{}, // вознамериться уйти в монастырь rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове rus_verbs:возникнуть{}, // Новые идейки возникли в голове rus_verbs:возродиться{}, // возродиться в новом качестве rus_verbs:возрождать{}, // возрождать в новом качестве rus_verbs:возрождаться{}, // возрождаться в новом амплуа rus_verbs:ворошить{}, // ворошить в камине кочергой золу rus_verbs:воспевать{}, // Поэты воспевают героев в одах rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами rus_verbs:воспеть{}, // Поэты воспели в этой оде героев rus_verbs:воспретить{}, // воспретить в помещении азартные игры rus_verbs:восславить{}, // Поэты восславили в одах rus_verbs:восславлять{}, // Поэты восславляют в одах rus_verbs:восславляться{}, // Героя восславляются в одах rus_verbs:воссоздать{}, // воссоздает в памяти образ человека rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека rus_verbs:воссоздаться{}, // воссоздаться в памяти rus_verbs:вскипятить{}, // вскипятить в чайнике воду rus_verbs:вскипятиться{}, // вскипятиться в чайнике rus_verbs:встретить{}, // встретить в классе старого приятеля rus_verbs:встретиться{}, // встретиться в классе rus_verbs:встречать{}, // встречать в лесу голодного медведя rus_verbs:встречаться{}, // встречаться в кафе rus_verbs:выбривать{}, // выбривать что-то в подмышках rus_verbs:выбрить{}, // выбрить что-то в паху rus_verbs:вывалять{}, // вывалять кого-то в грязи rus_verbs:вываляться{}, // вываляться в грязи rus_verbs:вываривать{}, // вываривать в молоке rus_verbs:вывариваться{}, // вывариваться в молоке rus_verbs:выварить{}, // выварить в молоке rus_verbs:вывариться{}, // вывариться в молоке rus_verbs:выгрызать{}, // выгрызать в сыре отверствие rus_verbs:выгрызть{}, // выгрызть в сыре отверстие rus_verbs:выгуливать{}, // выгуливать в парке собаку rus_verbs:выгулять{}, // выгулять в парке собаку rus_verbs:выдолбить{}, // выдолбить в стволе углубление rus_verbs:выжить{}, // выжить в пустыне rus_verbs:Выискать{}, // Выискать в программе ошибку rus_verbs:выискаться{}, // Ошибка выискалась в программе rus_verbs:выискивать{}, // выискивать в программе ошибку rus_verbs:выискиваться{}, // выискиваться в программе rus_verbs:выкраивать{}, // выкраивать в расписании время rus_verbs:выкраиваться{}, // выкраиваться в расписании инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере глагол:выкупаться{вид:соверш}, rus_verbs:выловить{}, // выловить в пруду rus_verbs:вымачивать{}, // вымачивать в молоке rus_verbs:вымачиваться{}, // вымачиваться в молоке rus_verbs:вынюхивать{}, // вынюхивать в траве следы rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду rus_verbs:выпачкаться{}, // выпачкаться в грязи rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков rus_verbs:выращивать{}, // выращивать в теплице помидоры rus_verbs:выращиваться{}, // выращиваться в теплице rus_verbs:вырыть{}, // вырыть в земле глубокую яму rus_verbs:высадить{}, // высадить в пустынной местности rus_verbs:высадиться{}, // высадиться в пустынной местности rus_verbs:высаживать{}, // высаживать в пустыне rus_verbs:высверливать{}, // высверливать в доске отверствие rus_verbs:высверливаться{}, // высверливаться в стене rus_verbs:высверлить{}, // высверлить в стене отверствие rus_verbs:высверлиться{}, // высверлиться в стене rus_verbs:выскоблить{}, // выскоблить в столешнице канавку rus_verbs:высматривать{}, // высматривать в темноте rus_verbs:заметить{}, // заметить в помещении rus_verbs:оказаться{}, // оказаться в первых рядах rus_verbs:душить{}, // душить в объятиях rus_verbs:оставаться{}, // оставаться в классе rus_verbs:появиться{}, // впервые появиться в фильме rus_verbs:лежать{}, // лежать в футляре rus_verbs:раздаться{}, // раздаться в плечах rus_verbs:ждать{}, // ждать в здании вокзала rus_verbs:жить{}, // жить в трущобах rus_verbs:постелить{}, // постелить в прихожей rus_verbs:оказываться{}, // оказываться в неприятной ситуации rus_verbs:держать{}, // держать в голове rus_verbs:обнаружить{}, // обнаружить в себе способность rus_verbs:начинать{}, // начинать в лаборатории rus_verbs:рассказывать{}, // рассказывать в лицах rus_verbs:ожидать{}, // ожидать в помещении rus_verbs:продолжить{}, // продолжить в помещении rus_verbs:состоять{}, // состоять в группе rus_verbs:родиться{}, // родиться в рубашке rus_verbs:искать{}, // искать в кармане rus_verbs:иметься{}, // иметься в наличии rus_verbs:говориться{}, // говориться в среде панков rus_verbs:клясться{}, // клясться в верности rus_verbs:узнавать{}, // узнавать в нем своего сына rus_verbs:признаться{}, // признаться в ошибке rus_verbs:сомневаться{}, // сомневаться в искренности rus_verbs:толочь{}, // толочь в ступе rus_verbs:понадобиться{}, // понадобиться в суде rus_verbs:служить{}, // служить в пехоте rus_verbs:потолочь{}, // потолочь в ступе rus_verbs:появляться{}, // появляться в театре rus_verbs:сжать{}, // сжать в объятиях rus_verbs:действовать{}, // действовать в постановке rus_verbs:селить{}, // селить в гостинице rus_verbs:поймать{}, // поймать в лесу rus_verbs:увидать{}, // увидать в толпе rus_verbs:подождать{}, // подождать в кабинете rus_verbs:прочесть{}, // прочесть в глазах rus_verbs:тонуть{}, // тонуть в реке rus_verbs:ощущать{}, // ощущать в животе rus_verbs:ошибиться{}, // ошибиться в расчетах rus_verbs:отметить{}, // отметить в списке rus_verbs:показывать{}, // показывать в динамике rus_verbs:скрыться{}, // скрыться в траве rus_verbs:убедиться{}, // убедиться в корректности rus_verbs:прозвучать{}, // прозвучать в наушниках rus_verbs:разговаривать{}, // разговаривать в фойе rus_verbs:издать{}, // издать в России rus_verbs:прочитать{}, // прочитать в газете rus_verbs:попробовать{}, // попробовать в деле rus_verbs:замечать{}, // замечать в программе ошибку rus_verbs:нести{}, // нести в руках rus_verbs:пропасть{}, // пропасть в плену rus_verbs:носить{}, // носить в кармане rus_verbs:гореть{}, // гореть в аду rus_verbs:поправить{}, // поправить в программе rus_verbs:застыть{}, // застыть в неудобной позе rus_verbs:получать{}, // получать в кассе rus_verbs:потребоваться{}, // потребоваться в работе rus_verbs:спрятать{}, // спрятать в шкафу rus_verbs:учиться{}, // учиться в институте rus_verbs:развернуться{}, // развернуться в коридоре rus_verbs:подозревать{}, // подозревать в мошенничестве rus_verbs:играть{}, // играть в команде rus_verbs:сыграть{}, // сыграть в команде rus_verbs:строить{}, // строить в деревне rus_verbs:устроить{}, // устроить в доме вечеринку rus_verbs:находить{}, // находить в лесу rus_verbs:нуждаться{}, // нуждаться в деньгах rus_verbs:испытать{}, // испытать в рабочей обстановке rus_verbs:мелькнуть{}, // мелькнуть в прицеле rus_verbs:очутиться{}, // очутиться в закрытом помещении инфинитив:использовать{вид:соверш}, // использовать в работе инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, глагол:использовать{вид:соверш}, rus_verbs:лететь{}, // лететь в самолете rus_verbs:смеяться{}, // смеяться в цирке rus_verbs:ездить{}, // ездить в лимузине rus_verbs:заснуть{}, // заснуть в неудобной позе rus_verbs:застать{}, // застать в неформальной обстановке rus_verbs:очнуться{}, // очнуться в незнакомой обстановке rus_verbs:твориться{}, // Что творится в закрытой зоне rus_verbs:разглядеть{}, // разглядеть в темноте rus_verbs:изучать{}, // изучать в естественных условиях rus_verbs:удержаться{}, // удержаться в седле rus_verbs:побывать{}, // побывать в зоопарке rus_verbs:уловить{}, // уловить в словах нотку отчаяния rus_verbs:приобрести{}, // приобрести в лавке rus_verbs:исчезать{}, // исчезать в тумане rus_verbs:уверять{}, // уверять в своей невиновности rus_verbs:продолжаться{}, // продолжаться в воздухе rus_verbs:открывать{}, // открывать в городе новый стадион rus_verbs:поддержать{}, // поддержать в парке порядок rus_verbs:солить{}, // солить в бочке rus_verbs:прожить{}, // прожить в деревне rus_verbs:создавать{}, // создавать в театре rus_verbs:обсуждать{}, // обсуждать в коллективе rus_verbs:заказать{}, // заказать в магазине rus_verbs:отыскать{}, // отыскать в гараже rus_verbs:уснуть{}, // уснуть в кресле rus_verbs:задержаться{}, // задержаться в театре rus_verbs:подобрать{}, // подобрать в коллекции rus_verbs:пробовать{}, // пробовать в работе rus_verbs:курить{}, // курить в закрытом помещении rus_verbs:устраивать{}, // устраивать в лесу засаду rus_verbs:установить{}, // установить в багажнике rus_verbs:запереть{}, // запереть в сарае rus_verbs:содержать{}, // содержать в достатке rus_verbs:синеть{}, // синеть в кислородной атмосфере rus_verbs:слышаться{}, // слышаться в голосе rus_verbs:закрыться{}, // закрыться в здании rus_verbs:скрываться{}, // скрываться в квартире rus_verbs:родить{}, // родить в больнице rus_verbs:описать{}, // описать в заметках rus_verbs:перехватить{}, // перехватить в коридоре rus_verbs:менять{}, // менять в магазине rus_verbs:скрывать{}, // скрывать в чужой квартире rus_verbs:стиснуть{}, // стиснуть в стальных объятиях rus_verbs:останавливаться{}, // останавливаться в гостинице rus_verbs:мелькать{}, // мелькать в телевизоре rus_verbs:присутствовать{}, // присутствовать в аудитории rus_verbs:украсть{}, // украсть в магазине rus_verbs:победить{}, // победить в войне rus_verbs:расположиться{}, // расположиться в гостинице rus_verbs:упомянуть{}, // упомянуть в своей книге rus_verbs:плыть{}, // плыть в старой бочке rus_verbs:нащупать{}, // нащупать в глубине rus_verbs:проявляться{}, // проявляться в работе rus_verbs:затихнуть{}, // затихнуть в норе rus_verbs:построить{}, // построить в гараже rus_verbs:поддерживать{}, // поддерживать в исправном состоянии rus_verbs:заработать{}, // заработать в стартапе rus_verbs:сломать{}, // сломать в суставе rus_verbs:снимать{}, // снимать в гардеробе rus_verbs:сохранить{}, // сохранить в коллекции rus_verbs:располагаться{}, // располагаться в отдельном кабинете rus_verbs:сражаться{}, // сражаться в честном бою rus_verbs:спускаться{}, // спускаться в батискафе rus_verbs:уничтожить{}, // уничтожить в схроне rus_verbs:изучить{}, // изучить в естественных условиях rus_verbs:рождаться{}, // рождаться в муках rus_verbs:пребывать{}, // пребывать в прострации rus_verbs:прилететь{}, // прилететь в аэробусе rus_verbs:догнать{}, // догнать в переулке rus_verbs:изобразить{}, // изобразить в танце rus_verbs:проехать{}, // проехать в легковушке rus_verbs:убедить{}, // убедить в разумности rus_verbs:приготовить{}, // приготовить в духовке rus_verbs:собирать{}, // собирать в лесу rus_verbs:поплыть{}, // поплыть в катере rus_verbs:доверять{}, // доверять в управлении rus_verbs:разобраться{}, // разобраться в законах rus_verbs:ловить{}, // ловить в озере rus_verbs:проесть{}, // проесть в куске металла отверстие rus_verbs:спрятаться{}, // спрятаться в подвале rus_verbs:провозгласить{}, // провозгласить в речи rus_verbs:изложить{}, // изложить в своём выступлении rus_verbs:замяться{}, // замяться в коридоре rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна rus_verbs:хранить{}, // хранить в шкатулке rus_verbs:шутить{}, // шутить в классе глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях инфинитив:рассыпаться{ aux stress="рассып^аться" }, rus_verbs:чертить{}, // чертить в тетрадке rus_verbs:отразиться{}, // отразиться в аттестате rus_verbs:греть{}, // греть в микроволновке rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса rus_verbs:рассуждать{}, // Автор рассуждает в своей статье rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда rus_verbs:окружать{}, // окружать в лесу rus_verbs:сопровождать{}, // сопровождать в операции rus_verbs:заканчиваться{}, // заканчиваться в дороге rus_verbs:поселиться{}, // поселиться в загородном доме rus_verbs:охватывать{}, // охватывать в хронологии rus_verbs:запеть{}, // запеть в кино инфинитив:провозить{вид:несоверш}, // провозить в багаже глагол:провозить{вид:несоверш}, rus_verbs:мочить{}, // мочить в сортире rus_verbs:перевернуться{}, // перевернуться в полёте rus_verbs:улететь{}, // улететь в теплые края rus_verbs:сдержать{}, // сдержать в руках rus_verbs:преследовать{}, // преследовать в любой другой стране rus_verbs:драться{}, // драться в баре rus_verbs:просидеть{}, // просидеть в классе rus_verbs:убираться{}, // убираться в квартире rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения rus_verbs:пугать{}, // пугать в прессе rus_verbs:отреагировать{}, // отреагировать в прессе rus_verbs:проверять{}, // проверять в аппарате rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив rus_verbs:летать{}, // летать в комфортабельном частном самолёте rus_verbs:толпиться{}, // толпиться в фойе rus_verbs:плавать{}, // плавать в специальном костюме rus_verbs:пробыть{}, // пробыть в воде слишком долго rus_verbs:прикинуть{}, // прикинуть в уме rus_verbs:застрять{}, // застрять в лифте rus_verbs:метаться{}, // метаться в кровате rus_verbs:сжечь{}, // сжечь в печке rus_verbs:расслабиться{}, // расслабиться в ванной rus_verbs:услыхать{}, // услыхать в автобусе rus_verbs:удержать{}, // удержать в вертикальном положении rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы rus_verbs:рассмотреть{}, // рассмотреть в капле воды rus_verbs:просмотреть{}, // просмотреть в браузере rus_verbs:учесть{}, // учесть в планах rus_verbs:уезжать{}, // уезжать в чьей-то машине rus_verbs:похоронить{}, // похоронить в мерзлой земле rus_verbs:растянуться{}, // растянуться в расслабленной позе rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке rus_verbs:гулять{}, // гулять в парке rus_verbs:утонуть{}, // утонуть в реке rus_verbs:зажать{}, // зажать в медвежьих объятиях rus_verbs:усомниться{}, // усомниться в объективности rus_verbs:танцевать{}, // танцевать в спортзале rus_verbs:проноситься{}, // проноситься в голове rus_verbs:трудиться{}, // трудиться в кооперативе глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный }, rus_verbs:сушить{}, // сушить в сушильном шкафу rus_verbs:зашевелиться{}, // зашевелиться в траве rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке rus_verbs:промелькнуть{}, // промелькнуть в окне rus_verbs:поучаствовать{}, // поучаствовать в обсуждении rus_verbs:закрыть{}, // закрыть в комнате rus_verbs:запирать{}, // запирать в комнате rus_verbs:закрывать{}, // закрывать в доме rus_verbs:заблокировать{}, // заблокировать в доме rus_verbs:зацвести{}, // В садах зацвела сирень rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу. rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе rus_verbs:стоять{}, // войска, стоявшие в Риме rus_verbs:закалить{}, // ветераны, закаленные в боях rus_verbs:выступать{}, // пришлось выступать в тюрьме. rus_verbs:выступить{}, // пришлось выступить в тюрьме. rus_verbs:закопошиться{}, // Мыши закопошились в траве rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре rus_verbs:закрываться{}, // закрываться в комнате rus_verbs:провалиться{}, // провалиться в прокате деепричастие:авторизируясь{ вид:несоверш }, глагол:авторизироваться{ вид:несоверш }, инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе rus_verbs:существовать{}, // существовать в вакууме деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, // находиться в вакууме rus_verbs:регистрировать{}, // регистрировать в инспекции глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш }, инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции rus_verbs:поковыряться{}, // поковыряться в носу rus_verbs:оттаять{}, // оттаять в кипятке rus_verbs:распинаться{}, // распинаться в проклятиях rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения. прилагательное:несчастный{}, // Он очень несчастен в семейной жизни. rus_verbs:объясниться{}, // Он объяснился в любви. прилагательное:нетвердый{}, // Он нетвёрд в истории. rus_verbs:заниматься{}, // Он занимается в читальном зале. rus_verbs:вращаться{}, // Он вращается в учёных кругах. прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне. rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры. rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения. rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев. rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях. rus_verbs:продолжать{}, // Продолжайте в том же духе. rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:болтать{}, // Не болтай в присутствии начальника! rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника! rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине. rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах rus_verbs:сходиться{}, // Все дороги сходятся в Москве rus_verbs:убирать{}, // убирать в комнате rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста rus_verbs:уединяться{}, // уединяться в пустыне rus_verbs:уживаться{}, // уживаться в одном коллективе rus_verbs:укорять{}, // укорять друга в забывчивости rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем rus_verbs:работать{}, // Я работаю в театре. rus_verbs:признать{}, // Я признал в нём старого друга. rus_verbs:преподавать{}, // Я преподаю в университете. rus_verbs:понимать{}, // Я плохо понимаю в живописи. rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа rus_verbs:замереть{}, // вся толпа замерла в восхищении rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле. rus_verbs:идти{}, // Я иду в неопределённом направлении. rus_verbs:заболеть{}, // Я заболел в дороге. rus_verbs:ехать{}, // Я еду в автобусе rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю. rus_verbs:провести{}, // Юные годы он провёл в Италии. rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти. rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении. rus_verbs:произойти{}, // Это произошло в одном городе в Японии. rus_verbs:привидеться{}, // Это мне привиделось во сне. rus_verbs:держаться{}, // Это дело держится в большом секрете. rus_verbs:привиться{}, // Это выражение не привилось в русском языке. rus_verbs:восстановиться{}, // Эти писатели восстановились в правах. rus_verbs:быть{}, // Эта книга есть в любом книжном магазине. прилагательное:популярный{}, // Эта идея очень популярна в массах. rus_verbs:шуметь{}, // Шумит в голове. rus_verbs:остаться{}, // Шляпа осталась в поезде. rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях. rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе. rus_verbs:пересохнуть{}, // У меня в горле пересохло. rus_verbs:щекотать{}, // У меня в горле щекочет. rus_verbs:колоть{}, // У меня в боку колет. прилагательное:свежий{}, // Событие ещё свежо в памяти. rus_verbs:собрать{}, // Соберите всех учеников во дворе. rus_verbs:белеть{}, // Снег белеет в горах. rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте? rus_verbs:таять{}, // Сахар тает в кипятке. rus_verbs:жать{}, // Сапог жмёт в подъёме. rus_verbs:возиться{}, // Ребята возятся в углу. rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме. rus_verbs:кружиться{}, // Они кружились в вальсе. rus_verbs:выставлять{}, // Они выставляют его в смешном виде. rus_verbs:бывать{}, // Она часто бывает в обществе. rus_verbs:петь{}, // Она поёт в опере. rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях. rus_verbs:валяться{}, // Вещи валялись в беспорядке. rus_verbs:пройти{}, // Весь день прошёл в беготне. rus_verbs:продавать{}, // В этом магазине продают обувь. rus_verbs:заключаться{}, // В этом заключается вся сущность. rus_verbs:звенеть{}, // В ушах звенит. rus_verbs:проступить{}, // В тумане проступили очертания корабля. rus_verbs:бить{}, // В саду бьёт фонтан. rus_verbs:проскользнуть{}, // В речи проскользнул упрёк. rus_verbs:оставить{}, // Не оставь товарища в опасности. rus_verbs:прогулять{}, // Мы прогуляли час в парке. rus_verbs:перебить{}, // Мы перебили врагов в бою. rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице. rus_verbs:видеть{}, // Он многое видел в жизни. // глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере. rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах. rus_verbs:кинуть{}, // Он кинул меня в беде. rus_verbs:приходить{}, // Приходи в сентябре rus_verbs:воскрешать{}, // воскрешать в памяти rus_verbs:соединять{}, // соединять в себе rus_verbs:разбираться{}, // умение разбираться в вещах rus_verbs:делать{}, // В её комнате делали обыск. rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина. rus_verbs:начаться{}, // В деревне начались полевые работы. rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль. rus_verbs:вертеться{}, // В голове вертится вчерашний разговор. rus_verbs:веять{}, // В воздухе веет прохладой. rus_verbs:висеть{}, // В воздухе висит зной. rus_verbs:носиться{}, // В воздухе носятся комары. rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее rus_verbs:воскресить{}, // воскресить в памяти rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина прилагательное:уверенный{ причастие }, // Она уверена в своих силах. прилагательное:постоянный{}, // Она постоянна во вкусах. прилагательное:сильный{}, // Он не силён в математике. прилагательное:повинный{}, // Он не повинен в этом. прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве. rus_verbs:сесть{}, // Она села в тени rus_verbs:заливаться{}, // в нашем парке заливаются соловьи rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени // rus_verbs:расти{}, // дерево, растущее в лесу rus_verbs:происходить{}, // что происходит в поликлиннике rus_verbs:спать{}, // кто спит в моей кровати rus_verbs:мыть{}, // мыть машину в саду ГЛ_ИНФ(царить), // В воздухе царило безмолвие ГЛ_ИНФ(мести), // мести в прихожей пол ГЛ_ИНФ(прятать), // прятать в яме ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне. // ГЛ_ИНФ(собраться), // собраться в порту ГЛ_ИНФ(случиться), // что-то случилось в больнице ГЛ_ИНФ(зажечься), // в небе зажглись звёзды ГЛ_ИНФ(купить), // купи молока в магазине прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР } // Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds fact гл_предл { if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } } then return true } // С локативом: // собраться в порту fact гл_предл { if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } } then return true } #endregion Предложный #region Винительный // Для глаголов движения с выраженным направлением действия может присоединяться // предложный паттерн с винительным падежом. wordentry_set Гл_В_Вин = { rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок. глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе. глагол:ввергать{}, инфинитив:ввергнуть{}, инфинитив:ввергать{}, rus_verbs:двинуться{}, // Двинулись в путь и мы. rus_verbs:сплавать{}, // Сплавать в Россию! rus_verbs:уложиться{}, // Уложиться в воскресенье. rus_verbs:спешить{}, // Спешите в Лондон rus_verbs:кинуть{}, // Киньте в море. rus_verbs:проситься{}, // Просилась в Никарагуа. rus_verbs:притопать{}, // Притопал в Будапешт. rus_verbs:скататься{}, // Скатался в Красноярск. rus_verbs:соскользнуть{}, // Соскользнул в пике. rus_verbs:соскальзывать{}, rus_verbs:играть{}, // Играл в дутье. глагол:айда{}, // Айда в каморы. rus_verbs:отзывать{}, // Отзывали в Москву... rus_verbs:сообщаться{}, // Сообщается в Лондон. rus_verbs:вдуматься{}, // Вдумайтесь в них. rus_verbs:проехать{}, // Проехать в Лунево... rus_verbs:спрыгивать{}, // Спрыгиваем в него. rus_verbs:верить{}, // Верю в вас! rus_verbs:прибыть{}, // Прибыл в Подмосковье. rus_verbs:переходить{}, // Переходите в школу. rus_verbs:доложить{}, // Доложили в Москву. rus_verbs:подаваться{}, // Подаваться в Россию? rus_verbs:спрыгнуть{}, // Спрыгнул в него. rus_verbs:вывезти{}, // Вывезли в Китай. rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю. rus_verbs:пропихнуть{}, rus_verbs:транспортироваться{}, rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения rus_verbs:дуть{}, rus_verbs:БОГАТЕТЬ{}, // rus_verbs:РАЗБОГАТЕТЬ{}, // rus_verbs:ВОЗРАСТАТЬ{}, // rus_verbs:ВОЗРАСТИ{}, // rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ) rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ) rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ) rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ) rus_verbs:ЗАМАНИВАТЬ{}, rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ) rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ) rus_verbs:ВРУБАТЬСЯ{}, rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ) rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ) rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ) rus_verbs:ЗАХВАТЫВАТЬ{}, rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ) rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ) rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ) rus_verbs:ПОСТРОИТЬСЯ{}, rus_verbs:ВЫСТРОИТЬСЯ{}, rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ) rus_verbs:ВЫПУСКАТЬ{}, rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ) rus_verbs:ВЦЕПИТЬСЯ{}, rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ) rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ) rus_verbs:ОТСТУПАТЬ{}, rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ) rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ) rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ) rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ) rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ) rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ) rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин) rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ) rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ) rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ) rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ) rus_verbs:СЖИМАТЬСЯ{}, rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ) rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ) rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ) rus_verbs:ПОКРАСИТЬ{}, // rus_verbs:ПЕРЕКРАСИТЬ{}, // rus_verbs:ОКРАСИТЬ{}, // rus_verbs:ЗАКРАСИТЬ{}, // rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ) rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ) rus_verbs:СТЯНУТЬ{}, // rus_verbs:ЗАТЯНУТЬ{}, // rus_verbs:ВТЯНУТЬ{}, // rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ) деепричастие:придя{}, // Немного придя в себя rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ) rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ) rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ) rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ) rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ) rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ) rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин) rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин) rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин) rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин) rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин) rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин) rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин) rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В) rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В) rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В) rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В) rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин) rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В) rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В) rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин) rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В) rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В) rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В) rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В) rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В) rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В) rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В) rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В) rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В) rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны. rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В) rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям. rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В) rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в) rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В) rus_verbs:валить{}, // валить все в одну кучу (валить в) rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в) rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в) rus_verbs:клониться{}, // он клонился в сторону (клониться в) rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в) rus_verbs:запасть{}, // Эти слова запали мне в душу. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:ездить{}, // Каждый день грузовик ездит в город. rus_verbs:претвориться{}, // Замысел претворился в жизнь. rus_verbs:разойтись{}, // Они разошлись в разные стороны. rus_verbs:выйти{}, // Охотник вышел в поле с ружьём. rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом. rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны rus_verbs:переодеваться{}, // переодеваться в женское платье rus_verbs:перерастать{}, // перерастать в массовые беспорядки rus_verbs:завязываться{}, // завязываться в узел rus_verbs:похватать{}, // похватать в руки rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:помещать{}, // помещать в изолятор rus_verbs:зыркнуть{}, // зыркнуть в окошко rus_verbs:закатать{}, // закатать в асфальт rus_verbs:усаживаться{}, // усаживаться в кресло rus_verbs:загонять{}, // загонять в сарай rus_verbs:подбрасывать{}, // подбрасывать в воздух rus_verbs:телеграфировать{}, // телеграфировать в центр rus_verbs:вязать{}, // вязать в стопы rus_verbs:подлить{}, // подлить в огонь rus_verbs:заполучить{}, // заполучить в распоряжение rus_verbs:подогнать{}, // подогнать в док rus_verbs:ломиться{}, // ломиться в открытую дверь rus_verbs:переправить{}, // переправить в деревню rus_verbs:затягиваться{}, // затягиваться в трубу rus_verbs:разлетаться{}, // разлетаться в стороны rus_verbs:кланяться{}, // кланяться в ножки rus_verbs:устремляться{}, // устремляться в открытое море rus_verbs:переместиться{}, // переместиться в другую аудиторию rus_verbs:ложить{}, // ложить в ящик rus_verbs:отвозить{}, // отвозить в аэропорт rus_verbs:напрашиваться{}, // напрашиваться в гости rus_verbs:напроситься{}, // напроситься в гости rus_verbs:нагрянуть{}, // нагрянуть в гости rus_verbs:заворачивать{}, // заворачивать в фольгу rus_verbs:заковать{}, // заковать в кандалы rus_verbs:свезти{}, // свезти в сарай rus_verbs:притащиться{}, // притащиться в дом rus_verbs:завербовать{}, // завербовать в разведку rus_verbs:рубиться{}, // рубиться в компьютерные игры rus_verbs:тыкаться{}, // тыкаться в материнскую грудь инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш }, деепричастие:ссыпав{}, деепричастие:ссыпая{}, rus_verbs:засасывать{}, // засасывать в себя rus_verbs:скакнуть{}, // скакнуть в будущее rus_verbs:подвозить{}, // подвозить в театр rus_verbs:переиграть{}, // переиграть в покер rus_verbs:мобилизовать{}, // мобилизовать в действующую армию rus_verbs:залетать{}, // залетать в закрытое воздушное пространство rus_verbs:подышать{}, // подышать в трубочку rus_verbs:смотаться{}, // смотаться в институт rus_verbs:рассовать{}, // рассовать в кармашки rus_verbs:захаживать{}, // захаживать в дом инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард деепричастие:сгоняя{}, rus_verbs:посылаться{}, // посылаться в порт rus_verbs:отлить{}, // отлить в кастрюлю rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение rus_verbs:поплакать{}, // поплакать в платочек rus_verbs:обуться{}, // обуться в сапоги rus_verbs:закапать{}, // закапать в глаза инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш }, деепричастие:свозив{}, деепричастие:свозя{}, rus_verbs:преобразовать{}, // преобразовать в линейное уравнение rus_verbs:кутаться{}, // кутаться в плед rus_verbs:смещаться{}, // смещаться в сторону rus_verbs:зазывать{}, // зазывать в свой магазин инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш }, деепричастие:трансформируясь{}, деепричастие:трансформировавшись{}, rus_verbs:погружать{}, // погружать в кипящее масло rus_verbs:обыграть{}, // обыграть в теннис rus_verbs:закутать{}, // закутать в одеяло rus_verbs:изливаться{}, // изливаться в воду rus_verbs:закатывать{}, // закатывать в асфальт rus_verbs:мотнуться{}, // мотнуться в банк rus_verbs:избираться{}, // избираться в сенат rus_verbs:наниматься{}, // наниматься в услужение rus_verbs:настучать{}, // настучать в органы rus_verbs:запихивать{}, // запихивать в печку rus_verbs:закапывать{}, // закапывать в нос rus_verbs:засобираться{}, // засобираться в поход rus_verbs:копировать{}, // копировать в другую папку rus_verbs:замуровать{}, // замуровать в стену rus_verbs:упечь{}, // упечь в тюрьму rus_verbs:зрить{}, // зрить в корень rus_verbs:стягиваться{}, // стягиваться в одну точку rus_verbs:усаживать{}, // усаживать в тренажер rus_verbs:протолкнуть{}, // протолкнуть в отверстие rus_verbs:расшибиться{}, // расшибиться в лепешку rus_verbs:приглашаться{}, // приглашаться в кабинет rus_verbs:садить{}, // садить в телегу rus_verbs:уткнуть{}, // уткнуть в подушку rus_verbs:протечь{}, // протечь в подвал rus_verbs:перегнать{}, // перегнать в другую страну rus_verbs:переползти{}, // переползти в тень rus_verbs:зарываться{}, // зарываться в грунт rus_verbs:переодеть{}, // переодеть в сухую одежду rus_verbs:припуститься{}, // припуститься в пляс rus_verbs:лопотать{}, // лопотать в микрофон rus_verbs:прогнусавить{}, // прогнусавить в микрофон rus_verbs:мочиться{}, // мочиться в штаны rus_verbs:загружать{}, // загружать в патронник rus_verbs:радировать{}, // радировать в центр rus_verbs:промотать{}, // промотать в конец rus_verbs:помчать{}, // помчать в школу rus_verbs:съезжать{}, // съезжать в кювет rus_verbs:завозить{}, // завозить в магазин rus_verbs:заявляться{}, // заявляться в школу rus_verbs:наглядеться{}, // наглядеться в зеркало rus_verbs:сворачиваться{}, // сворачиваться в клубочек rus_verbs:устремлять{}, // устремлять взор в будущее rus_verbs:забредать{}, // забредать в глухие уголки rus_verbs:перемотать{}, // перемотать в самое начало диалога rus_verbs:сморкаться{}, // сморкаться в носовой платочек rus_verbs:перетекать{}, // перетекать в другой сосуд rus_verbs:закачать{}, // закачать в шарик rus_verbs:запрятать{}, // запрятать в сейф rus_verbs:пинать{}, // пинать в живот rus_verbs:затрубить{}, // затрубить в горн rus_verbs:подглядывать{}, // подглядывать в замочную скважину инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш }, деепричастие:подсыпав{}, деепричастие:подсыпая{}, rus_verbs:засовывать{}, // засовывать в пенал rus_verbs:отрядить{}, // отрядить в командировку rus_verbs:справлять{}, // справлять в кусты rus_verbs:поторапливаться{}, // поторапливаться в самолет rus_verbs:скопировать{}, // скопировать в кэш rus_verbs:подливать{}, // подливать в огонь rus_verbs:запрячь{}, // запрячь в повозку rus_verbs:окраситься{}, // окраситься в пурпур rus_verbs:уколоть{}, // уколоть в шею rus_verbs:слететься{}, // слететься в гнездо rus_verbs:резаться{}, // резаться в карты rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш) деепричастие:задвигая{}, rus_verbs:доставляться{}, // доставляться в ресторан rus_verbs:поплевать{}, // поплевать в чашку rus_verbs:попереться{}, // попереться в магазин rus_verbs:хаживать{}, // хаживать в церковь rus_verbs:преображаться{}, // преображаться в королеву rus_verbs:организоваться{}, // организоваться в группу rus_verbs:ужалить{}, // ужалить в руку rus_verbs:протискиваться{}, // протискиваться в аудиторию rus_verbs:препроводить{}, // препроводить в закуток rus_verbs:разъезжаться{}, // разъезжаться в разные стороны rus_verbs:пропыхтеть{}, // пропыхтеть в трубку rus_verbs:уволочь{}, // уволочь в нору rus_verbs:отодвигаться{}, // отодвигаться в сторону rus_verbs:разливать{}, // разливать в стаканы rus_verbs:сбегаться{}, // сбегаться в актовый зал rus_verbs:наведаться{}, // наведаться в кладовку rus_verbs:перекочевать{}, // перекочевать в горы rus_verbs:прощебетать{}, // прощебетать в трубку rus_verbs:перекладывать{}, // перекладывать в другой карман rus_verbs:углубляться{}, // углубляться в теорию rus_verbs:переименовать{}, // переименовать в город rus_verbs:переметнуться{}, // переметнуться в лагерь противника rus_verbs:разносить{}, // разносить в щепки rus_verbs:осыпаться{}, // осыпаться в холода rus_verbs:попроситься{}, // попроситься в туалет rus_verbs:уязвить{}, // уязвить в сердце rus_verbs:перетащить{}, // перетащить в дом rus_verbs:закутаться{}, // закутаться в плед // rus_verbs:упаковать{}, // упаковать в бумагу инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость rus_verbs:хихикать{}, // хихикать в кулачок rus_verbs:объединить{}, // объединить в сеть инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию деепричастие:слетав{}, rus_verbs:заползти{}, // заползти в норку rus_verbs:перерасти{}, // перерасти в крупную аферу rus_verbs:списать{}, // списать в утиль rus_verbs:просачиваться{}, // просачиваться в бункер rus_verbs:пускаться{}, // пускаться в погоню rus_verbs:согревать{}, // согревать в мороз rus_verbs:наливаться{}, // наливаться в емкость rus_verbs:унестись{}, // унестись в небо rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф rus_verbs:сигануть{}, // сигануть в воду rus_verbs:окунуть{}, // окунуть в ледяную воду rus_verbs:просочиться{}, // просочиться в сапог rus_verbs:соваться{}, // соваться в толпу rus_verbs:протолкаться{}, // протолкаться в гардероб rus_verbs:заложить{}, // заложить в ломбард rus_verbs:перекатить{}, // перекатить в сарай rus_verbs:поставлять{}, // поставлять в Китай rus_verbs:залезать{}, // залезать в долги rus_verbs:отлучаться{}, // отлучаться в туалет rus_verbs:сбиваться{}, // сбиваться в кучу rus_verbs:зарыть{}, // зарыть в землю rus_verbs:засадить{}, // засадить в тело rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь rus_verbs:переставить{}, // переставить в шкаф rus_verbs:отчалить{}, // отчалить в плавание rus_verbs:набираться{}, // набираться в команду rus_verbs:лягнуть{}, // лягнуть в живот rus_verbs:притворить{}, // притворить в жизнь rus_verbs:проковылять{}, // проковылять в гардероб rus_verbs:прикатить{}, // прикатить в гараж rus_verbs:залететь{}, // залететь в окно rus_verbs:переделать{}, // переделать в мопед rus_verbs:протащить{}, // протащить в совет rus_verbs:обмакнуть{}, // обмакнуть в воду rus_verbs:отклоняться{}, // отклоняться в сторону rus_verbs:запихать{}, // запихать в пакет rus_verbs:избирать{}, // избирать в совет rus_verbs:загрузить{}, // загрузить в буфер rus_verbs:уплывать{}, // уплывать в Париж rus_verbs:забивать{}, // забивать в мерзлоту rus_verbs:потыкать{}, // потыкать в безжизненную тушу rus_verbs:съезжаться{}, // съезжаться в санаторий rus_verbs:залепить{}, // залепить в рыло rus_verbs:набиться{}, // набиться в карманы rus_verbs:уползти{}, // уползти в нору rus_verbs:упрятать{}, // упрятать в камеру rus_verbs:переместить{}, // переместить в камеру анабиоза rus_verbs:закрасться{}, // закрасться в душу rus_verbs:сместиться{}, // сместиться в инфракрасную область rus_verbs:запускать{}, // запускать в серию rus_verbs:потрусить{}, // потрусить в чащобу rus_verbs:забрасывать{}, // забрасывать в чистую воду rus_verbs:переселить{}, // переселить в отдаленную деревню rus_verbs:переезжать{}, // переезжать в новую квартиру rus_verbs:приподнимать{}, // приподнимать в воздух rus_verbs:добавиться{}, // добавиться в конец очереди rus_verbs:убыть{}, // убыть в часть rus_verbs:передвигать{}, // передвигать в соседнюю клетку rus_verbs:добавляться{}, // добавляться в очередь rus_verbs:дописать{}, // дописать в перечень rus_verbs:записываться{}, // записываться в кружок rus_verbs:продаться{}, // продаться в кредитное рабство rus_verbs:переписывать{}, // переписывать в тетрадку rus_verbs:заплыть{}, // заплыть в территориальные воды инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" }, rus_verbs:отбирать{}, // отбирать в гвардию rus_verbs:нашептывать{}, // нашептывать в микрофон rus_verbs:ковылять{}, // ковылять в стойло rus_verbs:прилетать{}, // прилетать в Париж rus_verbs:пролиться{}, // пролиться в канализацию rus_verbs:запищать{}, // запищать в микрофон rus_verbs:подвезти{}, // подвезти в больницу rus_verbs:припереться{}, // припереться в театр rus_verbs:утечь{}, // утечь в сеть rus_verbs:прорываться{}, // прорываться в буфет rus_verbs:увозить{}, // увозить в ремонт rus_verbs:съедать{}, // съедать в обед rus_verbs:просунуться{}, // просунуться в дверь rus_verbs:перенестись{}, // перенестись в прошлое rus_verbs:завезти{}, // завезти в магазин rus_verbs:проложить{}, // проложить в деревню rus_verbs:объединяться{}, // объединяться в профсоюз rus_verbs:развиться{}, // развиться в бабочку rus_verbs:засеменить{}, // засеменить в кабинку rus_verbs:скатываться{}, // скатываться в яму rus_verbs:завозиться{}, // завозиться в магазин rus_verbs:нанимать{}, // нанимать в рейс rus_verbs:поспеть{}, // поспеть в класс rus_verbs:кидаться{}, // кинаться в крайности rus_verbs:поспевать{}, // поспевать в оперу rus_verbs:обернуть{}, // обернуть в фольгу rus_verbs:обратиться{}, // обратиться в прокуратуру rus_verbs:истолковать{}, // истолковать в свою пользу rus_verbs:таращиться{}, // таращиться в дисплей rus_verbs:прыснуть{}, // прыснуть в кулачок rus_verbs:загнуть{}, // загнуть в другую сторону rus_verbs:раздать{}, // раздать в разные руки rus_verbs:назначить{}, // назначить в приемную комиссию rus_verbs:кидать{}, // кидать в кусты rus_verbs:увлекать{}, // увлекать в лес rus_verbs:переселиться{}, // переселиться в чужое тело rus_verbs:присылать{}, // присылать в город rus_verbs:уплыть{}, // уплыть в Европу rus_verbs:запричитать{}, // запричитать в полный голос rus_verbs:утащить{}, // утащить в логово rus_verbs:завернуться{}, // завернуться в плед rus_verbs:заносить{}, // заносить в блокнот rus_verbs:пятиться{}, // пятиться в дом rus_verbs:наведываться{}, // наведываться в больницу rus_verbs:нырять{}, // нырять в прорубь rus_verbs:зачастить{}, // зачастить в бар rus_verbs:назначаться{}, // назначается в комиссию rus_verbs:мотаться{}, // мотаться в областной центр rus_verbs:разыграть{}, // разыграть в карты rus_verbs:пропищать{}, // пропищать в микрофон rus_verbs:пихнуть{}, // пихнуть в бок rus_verbs:эмигрировать{}, // эмигрировать в Канаду rus_verbs:подключить{}, // подключить в сеть rus_verbs:упереть{}, // упереть в фундамент rus_verbs:уплатить{}, // уплатить в кассу rus_verbs:потащиться{}, // потащиться в медпункт rus_verbs:пригнать{}, // пригнать в стойло rus_verbs:оттеснить{}, // оттеснить в фойе rus_verbs:стучаться{}, // стучаться в ворота rus_verbs:перечислить{}, // перечислить в фонд rus_verbs:сомкнуть{}, // сомкнуть в круг rus_verbs:закачаться{}, // закачаться в резервуар rus_verbs:кольнуть{}, // кольнуть в бок rus_verbs:накрениться{}, // накрениться в сторону берега rus_verbs:подвинуться{}, // подвинуться в другую сторону rus_verbs:разнести{}, // разнести в клочья rus_verbs:отливать{}, // отливать в форму rus_verbs:подкинуть{}, // подкинуть в карман rus_verbs:уводить{}, // уводить в кабинет rus_verbs:ускакать{}, // ускакать в школу rus_verbs:ударять{}, // ударять в барабаны rus_verbs:даться{}, // даться в руки rus_verbs:поцеловаться{}, // поцеловаться в губы rus_verbs:посветить{}, // посветить в подвал rus_verbs:тыкать{}, // тыкать в арбуз rus_verbs:соединяться{}, // соединяться в кольцо rus_verbs:растянуть{}, // растянуть в тонкую ниточку rus_verbs:побросать{}, // побросать в пыль rus_verbs:стукнуться{}, // стукнуться в закрытую дверь rus_verbs:проигрывать{}, // проигрывать в теннис rus_verbs:дунуть{}, // дунуть в трубочку rus_verbs:улетать{}, // улетать в Париж rus_verbs:переводиться{}, // переводиться в филиал rus_verbs:окунуться{}, // окунуться в водоворот событий rus_verbs:попрятаться{}, // попрятаться в норы rus_verbs:перевезти{}, // перевезти в соседнюю палату rus_verbs:топать{}, // топать в школу rus_verbs:относить{}, // относить в помещение rus_verbs:укладывать{}, // укладывать в стопку rus_verbs:укатить{}, // укатил в турне rus_verbs:убирать{}, // убирать в сумку rus_verbs:помалкивать{}, // помалкивать в тряпочку rus_verbs:ронять{}, // ронять в грязь rus_verbs:глазеть{}, // глазеть в бинокль rus_verbs:преобразиться{}, // преобразиться в другого человека rus_verbs:запрыгнуть{}, // запрыгнуть в поезд rus_verbs:сгодиться{}, // сгодиться в суп rus_verbs:проползти{}, // проползти в нору rus_verbs:забираться{}, // забираться в коляску rus_verbs:сбежаться{}, // сбежались в класс rus_verbs:закатиться{}, // закатиться в угол rus_verbs:плевать{}, // плевать в душу rus_verbs:поиграть{}, // поиграть в демократию rus_verbs:кануть{}, // кануть в небытие rus_verbs:опаздывать{}, // опаздывать в школу rus_verbs:отползти{}, // отползти в сторону rus_verbs:стекаться{}, // стекаться в отстойник rus_verbs:запихнуть{}, // запихнуть в пакет rus_verbs:вышвырнуть{}, // вышвырнуть в коридор rus_verbs:связываться{}, // связываться в плотный узел rus_verbs:затолкать{}, // затолкать в ухо rus_verbs:скрутить{}, // скрутить в трубочку rus_verbs:сворачивать{}, // сворачивать в трубочку rus_verbs:сплестись{}, // сплестись в узел rus_verbs:заскочить{}, // заскочить в кабинет rus_verbs:проваливаться{}, // проваливаться в сон rus_verbs:уверовать{}, // уверовать в свою безнаказанность rus_verbs:переписать{}, // переписать в тетрадку rus_verbs:переноситься{}, // переноситься в мир фантазий rus_verbs:заводить{}, // заводить в помещение rus_verbs:сунуться{}, // сунуться в аудиторию rus_verbs:устраиваться{}, // устраиваться в автомастерскую rus_verbs:пропускать{}, // пропускать в зал инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш }, деепричастие:сбегая{}, деепричастие:сбегав{}, rus_verbs:прибегать{}, // прибегать в школу rus_verbs:съездить{}, // съездить в лес rus_verbs:захлопать{}, // захлопать в ладошки rus_verbs:опрокинуться{}, // опрокинуться в грязь инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш }, деепричастие:насыпая{}, деепричастие:насыпав{}, rus_verbs:употреблять{}, // употреблять в пищу rus_verbs:приводиться{}, // приводиться в действие rus_verbs:пристроить{}, // пристроить в надежные руки rus_verbs:юркнуть{}, // юркнуть в нору rus_verbs:объединиться{}, // объединиться в банду rus_verbs:сажать{}, // сажать в одиночку rus_verbs:соединить{}, // соединить в кольцо rus_verbs:забрести{}, // забрести в кафешку rus_verbs:свернуться{}, // свернуться в клубочек rus_verbs:пересесть{}, // пересесть в другой автобус rus_verbs:постучаться{}, // постучаться в дверцу rus_verbs:соединять{}, // соединять в кольцо rus_verbs:приволочь{}, // приволочь в коморку rus_verbs:смахивать{}, // смахивать в ящик стола rus_verbs:забежать{}, // забежать в помещение rus_verbs:целиться{}, // целиться в беглеца rus_verbs:прокрасться{}, // прокрасться в хранилище rus_verbs:заковылять{}, // заковылять в травтамологию rus_verbs:прискакать{}, // прискакать в стойло rus_verbs:колотить{}, // колотить в дверь rus_verbs:смотреться{}, // смотреться в зеркало rus_verbs:подложить{}, // подложить в салон rus_verbs:пущать{}, // пущать в королевские покои rus_verbs:согнуть{}, // согнуть в дугу rus_verbs:забарабанить{}, // забарабанить в дверь rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы rus_verbs:убраться{}, // убраться в специальную нишу rus_verbs:насмотреться{}, // насмотреться в зеркало rus_verbs:чмокнуть{}, // чмокнуть в щечку rus_verbs:усмехаться{}, // усмехаться в бороду rus_verbs:передвинуть{}, // передвинуть в конец очереди rus_verbs:допускаться{}, // допускаться в опочивальню rus_verbs:задвинуть{}, // задвинуть в дальний угол rus_verbs:отправлять{}, // отправлять в центр rus_verbs:сбрасывать{}, // сбрасывать в жерло rus_verbs:расстреливать{}, // расстреливать в момент обнаружения rus_verbs:заволочь{}, // заволочь в закуток rus_verbs:пролить{}, // пролить в воду rus_verbs:зарыться{}, // зарыться в сено rus_verbs:переливаться{}, // переливаться в емкость rus_verbs:затащить{}, // затащить в клуб rus_verbs:перебежать{}, // перебежать в лагерь врагов rus_verbs:одеть{}, // одеть в новое платье инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу деепричастие:задвигаясь{}, rus_verbs:клюнуть{}, // клюнуть в темечко rus_verbs:наливать{}, // наливать в кружку rus_verbs:пролезть{}, // пролезть в ушко rus_verbs:откладывать{}, // откладывать в ящик rus_verbs:протянуться{}, // протянуться в соседний дом rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь rus_verbs:устанавливать{}, // устанавливать в машину rus_verbs:употребляться{}, // употребляться в пищу rus_verbs:переключиться{}, // переключиться в реверсный режим rus_verbs:пискнуть{}, // пискнуть в микрофон rus_verbs:заявиться{}, // заявиться в класс rus_verbs:налиться{}, // налиться в стакан rus_verbs:заливать{}, // заливать в бак rus_verbs:ставиться{}, // ставиться в очередь инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны деепричастие:писаясь{}, rus_verbs:целоваться{}, // целоваться в губы rus_verbs:наносить{}, // наносить в область сердца rus_verbs:посмеяться{}, // посмеяться в кулачок rus_verbs:употребить{}, // употребить в пищу rus_verbs:прорваться{}, // прорваться в столовую rus_verbs:укладываться{}, // укладываться в ровные стопки rus_verbs:пробиться{}, // пробиться в финал rus_verbs:забить{}, // забить в землю rus_verbs:переложить{}, // переложить в другой карман rus_verbs:опускать{}, // опускать в свежевырытую могилу rus_verbs:поторопиться{}, // поторопиться в школу rus_verbs:сдвинуться{}, // сдвинуться в сторону rus_verbs:капать{}, // капать в смесь rus_verbs:погружаться{}, // погружаться во тьму rus_verbs:направлять{}, // направлять в кабинку rus_verbs:погрузить{}, // погрузить во тьму rus_verbs:примчаться{}, // примчаться в школу rus_verbs:упираться{}, // упираться в дверь rus_verbs:удаляться{}, // удаляться в комнату совещаний rus_verbs:ткнуться{}, // ткнуться в окошко rus_verbs:убегать{}, // убегать в чащу rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру rus_verbs:наговорить{}, // наговорить в микрофон rus_verbs:переносить{}, // переносить в дом rus_verbs:прилечь{}, // прилечь в кроватку rus_verbs:поворачивать{}, // поворачивать в обратную сторону rus_verbs:проскочить{}, // проскочить в щель rus_verbs:совать{}, // совать в духовку rus_verbs:переодеться{}, // переодеться в чистую одежду rus_verbs:порвать{}, // порвать в лоскуты rus_verbs:завязать{}, // завязать в бараний рог rus_verbs:съехать{}, // съехать в кювет rus_verbs:литься{}, // литься в канистру rus_verbs:уклониться{}, // уклониться в левую сторону rus_verbs:смахнуть{}, // смахнуть в мусорное ведро rus_verbs:спускать{}, // спускать в шахту rus_verbs:плеснуть{}, // плеснуть в воду rus_verbs:подуть{}, // подуть в угольки rus_verbs:набирать{}, // набирать в команду rus_verbs:хлопать{}, // хлопать в ладошки rus_verbs:ранить{}, // ранить в самое сердце rus_verbs:посматривать{}, // посматривать в иллюминатор rus_verbs:превращать{}, // превращать воду в вино rus_verbs:толкать{}, // толкать в пучину rus_verbs:отбыть{}, // отбыть в расположение части rus_verbs:сгрести{}, // сгрести в карман rus_verbs:удрать{}, // удрать в тайгу rus_verbs:пристроиться{}, // пристроиться в хорошую фирму rus_verbs:сбиться{}, // сбиться в плотную группу rus_verbs:заключать{}, // заключать в объятия rus_verbs:отпускать{}, // отпускать в поход rus_verbs:устремить{}, // устремить взгляд в будущее rus_verbs:обронить{}, // обронить в траву rus_verbs:сливаться{}, // сливаться в речку rus_verbs:стекать{}, // стекать в канаву rus_verbs:свалить{}, // свалить в кучу rus_verbs:подтянуть{}, // подтянуть в кабину rus_verbs:скатиться{}, // скатиться в канаву rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь rus_verbs:заторопиться{}, // заторопиться в буфет rus_verbs:протиснуться{}, // протиснуться в центр толпы rus_verbs:прятать{}, // прятать в укромненькое местечко rus_verbs:пропеть{}, // пропеть в микрофон rus_verbs:углубиться{}, // углубиться в джунгли rus_verbs:сползти{}, // сползти в яму rus_verbs:записывать{}, // записывать в память rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР) rus_verbs:колотиться{}, // колотиться в дверь rus_verbs:просунуть{}, // просунуть в отверстие rus_verbs:провожать{}, // провожать в армию rus_verbs:катить{}, // катить в гараж rus_verbs:поражать{}, // поражать в самое сердце rus_verbs:отлететь{}, // отлететь в дальний угол rus_verbs:закинуть{}, // закинуть в речку rus_verbs:катиться{}, // катиться в пропасть rus_verbs:забросить{}, // забросить в дальний угол rus_verbs:отвезти{}, // отвезти в лагерь rus_verbs:втопить{}, // втопить педаль в пол rus_verbs:втапливать{}, // втапливать педать в пол rus_verbs:утопить{}, // утопить кнопку в панель rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?) rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег rus_verbs:поскакать{}, // поскакать в атаку rus_verbs:прицелиться{}, // прицелиться в бегущего зайца rus_verbs:прыгать{}, // прыгать в кровать rus_verbs:приглашать{}, // приглашать в дом rus_verbs:понестись{}, // понестись в ворота rus_verbs:заехать{}, // заехать в гаражный бокс rus_verbs:опускаться{}, // опускаться в бездну rus_verbs:переехать{}, // переехать в коттедж rus_verbs:поместить{}, // поместить в карантин rus_verbs:ползти{}, // ползти в нору rus_verbs:добавлять{}, // добавлять в корзину rus_verbs:уткнуться{}, // уткнуться в подушку rus_verbs:продавать{}, // продавать в рабство rus_verbs:спрятаться{}, // Белка спрячется в дупло. rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию rus_verbs:воткнуть{}, // воткни вилку в розетку rus_verbs:нести{}, // нести в больницу rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку rus_verbs:впаивать{}, // впаивать деталь в плату rus_verbs:впаиваться{}, // деталь впаивается в плату rus_verbs:впархивать{}, // впархивать в помещение rus_verbs:впаять{}, // впаять деталь в плату rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат rus_verbs:вперивать{}, // вперивать взгляд в экран rus_verbs:впериваться{}, // впериваться в экран rus_verbs:вперить{}, // вперить взгляд в экран rus_verbs:впериться{}, // впериться в экран rus_verbs:вперять{}, // вперять взгляд в экран rus_verbs:вперяться{}, // вперяться в экран rus_verbs:впечатать{}, // впечатать текст в первую главу rus_verbs:впечататься{}, // впечататься в стену rus_verbs:впечатывать{}, // впечатывать текст в первую главу rus_verbs:впечатываться{}, // впечатываться в стену rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами rus_verbs:впитаться{}, // Жидкость впиталась в ткань rus_verbs:впитываться{}, // Жидкость впитывается в ткань rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник rus_verbs:вплавиться{}, // Провод вплавился в плату rus_verbs:вплеснуть{}, // вплеснуть краситель в бак rus_verbs:вплести{}, // вплести ленту в волосы rus_verbs:вплестись{}, // вплестись в волосы rus_verbs:вплетать{}, // вплетать ленты в волосы rus_verbs:вплывать{}, // корабль вплывает в порт rus_verbs:вплыть{}, // яхта вплыла в бухту rus_verbs:вползать{}, // дракон вползает в пещеру rus_verbs:вползти{}, // дракон вполз в свою пещеру rus_verbs:впорхнуть{}, // бабочка впорхнула в окно rus_verbs:впрессовать{}, // впрессовать деталь в плиту rus_verbs:впрессоваться{}, // впрессоваться в плиту rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту rus_verbs:впрессовываться{}, // впрессовываться в плиту rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания rus_verbs:впрягать{}, // впрягать лошадь в телегу rus_verbs:впрягаться{}, // впрягаться в работу rus_verbs:впрячь{}, // впрячь лошадь в телегу rus_verbs:впрячься{}, // впрячься в работу rus_verbs:впускать{}, // впускать посетителей в музей rus_verbs:впускаться{}, // впускаться в помещение rus_verbs:впустить{}, // впустить посетителей в музей rus_verbs:впутать{}, // впутать кого-то во что-то rus_verbs:впутаться{}, // впутаться во что-то rus_verbs:впутывать{}, // впутывать кого-то во что-то rus_verbs:впутываться{}, // впутываться во что-то rus_verbs:врабатываться{}, // врабатываться в режим rus_verbs:вработаться{}, // вработаться в режим rus_verbs:врастать{}, // врастать в кожу rus_verbs:врасти{}, // врасти в кожу инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь инфинитив:врезать{ вид:соверш }, глагол:врезать{ вид:несоверш }, глагол:врезать{ вид:соверш }, деепричастие:врезая{}, деепричастие:врезав{}, прилагательное:врезанный{}, инфинитив:врезаться{ вид:несоверш }, // врезаться в стену инфинитив:врезаться{ вид:соверш }, глагол:врезаться{ вид:несоверш }, деепричастие:врезаясь{}, деепричастие:врезавшись{}, rus_verbs:врубить{}, // врубить в нагрузку rus_verbs:врываться{}, // врываться в здание rus_verbs:закачивать{}, // Насос закачивает топливо в бак rus_verbs:ввезти{}, // Предприятие ввезло товар в страну rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу rus_verbs:ввивать{}, // Женщина ввивает полоску в косу rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека rus_verbs:вламываться{}, // Полиция вламывается в квартиру rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом rus_verbs:вовлечься{}, // вовлечься в занятие спортом rus_verbs:спуститься{}, // спуститься в подвал rus_verbs:спускаться{}, // спускаться в подвал rus_verbs:отправляться{}, // отправляться в дальнее плавание инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство инфинитив:эмитировать{ вид:несоверш }, глагол:эмитировать{ вид:соверш }, глагол:эмитировать{ вид:несоверш }, деепричастие:эмитируя{}, деепричастие:эмитировав{}, прилагательное:эмитировавший{ вид:несоверш }, // прилагательное:эмитировавший{ вид:соверш }, прилагательное:эмитирующий{}, прилагательное:эмитируемый{}, прилагательное:эмитированный{}, инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию инфинитив:этапировать{вид:соверш}, глагол:этапировать{вид:несоверш}, глагол:этапировать{вид:соверш}, деепричастие:этапируя{}, прилагательное:этапируемый{}, прилагательное:этапированный{}, rus_verbs:этапироваться{}, // Преступники этапируются в колонию rus_verbs:баллотироваться{}, // они баллотировались в жюри rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну rus_verbs:бросать{}, // Они бросали в фонтан медные монетки rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:бросить{}, // Он бросил в фонтан медную монетку rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя rus_verbs:буксировать{}, // Буксир буксирует танкер в порт rus_verbs:буксироваться{}, // Сухогруз буксируется в порт rus_verbs:вбегать{}, // Курьер вбегает в дверь rus_verbs:вбежать{}, // Курьер вбежал в дверь rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту rus_verbs:вбиваться{}, // Штырь вбивается в плиту rus_verbs:вбирать{}, // Вата вбирает в себя влагу rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру rus_verbs:вбросить{}, // Судья вбросил мяч в игру rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту rus_verbs:ввариваться{}, // Арматура вваривается в плиту rus_verbs:вварить{}, // Робот вварил арматурину в плиту rus_verbs:влезть{}, // Предприятие ввезло товар в страну rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача rus_verbs:вверяться{}, // Пациент вверяется в руки врача rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров rus_verbs:ввиваться{}, // полоска ввивается в косу rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров // rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон rus_verbs:ввязаться{}, // Разведрота ввязалась в бой rus_verbs:ввязываться{}, // Передовые части ввязываются в бой rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь rus_verbs:вдвинуться{}, // деталь вдвинулась в печь rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко rus_verbs:вделать{}, // мастер вделал розетку в стену rus_verbs:вделывать{}, // мастер вделывает выключатель в стену rus_verbs:вделываться{}, // кронштейн вделывается в стену rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку rus_verbs:вернуться{}, // Дети вернулись в библиотеку rus_verbs:вжаться{}, // Водитель вжался в кресло rus_verbs:вживаться{}, // Актер вживается в новую роль rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента rus_verbs:вживляться{}, // Стимулятор вживляется в тело rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло rus_verbs:вжиться{}, // Актер вжился в свою новую роль rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо rus_verbs:взвинтиться{}, // Цены взвинтились в небо rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо rus_verbs:взвиться{}, // Шарики взвились в небо rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо rus_verbs:взмывать{}, // шарики взмывают в небо rus_verbs:взмыть{}, // Шарики взмыли в небо rus_verbs:вильнуть{}, // Машина вильнула в левую сторону rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю rus_verbs:вкапываться{}, // Свая вкапывается в землю rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж rus_verbs:вкатиться{}, // машина вкатилась в гараж rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж rus_verbs:вкатываться{}, // машина вкатывается в гараж rus_verbs:вкачать{}, // Механики вкачали в бак много топлива rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак rus_verbs:вкачиваться{}, // Топливо вкачивается в бак rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер rus_verbs:вкидываться{}, // Груз вкидывается в контейнер rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции rus_verbs:вкладываться{}, // Инвестор вкладывается в акции rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист rus_verbs:вклиниваться{}, // Машина вклинивается в поток rus_verbs:вклиниться{}, // машина вклинилась в поток rus_verbs:включать{}, // Команда включает компьютер в сеть rus_verbs:включаться{}, // Машина включается в глобальную сеть rus_verbs:включить{}, // Команда включила компьютер в сеть rus_verbs:включиться{}, // Компьютер включился в сеть rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон rus_verbs:влазить{}, // Разъем влазит в отверствие rus_verbs:вламывать{}, // Полиция вламывается в квартиру rus_verbs:влетать{}, // Самолет влетает в грозовой фронт rus_verbs:влететь{}, // Самолет влетел в грозовой фронт rus_verbs:вливать{}, // Механик вливает масло в картер rus_verbs:вливаться{}, // Масло вливается в картер rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности rus_verbs:влить{}, // Механик влил свежее масло в картер rus_verbs:влиться{}, // Свежее масло влилось в бак rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства rus_verbs:вложиться{}, // Инвесторы вложились в эти акции rus_verbs:влюбиться{}, // Коля влюбился в Олю rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов rus_verbs:вляпаться{}, // Коля вляпался в неприятность rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности rus_verbs:вменить{}, // вменить в вину rus_verbs:вменять{}, // вменять в обязанность rus_verbs:вмерзать{}, // Колеса вмерзают в лед rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед rus_verbs:вмести{}, // вмести в дом rus_verbs:вместить{}, // вместить в ёмкость rus_verbs:вместиться{}, // Прибор не вместился в зонд rus_verbs:вмешаться{}, // Начальник вмешался в конфликт rus_verbs:вмешивать{}, // Не вмешивай меня в это дело rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус rus_verbs:вминать{}, // вминать в корпус rus_verbs:вминаться{}, // кронштейн вминается в корпус rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт rus_verbs:вморозить{}, // Установка вморозила сваи в грунт rus_verbs:вмуровать{}, // Сейф был вмурован в стену rus_verbs:вмуровывать{}, // вмуровывать сейф в стену rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену rus_verbs:внедрить{}, // внедрить инновацию в производство rus_verbs:внедриться{}, // Шпион внедрился в руководство rus_verbs:внедрять{}, // внедрять инновации в производство rus_verbs:внедряться{}, // Шпионы внедряются в руководство rus_verbs:внести{}, // внести коробку в дом rus_verbs:внестись{}, // внестись в список приглашенных гостей rus_verbs:вникать{}, // Разработчик вникает в детали задачи rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев rus_verbs:вноситься{}, // вноситься в список главных персонажей rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом rus_verbs:вогнать{}, // вогнал человека в тоску rus_verbs:водворить{}, // водворить преступника в тюрьму rus_verbs:возвернуть{}, // возвернуть в родную стихию rus_verbs:возвернуться{}, // возвернуться в родную стихию rus_verbs:возвести{}, // возвести число в четную степень rus_verbs:возводить{}, // возводить число в четную степень rus_verbs:возводиться{}, // число возводится в четную степень rus_verbs:возвратить{}, // возвратить коров в стойло rus_verbs:возвратиться{}, // возвратиться в родной дом rus_verbs:возвращать{}, // возвращать коров в стойло rus_verbs:возвращаться{}, // возвращаться в родной дом rus_verbs:войти{}, // войти в галерею славы rus_verbs:вонзать{}, // Коля вонзает вилку в котлету rus_verbs:вонзаться{}, // Вилка вонзается в котлету rus_verbs:вонзить{}, // Коля вонзил вилку в котлету rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность rus_verbs:воплотиться{}, // Мечты воплотились в реальность rus_verbs:воплощать{}, // Коля воплощает мечты в реальность rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь rus_verbs:воспарить{}, // Душа воспарила в небо rus_verbs:воспарять{}, // Душа воспаряет в небо rus_verbs:врыть{}, // врыть опору в землю rus_verbs:врыться{}, // врыться в землю rus_verbs:всадить{}, // всадить пулю в сердце rus_verbs:всаживать{}, // всаживать нож в бок rus_verbs:всасывать{}, // всасывать воду в себя rus_verbs:всасываться{}, // всасываться в ёмкость rus_verbs:вселить{}, // вселить надежду в кого-либо rus_verbs:вселиться{}, // вселиться в пустующее здание rus_verbs:вселять{}, // вселять надежду в кого-то rus_verbs:вселяться{}, // вселяться в пустующее здание rus_verbs:вскидывать{}, // вскидывать руку в небо rus_verbs:вскинуть{}, // вскинуть руку в небо rus_verbs:вслушаться{}, // вслушаться в звуки rus_verbs:вслушиваться{}, // вслушиваться в шорох rus_verbs:всматриваться{}, // всматриваться в темноту rus_verbs:всмотреться{}, // всмотреться в темень rus_verbs:всовывать{}, // всовывать палец в отверстие rus_verbs:всовываться{}, // всовываться в форточку rus_verbs:всосать{}, // всосать жидкость в себя rus_verbs:всосаться{}, // всосаться в кожу rus_verbs:вставить{}, // вставить ключ в замок rus_verbs:вставлять{}, // вставлять ключ в замок rus_verbs:встраивать{}, // встраивать черный ход в систему защиты rus_verbs:встраиваться{}, // встраиваться в систему безопасности rus_verbs:встревать{}, // встревать в разговор rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности rus_verbs:встроиться{}, // встроиться в систему безопасности rus_verbs:встрять{}, // встрять в разговор rus_verbs:вступать{}, // вступать в действующую армию rus_verbs:вступить{}, // вступить в действующую армию rus_verbs:всунуть{}, // всунуть палец в отверстие rus_verbs:всунуться{}, // всунуться в форточку инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер инфинитив:всыпать{вид:несоверш}, глагол:всыпать{вид:соверш}, глагол:всыпать{вид:несоверш}, деепричастие:всыпав{}, деепричастие:всыпая{}, прилагательное:всыпавший{ вид:соверш }, // прилагательное:всыпавший{ вид:несоверш }, прилагательное:всыпанный{}, // прилагательное:всыпающий{}, инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер // инфинитив:всыпаться{ вид:соверш}, // глагол:всыпаться{ вид:соверш}, глагол:всыпаться{ вид:несоверш}, // деепричастие:всыпавшись{}, деепричастие:всыпаясь{}, // прилагательное:всыпавшийся{ вид:соверш }, // прилагательное:всыпавшийся{ вид:несоверш }, // прилагательное:всыпающийся{}, rus_verbs:вталкивать{}, // вталкивать деталь в ячейку rus_verbs:вталкиваться{}, // вталкиваться в ячейку rus_verbs:втаптывать{}, // втаптывать в грязь rus_verbs:втаптываться{}, // втаптываться в грязь rus_verbs:втаскивать{}, // втаскивать мешок в комнату rus_verbs:втаскиваться{}, // втаскиваться в комнату rus_verbs:втащить{}, // втащить мешок в комнату rus_verbs:втащиться{}, // втащиться в комнату rus_verbs:втекать{}, // втекать в бутылку rus_verbs:втемяшивать{}, // втемяшивать в голову rus_verbs:втемяшиваться{}, // втемяшиваться в голову rus_verbs:втемяшить{}, // втемяшить в голову rus_verbs:втемяшиться{}, // втемяшиться в голову rus_verbs:втереть{}, // втереть крем в кожу rus_verbs:втереться{}, // втереться в кожу rus_verbs:втесаться{}, // втесаться в группу rus_verbs:втесывать{}, // втесывать в группу rus_verbs:втесываться{}, // втесываться в группу rus_verbs:втечь{}, // втечь в бак rus_verbs:втирать{}, // втирать крем в кожу rus_verbs:втираться{}, // втираться в кожу rus_verbs:втискивать{}, // втискивать сумку в вагон rus_verbs:втискиваться{}, // втискиваться в переполненный вагон rus_verbs:втиснуть{}, // втиснуть сумку в вагон rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро rus_verbs:втолкать{}, // втолкать коляску в лифт rus_verbs:втолкаться{}, // втолкаться в вагон метро rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт rus_verbs:втолкнуться{}, // втолкнуться в вагон метро rus_verbs:втолочь{}, // втолочь в смесь rus_verbs:втоптать{}, // втоптать цветы в землю rus_verbs:вторгаться{}, // вторгаться в чужую зону rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь rus_verbs:втравить{}, // втравить кого-то в неприятности rus_verbs:втравливать{}, // втравливать кого-то в неприятности rus_verbs:втрамбовать{}, // втрамбовать камни в землю rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю rus_verbs:втрамбовываться{}, // втрамбовываться в землю rus_verbs:втрескаться{}, // втрескаться в кого-то rus_verbs:втрескиваться{}, // втрескиваться в кого-либо rus_verbs:втыкать{}, // втыкать вилку в котлетку rus_verbs:втыкаться{}, // втыкаться в розетку rus_verbs:втюриваться{}, // втюриваться в кого-либо rus_verbs:втюриться{}, // втюриться в кого-либо rus_verbs:втягивать{}, // втягивать что-то в себя rus_verbs:втягиваться{}, // втягиваться в себя rus_verbs:втянуться{}, // втянуться в себя rus_verbs:вцементировать{}, // вцементировать сваю в фундамент rus_verbs:вчеканить{}, // вчеканить надпись в лист rus_verbs:вчитаться{}, // вчитаться внимательнее в текст rus_verbs:вчитываться{}, // вчитываться внимательнее в текст rus_verbs:вчувствоваться{}, // вчувствоваться в роль rus_verbs:вшагивать{}, // вшагивать в новую жизнь rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь rus_verbs:вшивать{}, // вшивать заплату в рубашку rus_verbs:вшиваться{}, // вшиваться в ткань rus_verbs:вшить{}, // вшить заплату в ткань rus_verbs:въедаться{}, // въедаться в мякоть rus_verbs:въезжать{}, // въезжать в гараж rus_verbs:въехать{}, // въехать в гараж rus_verbs:выиграть{}, // Коля выиграл в шахматы rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы rus_verbs:выкладывать{}, // выкладывать в общий доступ rus_verbs:выкладываться{}, // выкладываться в общий доступ rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет rus_verbs:вылезать{}, // вылезать в открытое пространство rus_verbs:вылезти{}, // вылезти в открытое пространство rus_verbs:выливать{}, // выливать в бутылку rus_verbs:выливаться{}, // выливаться в ёмкость rus_verbs:вылить{}, // вылить отходы в канализацию rus_verbs:вылиться{}, // Топливо вылилось в воду rus_verbs:выложить{}, // выложить в общий доступ rus_verbs:выпадать{}, // выпадать в осадок rus_verbs:выпрыгивать{}, // выпрыгивать в окно rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно rus_verbs:выродиться{}, // выродиться в жалкое подобие rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков rus_verbs:высеваться{}, // высеваться в землю rus_verbs:высеять{}, // высеять в землю rus_verbs:выслать{}, // выслать в страну постоянного пребывания rus_verbs:высморкаться{}, // высморкаться в платок rus_verbs:высморкнуться{}, // высморкнуться в платок rus_verbs:выстреливать{}, // выстреливать в цель rus_verbs:выстреливаться{}, // выстреливаться в цель rus_verbs:выстрелить{}, // выстрелить в цель rus_verbs:вытекать{}, // вытекать в озеро rus_verbs:вытечь{}, // вытечь в воду rus_verbs:смотреть{}, // смотреть в будущее rus_verbs:подняться{}, // подняться в лабораторию rus_verbs:послать{}, // послать в магазин rus_verbs:слать{}, // слать в неизвестность rus_verbs:добавить{}, // добавить в суп rus_verbs:пройти{}, // пройти в лабораторию rus_verbs:положить{}, // положить в ящик rus_verbs:прислать{}, // прислать в полицию rus_verbs:упасть{}, // упасть в пропасть инфинитив:писать{ aux stress="пис^ать" }, // писать в газету инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки глагол:писать{ aux stress="п^исать" }, глагол:писать{ aux stress="пис^ать" }, деепричастие:писая{}, прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету rus_verbs:собираться{}, // собираться в поход rus_verbs:звать{}, // звать в ресторан rus_verbs:направиться{}, // направиться в ресторан rus_verbs:отправиться{}, // отправиться в ресторан rus_verbs:поставить{}, // поставить в угол rus_verbs:целить{}, // целить в мишень rus_verbs:попасть{}, // попасть в переплет rus_verbs:ударить{}, // ударить в больное место rus_verbs:закричать{}, // закричать в микрофон rus_verbs:опустить{}, // опустить в воду rus_verbs:принести{}, // принести в дом бездомного щенка rus_verbs:отдать{}, // отдать в хорошие руки rus_verbs:ходить{}, // ходить в школу rus_verbs:уставиться{}, // уставиться в экран rus_verbs:приходить{}, // приходить в бешенство rus_verbs:махнуть{}, // махнуть в Италию rus_verbs:сунуть{}, // сунуть в замочную скважину rus_verbs:явиться{}, // явиться в расположение части rus_verbs:уехать{}, // уехать в город rus_verbs:целовать{}, // целовать в лобик rus_verbs:повести{}, // повести в бой rus_verbs:опуститься{}, // опуститься в кресло rus_verbs:передать{}, // передать в архив rus_verbs:побежать{}, // побежать в школу rus_verbs:стечь{}, // стечь в воду rus_verbs:уходить{}, // уходить добровольцем в армию rus_verbs:привести{}, // привести в дом rus_verbs:шагнуть{}, // шагнуть в неизвестность rus_verbs:собраться{}, // собраться в поход rus_verbs:заглянуть{}, // заглянуть в основу rus_verbs:поспешить{}, // поспешить в церковь rus_verbs:поцеловать{}, // поцеловать в лоб rus_verbs:перейти{}, // перейти в высшую лигу rus_verbs:поверить{}, // поверить в искренность rus_verbs:глянуть{}, // глянуть в оглавление rus_verbs:зайти{}, // зайти в кафетерий rus_verbs:подобрать{}, // подобрать в лесу rus_verbs:проходить{}, // проходить в помещение rus_verbs:глядеть{}, // глядеть в глаза rus_verbs:пригласить{}, // пригласить в театр rus_verbs:позвать{}, // позвать в класс rus_verbs:усесться{}, // усесться в кресло rus_verbs:поступить{}, // поступить в институт rus_verbs:лечь{}, // лечь в постель rus_verbs:поклониться{}, // поклониться в пояс rus_verbs:потянуться{}, // потянуться в лес rus_verbs:колоть{}, // колоть в ягодицу rus_verbs:присесть{}, // присесть в кресло rus_verbs:оглядеться{}, // оглядеться в зеркало rus_verbs:поглядеть{}, // поглядеть в зеркало rus_verbs:превратиться{}, // превратиться в лягушку rus_verbs:принимать{}, // принимать во внимание rus_verbs:звонить{}, // звонить в колокола rus_verbs:привезти{}, // привезти в гостиницу rus_verbs:рухнуть{}, // рухнуть в пропасть rus_verbs:пускать{}, // пускать в дело rus_verbs:отвести{}, // отвести в больницу rus_verbs:сойти{}, // сойти в ад rus_verbs:набрать{}, // набрать в команду rus_verbs:собрать{}, // собрать в кулак rus_verbs:двигаться{}, // двигаться в каюту rus_verbs:падать{}, // падать в область нуля rus_verbs:полезть{}, // полезть в драку rus_verbs:направить{}, // направить в стационар rus_verbs:приводить{}, // приводить в чувство rus_verbs:толкнуть{}, // толкнуть в бок rus_verbs:кинуться{}, // кинуться в драку rus_verbs:ткнуть{}, // ткнуть в глаз rus_verbs:заключить{}, // заключить в объятия rus_verbs:подниматься{}, // подниматься в небо rus_verbs:расти{}, // расти в глубину rus_verbs:налить{}, // налить в кружку rus_verbs:швырнуть{}, // швырнуть в бездну rus_verbs:прыгнуть{}, // прыгнуть в дверь rus_verbs:промолчать{}, // промолчать в тряпочку rus_verbs:садиться{}, // садиться в кресло rus_verbs:лить{}, // лить в кувшин rus_verbs:дослать{}, // дослать деталь в держатель rus_verbs:переслать{}, // переслать в обработчик rus_verbs:удалиться{}, // удалиться в совещательную комнату rus_verbs:разглядывать{}, // разглядывать в бинокль rus_verbs:повесить{}, // повесить в шкаф инфинитив:походить{ вид:соверш }, // походить в институт глагол:походить{ вид:соверш }, деепричастие:походив{}, // прилагательное:походивший{вид:соверш}, rus_verbs:помчаться{}, // помчаться в класс rus_verbs:свалиться{}, // свалиться в яму rus_verbs:сбежать{}, // сбежать в Англию rus_verbs:стрелять{}, // стрелять в цель rus_verbs:обращать{}, // обращать в свою веру rus_verbs:завести{}, // завести в дом rus_verbs:приобрести{}, // приобрести в рассрочку rus_verbs:сбросить{}, // сбросить в яму rus_verbs:устроиться{}, // устроиться в крупную корпорацию rus_verbs:погрузиться{}, // погрузиться в пучину rus_verbs:течь{}, // течь в канаву rus_verbs:произвести{}, // произвести в звание майора rus_verbs:метать{}, // метать в цель rus_verbs:пустить{}, // пустить в дело rus_verbs:полететь{}, // полететь в Европу rus_verbs:пропустить{}, // пропустить в здание rus_verbs:рвануть{}, // рвануть в отпуск rus_verbs:заходить{}, // заходить в каморку rus_verbs:нырнуть{}, // нырнуть в прорубь rus_verbs:рвануться{}, // рвануться в атаку rus_verbs:приподняться{}, // приподняться в воздух rus_verbs:превращаться{}, // превращаться в крупную величину rus_verbs:прокричать{}, // прокричать в ухо rus_verbs:записать{}, // записать в блокнот rus_verbs:забраться{}, // забраться в шкаф rus_verbs:приезжать{}, // приезжать в деревню rus_verbs:продать{}, // продать в рабство rus_verbs:проникнуть{}, // проникнуть в центр rus_verbs:устремиться{}, // устремиться в открытое море rus_verbs:посадить{}, // посадить в кресло rus_verbs:упереться{}, // упереться в пол rus_verbs:ринуться{}, // ринуться в буфет rus_verbs:отдавать{}, // отдавать в кадетское училище rus_verbs:отложить{}, // отложить в долгий ящик rus_verbs:убежать{}, // убежать в приют rus_verbs:оценить{}, // оценить в миллион долларов rus_verbs:поднимать{}, // поднимать в стратосферу rus_verbs:отослать{}, // отослать в квалификационную комиссию rus_verbs:отодвинуть{}, // отодвинуть в дальний угол rus_verbs:торопиться{}, // торопиться в школу rus_verbs:попадаться{}, // попадаться в руки rus_verbs:поразить{}, // поразить в самое сердце rus_verbs:доставить{}, // доставить в квартиру rus_verbs:заслать{}, // заслать в тыл rus_verbs:сослать{}, // сослать в изгнание rus_verbs:запустить{}, // запустить в космос rus_verbs:удариться{}, // удариться в запой rus_verbs:ударяться{}, // ударяться в крайность rus_verbs:шептать{}, // шептать в лицо rus_verbs:уронить{}, // уронить в унитаз rus_verbs:прорычать{}, // прорычать в микрофон rus_verbs:засунуть{}, // засунуть в глотку rus_verbs:плыть{}, // плыть в открытое море rus_verbs:перенести{}, // перенести в духовку rus_verbs:светить{}, // светить в лицо rus_verbs:мчаться{}, // мчаться в ремонт rus_verbs:стукнуть{}, // стукнуть в лоб rus_verbs:обрушиться{}, // обрушиться в котлован rus_verbs:поглядывать{}, // поглядывать в экран rus_verbs:уложить{}, // уложить в кроватку инфинитив:попадать{ вид:несоверш }, // попадать в черный список глагол:попадать{ вид:несоверш }, прилагательное:попадающий{ вид:несоверш }, прилагательное:попадавший{ вид:несоверш }, деепричастие:попадая{}, rus_verbs:провалиться{}, // провалиться в яму rus_verbs:жаловаться{}, // жаловаться в комиссию rus_verbs:опоздать{}, // опоздать в школу rus_verbs:посылать{}, // посылать в парикмахерскую rus_verbs:погнать{}, // погнать в хлев rus_verbs:поступать{}, // поступать в институт rus_verbs:усадить{}, // усадить в кресло rus_verbs:проиграть{}, // проиграть в рулетку rus_verbs:прилететь{}, // прилететь в страну rus_verbs:повалиться{}, // повалиться в траву rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ rus_verbs:лезть{}, // лезть в чужие дела rus_verbs:потащить{}, // потащить в суд rus_verbs:направляться{}, // направляться в порт rus_verbs:поползти{}, // поползти в другую сторону rus_verbs:пуститься{}, // пуститься в пляс rus_verbs:забиться{}, // забиться в нору rus_verbs:залезть{}, // залезть в конуру rus_verbs:сдать{}, // сдать в утиль rus_verbs:тронуться{}, // тронуться в путь rus_verbs:сыграть{}, // сыграть в шахматы rus_verbs:перевернуть{}, // перевернуть в более удобную позу rus_verbs:сжимать{}, // сжимать пальцы в кулак rus_verbs:подтолкнуть{}, // подтолкнуть в бок rus_verbs:отнести{}, // отнести животное в лечебницу rus_verbs:одеться{}, // одеться в зимнюю одежду rus_verbs:плюнуть{}, // плюнуть в колодец rus_verbs:передавать{}, // передавать в прокуратуру rus_verbs:отскочить{}, // отскочить в лоб rus_verbs:призвать{}, // призвать в армию rus_verbs:увезти{}, // увезти в деревню rus_verbs:улечься{}, // улечься в кроватку rus_verbs:отшатнуться{}, // отшатнуться в сторону rus_verbs:ложиться{}, // ложиться в постель rus_verbs:пролететь{}, // пролететь в конец rus_verbs:класть{}, // класть в сейф rus_verbs:доставлять{}, // доставлять в кабинет rus_verbs:приобретать{}, // приобретать в кредит rus_verbs:сводить{}, // сводить в театр rus_verbs:унести{}, // унести в могилу rus_verbs:покатиться{}, // покатиться в яму rus_verbs:сходить{}, // сходить в магазинчик rus_verbs:спустить{}, // спустить в канализацию rus_verbs:проникать{}, // проникать в сердцевину rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд rus_verbs:пожаловаться{}, // пожаловаться в администрацию rus_verbs:стучать{}, // стучать в металлическую дверь rus_verbs:тащить{}, // тащить в ремонт rus_verbs:заглядывать{}, // заглядывать в ответы rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена rus_verbs:увести{}, // увести в следующий кабинет rus_verbs:успевать{}, // успевать в школу rus_verbs:пробраться{}, // пробраться в собачью конуру rus_verbs:подавать{}, // подавать в суд rus_verbs:прибежать{}, // прибежать в конюшню rus_verbs:рассмотреть{}, // рассмотреть в микроскоп rus_verbs:пнуть{}, // пнуть в живот rus_verbs:завернуть{}, // завернуть в декоративную пленку rus_verbs:уезжать{}, // уезжать в деревню rus_verbs:привлекать{}, // привлекать в свои ряды rus_verbs:перебраться{}, // перебраться в прибрежный город rus_verbs:долить{}, // долить в коктейль rus_verbs:палить{}, // палить в нападающих rus_verbs:отобрать{}, // отобрать в коллекцию rus_verbs:улететь{}, // улететь в неизвестность rus_verbs:выглянуть{}, // выглянуть в окно rus_verbs:выглядывать{}, // выглядывать в окно rus_verbs:пробираться{}, // грабитель, пробирающийся в дом инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог глагол:написать{ aux stress="напис^ать"}, прилагательное:написавший{ aux stress="напис^авший"}, rus_verbs:свернуть{}, // свернуть в колечко инфинитив:сползать{ вид:несоверш }, // сползать в овраг глагол:сползать{ вид:несоверш }, прилагательное:сползающий{ вид:несоверш }, прилагательное:сползавший{ вид:несоверш }, rus_verbs:барабанить{}, // барабанить в дверь rus_verbs:дописывать{}, // дописывать в конец rus_verbs:меняться{}, // меняться в лучшую сторону rus_verbs:измениться{}, // измениться в лучшую сторону rus_verbs:изменяться{}, // изменяться в лучшую сторону rus_verbs:вписаться{}, // вписаться в поворот rus_verbs:вписываться{}, // вписываться в повороты rus_verbs:переработать{}, // переработать в удобрение rus_verbs:перерабатывать{}, // перерабатывать в удобрение rus_verbs:уползать{}, // уползать в тень rus_verbs:заползать{}, // заползать в нору rus_verbs:перепрятать{}, // перепрятать в укромное место rus_verbs:заталкивать{}, // заталкивать в вагон rus_verbs:преобразовывать{}, // преобразовывать в список инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список глагол:конвертировать{ вид:несоверш }, инфинитив:конвертировать{ вид:соверш }, глагол:конвертировать{ вид:соверш }, деепричастие:конвертировав{}, деепричастие:конвертируя{}, rus_verbs:изорвать{}, // Он изорвал газету в клочки. rus_verbs:выходить{}, // Окна выходят в сад. rus_verbs:говорить{}, // Он говорил в защиту своего отца. rus_verbs:вырастать{}, // Он вырастает в большого художника. rus_verbs:вывести{}, // Он вывел детей в сад. // инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш }, // глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли. // прилагательное:раненый{}, // Он был ранен в левую руку. // прилагательное:одетый{}, // Он был одет в толстое осеннее пальто. rus_verbs:бухнуться{}, // Он бухнулся в воду. rus_verbs:склонять{}, // склонять защиту в свою пользу rus_verbs:впиться{}, // Пиявка впилась в тело. rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы rus_verbs:сохранять{}, // сохранить данные в файл rus_verbs:собирать{}, // собирать игрушки в ящик rus_verbs:упаковывать{}, // упаковывать вещи в чемодан rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:стрельнуть{}, // стрельни в толпу! rus_verbs:пулять{}, // пуляй в толпу rus_verbs:пульнуть{}, // пульни в толпу rus_verbs:становиться{}, // Становитесь в очередь. rus_verbs:вписать{}, // Юля вписала свое имя в список. rus_verbs:вписывать{}, // Мы вписывали свои имена в список прилагательное:видный{}, // Планета Марс видна в обычный бинокль rus_verbs:пойти{}, // Девочка рано пошла в школу rus_verbs:отойти{}, // Эти обычаи отошли в историю. rus_verbs:бить{}, // Холодный ветер бил ему в лицо. rus_verbs:входить{}, // Это входит в его обязанности. rus_verbs:принять{}, // меня приняли в пионеры rus_verbs:уйти{}, // Правительство РФ ушло в отставку rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году. rus_verbs:посвятить{}, // Я посвятил друга в свою тайну. инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза. rus_verbs:идти{}, // Я иду гулять в парк. rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт. rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей. rus_verbs:везти{}, // Учитель везёт детей в лагерь. rus_verbs:качать{}, // Судно качает во все стороны. rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами. rus_verbs:связать{}, // Свяжите свои вещи в узелок. rus_verbs:пронести{}, // Пронесите стол в дверь. rus_verbs:вынести{}, // Надо вынести примечания в конец. rus_verbs:устроить{}, // Она устроила сына в школу. rus_verbs:угодить{}, // Она угодила головой в дверь. rus_verbs:отвернуться{}, // Она резко отвернулась в сторону. rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль. rus_verbs:обратить{}, // Война обратила город в развалины. rus_verbs:сойтись{}, // Мы сошлись в школьные годы. rus_verbs:приехать{}, // Мы приехали в положенный час. rus_verbs:встать{}, // Дети встали в круг. rus_verbs:впасть{}, // Из-за болезни он впал в нужду. rus_verbs:придти{}, // придти в упадок rus_verbs:заявить{}, // Надо заявить в милицию о краже. rus_verbs:заявлять{}, // заявлять в полицию rus_verbs:ехать{}, // Мы будем ехать в Орёл rus_verbs:окрашиваться{}, // окрашиваться в красный цвет rus_verbs:решить{}, // Дело решено в пользу истца. rus_verbs:сесть{}, // Она села в кресло rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало. rus_verbs:влезать{}, // он влезает в мою квартирку rus_verbs:попасться{}, // в мою ловушку попалась мышь rus_verbs:лететь{}, // Мы летим в Орёл ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень ГЛ_ИНФ(взять), // Коля взял в руку камень ГЛ_ИНФ(поехать), // поехать в круиз ГЛ_ИНФ(подать), // подать в отставку инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море ГЛ_ИНФ(постучать) // постучать в дверь } // Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems fact гл_предл { if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } } then return true } #endregion Винительный // Все остальные варианты по умолчанию запрещаем. fact гл_предл { if context { * предлог:в{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:в{} * } then return false,-5 } #endregion Предлог_В #region Предлог_НА // ------------------- С ПРЕДЛОГОМ 'НА' --------------------------- #region ПРЕДЛОЖНЫЙ // НА+предложный падеж: // ЛЕЖАТЬ НА СТОЛЕ #region VerbList wordentry_set Гл_НА_Предл= { rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ) rus_verbs:ПРОСТУПИТЬ{}, // rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ) rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ) rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив) rus_verbs:ЗАМИРАТЬ{}, // rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ) rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ) rus_verbs:УПОЛЗАТЬ{}, // rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ) rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ) rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ) rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ) rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ) rus_verbs:искриться{}, rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ) rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ) rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ) rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ) rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ) rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ) rus_verbs:отвести{}, // отвести душу на людях rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра rus_verbs:сойтись{}, rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ) rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ) rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ) глагол:ДОСТИЧЬ{}, инфинитив:ДОСТИЧЬ{}, rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте rus_verbs:РАСКЛАДЫВАТЬ{}, rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ) rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ) rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ) rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ) rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ) rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ) rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта rus_verbs:подпрыгивать{}, rus_verbs:высветиться{}, // на компьютере высветится твоя подпись rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА) rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл) rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл) rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА) rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл) rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл) rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл) rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл) rus_verbs:ОТТОЧИТЬ{}, rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА) rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл) инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл) глагол:НАХОДИТЬСЯ{ вид:несоверш }, прилагательное:находившийся{ вид:несоверш }, прилагательное:находящийся{ вид:несоверш }, деепричастие:находясь{}, rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл) rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА) rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА) rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл) rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА) rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл) rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА) rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА) rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА) rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА) rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА) rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА) rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл) rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА) rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА) rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА) rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА) rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА) rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА) rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл) rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл) rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на) rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к) rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на) глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте) деепричастие:вычитав{}, rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на) rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере rus_verbs:развалиться{}, // Антонио развалился на диване rus_verbs:улечься{}, // Антонио улегся на полу rus_verbs:зарубить{}, // Заруби себе на носу. rus_verbs:ценить{}, // Его ценят на заводе. rus_verbs:вернуться{}, // Отец вернулся на закате. rus_verbs:шить{}, // Вы умеете шить на машинке? rus_verbs:бить{}, // Скот бьют на бойне. rus_verbs:выехать{}, // Мы выехали на рассвете. rus_verbs:валяться{}, // На полу валяется бумага. rus_verbs:разложить{}, // она разложила полотенце на песке rus_verbs:заниматься{}, // я занимаюсь на тренажере rus_verbs:позаниматься{}, rus_verbs:порхать{}, // порхать на лугу rus_verbs:пресекать{}, // пресекать на корню rus_verbs:изъясняться{}, // изъясняться на непонятном языке rus_verbs:развесить{}, // развесить на столбах rus_verbs:обрасти{}, // обрасти на южной части rus_verbs:откладываться{}, // откладываться на стенках артерий rus_verbs:уносить{}, // уносить на носилках rus_verbs:проплыть{}, // проплыть на плоту rus_verbs:подъезжать{}, // подъезжать на повозках rus_verbs:пульсировать{}, // пульсировать на лбу rus_verbs:рассесться{}, // птицы расселись на ветках rus_verbs:застопориться{}, // застопориться на первом пункте rus_verbs:изловить{}, // изловить на окраинах rus_verbs:покататься{}, // покататься на машинках rus_verbs:залопотать{}, // залопотать на неизвестном языке rus_verbs:растягивать{}, // растягивать на станке rus_verbs:поделывать{}, // поделывать на пляже rus_verbs:подстеречь{}, // подстеречь на площадке rus_verbs:проектировать{}, // проектировать на компьютере rus_verbs:притулиться{}, // притулиться на кушетке rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище rus_verbs:пострелять{}, // пострелять на испытательном полигоне rus_verbs:засиживаться{}, // засиживаться на работе rus_verbs:нежиться{}, // нежиться на солнышке rus_verbs:притомиться{}, // притомиться на рабочем месте rus_verbs:поселяться{}, // поселяться на чердаке rus_verbs:потягиваться{}, // потягиваться на земле rus_verbs:отлеживаться{}, // отлеживаться на койке rus_verbs:протаранить{}, // протаранить на танке rus_verbs:гарцевать{}, // гарцевать на коне rus_verbs:облупиться{}, // облупиться на носу rus_verbs:оговорить{}, // оговорить на собеседовании rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте rus_verbs:отпечатать{}, // отпечатать на картоне rus_verbs:сэкономить{}, // сэкономить на мелочах rus_verbs:покатать{}, // покатать на пони rus_verbs:колесить{}, // колесить на старой машине rus_verbs:понастроить{}, // понастроить на участках rus_verbs:поджарить{}, // поджарить на костре rus_verbs:узнаваться{}, // узнаваться на фотографии rus_verbs:отощать{}, // отощать на казенных харчах rus_verbs:редеть{}, // редеть на макушке rus_verbs:оглашать{}, // оглашать на общем собрании rus_verbs:лопотать{}, // лопотать на иврите rus_verbs:пригреть{}, // пригреть на груди rus_verbs:консультироваться{}, // консультироваться на форуме rus_verbs:приноситься{}, // приноситься на одежде rus_verbs:сушиться{}, // сушиться на балконе rus_verbs:наследить{}, // наследить на полу rus_verbs:нагреться{}, // нагреться на солнце rus_verbs:рыбачить{}, // рыбачить на озере rus_verbs:прокатить{}, // прокатить на выборах rus_verbs:запинаться{}, // запинаться на ровном месте rus_verbs:отрубиться{}, // отрубиться на мягкой подушке rus_verbs:заморозить{}, // заморозить на улице rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе rus_verbs:просохнуть{}, // просохнуть на батарее rus_verbs:развозить{}, // развозить на велосипеде rus_verbs:прикорнуть{}, // прикорнуть на диванчике rus_verbs:отпечататься{}, // отпечататься на коже rus_verbs:выявлять{}, // выявлять на таможне rus_verbs:расставлять{}, // расставлять на башнях rus_verbs:прокрутить{}, // прокрутить на пальце rus_verbs:умываться{}, // умываться на улице rus_verbs:пересказывать{}, // пересказывать на страницах романа rus_verbs:удалять{}, // удалять на пуховике rus_verbs:хозяйничать{}, // хозяйничать на складе rus_verbs:оперировать{}, // оперировать на поле боя rus_verbs:поносить{}, // поносить на голове rus_verbs:замурлыкать{}, // замурлыкать на коленях rus_verbs:передвигать{}, // передвигать на тележке rus_verbs:прочертить{}, // прочертить на земле rus_verbs:колдовать{}, // колдовать на кухне rus_verbs:отвозить{}, // отвозить на казенном транспорте rus_verbs:трахать{}, // трахать на природе rus_verbs:мастерить{}, // мастерить на кухне rus_verbs:ремонтировать{}, // ремонтировать на коленке rus_verbs:развезти{}, // развезти на велосипеде rus_verbs:робеть{}, // робеть на сцене инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш }, деепричастие:реализовав{}, деепричастие:реализуя{}, rus_verbs:покаяться{}, // покаяться на смертном одре rus_verbs:специализироваться{}, // специализироваться на тестировании rus_verbs:попрыгать{}, // попрыгать на батуте rus_verbs:переписывать{}, // переписывать на столе rus_verbs:расписывать{}, // расписывать на доске rus_verbs:зажимать{}, // зажимать на запястье rus_verbs:практиковаться{}, // практиковаться на мышах rus_verbs:уединиться{}, // уединиться на чердаке rus_verbs:подохнуть{}, // подохнуть на чужбине rus_verbs:приподниматься{}, // приподниматься на руках rus_verbs:уродиться{}, // уродиться на полях rus_verbs:продолжиться{}, // продолжиться на улице rus_verbs:посапывать{}, // посапывать на диване rus_verbs:ободрать{}, // ободрать на спине rus_verbs:скрючиться{}, // скрючиться на песке rus_verbs:тормознуть{}, // тормознуть на перекрестке rus_verbs:лютовать{}, // лютовать на хуторе rus_verbs:зарегистрировать{}, // зарегистрировать на сайте rus_verbs:переждать{}, // переждать на вершине холма rus_verbs:доминировать{}, // доминировать на территории rus_verbs:публиковать{}, // публиковать на сайте rus_verbs:морщить{}, // морщить на лбу rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном rus_verbs:подрабатывать{}, // подрабатывать на рынке rus_verbs:репетировать{}, // репетировать на заднем дворе rus_verbs:подвернуть{}, // подвернуть на брусчатке rus_verbs:зашелестеть{}, // зашелестеть на ветру rus_verbs:расчесывать{}, // расчесывать на спине rus_verbs:одевать{}, // одевать на рынке rus_verbs:испечь{}, // испечь на углях rus_verbs:сбрить{}, // сбрить на затылке rus_verbs:согреться{}, // согреться на печке rus_verbs:замаячить{}, // замаячить на горизонте rus_verbs:пересчитывать{}, // пересчитывать на пальцах rus_verbs:галдеть{}, // галдеть на крыльце rus_verbs:переплыть{}, // переплыть на плоту rus_verbs:передохнуть{}, // передохнуть на скамейке rus_verbs:прижиться{}, // прижиться на ферме rus_verbs:переправляться{}, // переправляться на плотах rus_verbs:накупить{}, // накупить на блошином рынке rus_verbs:проторчать{}, // проторчать на виду rus_verbs:мокнуть{}, // мокнуть на улице rus_verbs:застукать{}, // застукать на камбузе rus_verbs:завязывать{}, // завязывать на ботинках rus_verbs:повисать{}, // повисать на ветке rus_verbs:подвизаться{}, // подвизаться на государственной службе rus_verbs:кормиться{}, // кормиться на болоте rus_verbs:покурить{}, // покурить на улице rus_verbs:зимовать{}, // зимовать на болотах rus_verbs:застегивать{}, // застегивать на гимнастерке rus_verbs:поигрывать{}, // поигрывать на гитаре rus_verbs:погореть{}, // погореть на махинациях с землей rus_verbs:кувыркаться{}, // кувыркаться на батуте rus_verbs:похрапывать{}, // похрапывать на диване rus_verbs:пригревать{}, // пригревать на груди rus_verbs:завязнуть{}, // завязнуть на болоте rus_verbs:шастать{}, // шастать на втором этаже rus_verbs:заночевать{}, // заночевать на сеновале rus_verbs:отсиживаться{}, // отсиживаться на чердаке rus_verbs:мчать{}, // мчать на байке rus_verbs:сгнить{}, // сгнить на урановых рудниках rus_verbs:тренировать{}, // тренировать на манекенах rus_verbs:повеселиться{}, // повеселиться на празднике rus_verbs:измучиться{}, // измучиться на болоте rus_verbs:увянуть{}, // увянуть на подоконнике rus_verbs:раскрутить{}, // раскрутить на оси rus_verbs:выцвести{}, // выцвести на солнечном свету rus_verbs:изготовлять{}, // изготовлять на коленке rus_verbs:гнездиться{}, // гнездиться на вершине дерева rus_verbs:разогнаться{}, // разогнаться на мотоцикле rus_verbs:излагаться{}, // излагаться на страницах доклада rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге rus_verbs:расчесать{}, // расчесать на макушке rus_verbs:плавиться{}, // плавиться на солнце rus_verbs:редактировать{}, // редактировать на ноутбуке rus_verbs:подскакивать{}, // подскакивать на месте rus_verbs:покупаться{}, // покупаться на рынке rus_verbs:промышлять{}, // промышлять на мелководье rus_verbs:приобретаться{}, // приобретаться на распродажах rus_verbs:наигрывать{}, // наигрывать на банджо rus_verbs:маневрировать{}, // маневрировать на флангах rus_verbs:запечатлеться{}, // запечатлеться на записях камер rus_verbs:укрывать{}, // укрывать на чердаке rus_verbs:подорваться{}, // подорваться на фугасе rus_verbs:закрепиться{}, // закрепиться на занятых позициях rus_verbs:громыхать{}, // громыхать на кухне инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу деепричастие:подвигавшись{}, rus_verbs:добываться{}, // добываться на территории Анголы rus_verbs:приплясывать{}, // приплясывать на сцене rus_verbs:доживать{}, // доживать на больничной койке rus_verbs:отпраздновать{}, // отпраздновать на работе rus_verbs:сгубить{}, // сгубить на корню rus_verbs:схоронить{}, // схоронить на кладбище rus_verbs:тускнеть{}, // тускнеть на солнце rus_verbs:скопить{}, // скопить на счету rus_verbs:помыть{}, // помыть на своем этаже rus_verbs:пороть{}, // пороть на конюшне rus_verbs:наличествовать{}, // наличествовать на складе rus_verbs:нащупывать{}, // нащупывать на полке rus_verbs:змеиться{}, // змеиться на дне rus_verbs:пожелтеть{}, // пожелтеть на солнце rus_verbs:заостриться{}, // заостриться на конце rus_verbs:свезти{}, // свезти на поле rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре rus_verbs:подкрутить{}, // подкрутить на приборной панели rus_verbs:рубиться{}, // рубиться на мечах rus_verbs:сиживать{}, // сиживать на крыльце rus_verbs:тараторить{}, // тараторить на иностранном языке rus_verbs:теплеть{}, // теплеть на сердце rus_verbs:покачаться{}, // покачаться на ветке rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче rus_verbs:развязывать{}, // развязывать на ботинках rus_verbs:подвозить{}, // подвозить на мотороллере rus_verbs:вышивать{}, // вышивать на рубашке rus_verbs:скупать{}, // скупать на открытом рынке rus_verbs:оформлять{}, // оформлять на встрече rus_verbs:распускаться{}, // распускаться на клумбах rus_verbs:прогореть{}, // прогореть на спекуляциях rus_verbs:приползти{}, // приползти на коленях rus_verbs:загореть{}, // загореть на пляже rus_verbs:остудить{}, // остудить на балконе rus_verbs:нарвать{}, // нарвать на поляне rus_verbs:издохнуть{}, // издохнуть на болоте rus_verbs:разгружать{}, // разгружать на дороге rus_verbs:произрастать{}, // произрастать на болотах rus_verbs:разуться{}, // разуться на коврике rus_verbs:сооружать{}, // сооружать на площади rus_verbs:зачитывать{}, // зачитывать на митинге rus_verbs:уместиться{}, // уместиться на ладони rus_verbs:закупить{}, // закупить на рынке rus_verbs:горланить{}, // горланить на улице rus_verbs:экономить{}, // экономить на спичках rus_verbs:исправлять{}, // исправлять на доске rus_verbs:расслабляться{}, // расслабляться на лежаке rus_verbs:скапливаться{}, // скапливаться на крыше rus_verbs:сплетничать{}, // сплетничать на скамеечке rus_verbs:отъезжать{}, // отъезжать на лимузине rus_verbs:отчитывать{}, // отчитывать на собрании rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке rus_verbs:потчевать{}, // потчевать на лаврах rus_verbs:окопаться{}, // окопаться на окраине rus_verbs:загорать{}, // загорать на пляже rus_verbs:обгореть{}, // обгореть на солнце rus_verbs:распознавать{}, // распознавать на фотографии rus_verbs:заплетаться{}, // заплетаться на макушке rus_verbs:перегреться{}, // перегреться на жаре rus_verbs:подметать{}, // подметать на крыльце rus_verbs:нарисоваться{}, // нарисоваться на горизонте rus_verbs:проскакивать{}, // проскакивать на экране rus_verbs:попивать{}, // попивать на балконе чай rus_verbs:отплывать{}, // отплывать на лодке rus_verbs:чирикать{}, // чирикать на ветках rus_verbs:скупить{}, // скупить на оптовых базах rus_verbs:наколоть{}, // наколоть на коже картинку rus_verbs:созревать{}, // созревать на ветке rus_verbs:проколоться{}, // проколоться на мелочи rus_verbs:крутнуться{}, // крутнуться на заднем колесе rus_verbs:переночевать{}, // переночевать на постоялом дворе rus_verbs:концентрироваться{}, // концентрироваться на фильтре rus_verbs:одичать{}, // одичать на хуторе rus_verbs:спасаться{}, // спасаются на лодке rus_verbs:доказываться{}, // доказываться на страницах книги rus_verbs:познаваться{}, // познаваться на ринге rus_verbs:замыкаться{}, // замыкаться на металлическом предмете rus_verbs:заприметить{}, // заприметить на пригорке rus_verbs:продержать{}, // продержать на морозе rus_verbs:форсировать{}, // форсировать на плотах rus_verbs:сохнуть{}, // сохнуть на солнце rus_verbs:выявить{}, // выявить на поверхности rus_verbs:заседать{}, // заседать на кафедре rus_verbs:расплачиваться{}, // расплачиваться на выходе rus_verbs:светлеть{}, // светлеть на горизонте rus_verbs:залепетать{}, // залепетать на незнакомом языке rus_verbs:подсчитывать{}, // подсчитывать на пальцах rus_verbs:зарыть{}, // зарыть на пустыре rus_verbs:сформироваться{}, // сформироваться на месте rus_verbs:развертываться{}, // развертываться на площадке rus_verbs:набивать{}, // набивать на манекенах rus_verbs:замерзать{}, // замерзать на ветру rus_verbs:схватывать{}, // схватывать на лету rus_verbs:перевестись{}, // перевестись на Руси rus_verbs:смешивать{}, // смешивать на блюдце rus_verbs:прождать{}, // прождать на входе rus_verbs:мерзнуть{}, // мерзнуть на ветру rus_verbs:растирать{}, // растирать на коже rus_verbs:переспать{}, // переспал на сеновале rus_verbs:рассекать{}, // рассекать на скутере rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне rus_verbs:дрыхнуть{}, // дрыхнуть на диване rus_verbs:распять{}, // распять на кресте rus_verbs:запечься{}, // запечься на костре rus_verbs:застилать{}, // застилать на балконе rus_verbs:сыскаться{}, // сыскаться на огороде rus_verbs:разориться{}, // разориться на продаже спичек rus_verbs:переделать{}, // переделать на станке rus_verbs:разъяснять{}, // разъяснять на страницах газеты rus_verbs:поседеть{}, // поседеть на висках rus_verbs:протащить{}, // протащить на спине rus_verbs:осуществиться{}, // осуществиться на деле rus_verbs:селиться{}, // селиться на окраине rus_verbs:оплачивать{}, // оплачивать на первой кассе rus_verbs:переворачивать{}, // переворачивать на сковородке rus_verbs:упражняться{}, // упражняться на батуте rus_verbs:испробовать{}, // испробовать на себе rus_verbs:разгладиться{}, // разгладиться на спине rus_verbs:рисоваться{}, // рисоваться на стекле rus_verbs:продрогнуть{}, // продрогнуть на морозе rus_verbs:пометить{}, // пометить на доске rus_verbs:приютить{}, // приютить на чердаке rus_verbs:избирать{}, // избирать на первых свободных выборах rus_verbs:затеваться{}, // затеваться на матче rus_verbs:уплывать{}, // уплывать на катере rus_verbs:замерцать{}, // замерцать на рекламном щите rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне rus_verbs:запираться{}, // запираться на чердаке rus_verbs:загубить{}, // загубить на корню rus_verbs:развеяться{}, // развеяться на природе rus_verbs:съезжаться{}, // съезжаться на лимузинах rus_verbs:потанцевать{}, // потанцевать на могиле rus_verbs:дохнуть{}, // дохнуть на солнце rus_verbs:припарковаться{}, // припарковаться на газоне rus_verbs:отхватить{}, // отхватить на распродаже rus_verbs:остывать{}, // остывать на улице rus_verbs:переваривать{}, // переваривать на высокой ветке rus_verbs:подвесить{}, // подвесить на веревке rus_verbs:хвастать{}, // хвастать на работе rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая rus_verbs:разлечься{}, // разлечься на полу rus_verbs:очертить{}, // очертить на полу rus_verbs:председательствовать{}, // председательствовать на собрании rus_verbs:сконфузиться{}, // сконфузиться на сцене rus_verbs:выявляться{}, // выявляться на ринге rus_verbs:крутануться{}, // крутануться на заднем колесе rus_verbs:караулить{}, // караулить на входе rus_verbs:перечислять{}, // перечислять на пальцах rus_verbs:обрабатывать{}, // обрабатывать на станке rus_verbs:настигать{}, // настигать на берегу rus_verbs:разгуливать{}, // разгуливать на берегу rus_verbs:насиловать{}, // насиловать на пляже rus_verbs:поредеть{}, // поредеть на макушке rus_verbs:учитывать{}, // учитывать на балансе rus_verbs:зарождаться{}, // зарождаться на большой глубине rus_verbs:распространять{}, // распространять на сайтах rus_verbs:пировать{}, // пировать на вершине холма rus_verbs:начертать{}, // начертать на стене rus_verbs:расцветать{}, // расцветать на подоконнике rus_verbs:умнеть{}, // умнеть на глазах rus_verbs:царствовать{}, // царствовать на окраине rus_verbs:закрутиться{}, // закрутиться на работе rus_verbs:отработать{}, // отработать на шахте rus_verbs:полечь{}, // полечь на поле брани rus_verbs:щебетать{}, // щебетать на ветке rus_verbs:подчеркиваться{}, // подчеркиваться на сайте rus_verbs:посеять{}, // посеять на другом поле rus_verbs:замечаться{}, // замечаться на пастбище rus_verbs:просчитать{}, // просчитать на пальцах rus_verbs:голосовать{}, // голосовать на трассе rus_verbs:маяться{}, // маяться на пляже rus_verbs:сколотить{}, // сколотить на службе rus_verbs:обретаться{}, // обретаться на чужбине rus_verbs:обливаться{}, // обливаться на улице rus_verbs:катать{}, // катать на лошадке rus_verbs:припрятать{}, // припрятать на теле rus_verbs:запаниковать{}, // запаниковать на экзамене инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете деепричастие:слетав{}, rus_verbs:срубить{}, // срубить денег на спекуляциях rus_verbs:зажигаться{}, // зажигаться на улице rus_verbs:жарить{}, // жарить на углях rus_verbs:накапливаться{}, // накапливаться на счету rus_verbs:распуститься{}, // распуститься на грядке rus_verbs:рассаживаться{}, // рассаживаться на местах rus_verbs:странствовать{}, // странствовать на лошади rus_verbs:осматриваться{}, // осматриваться на месте rus_verbs:разворачивать{}, // разворачивать на завоеванной территории rus_verbs:согревать{}, // согревать на вершине горы rus_verbs:заскучать{}, // заскучать на вахте rus_verbs:перекусить{}, // перекусить на бегу rus_verbs:приплыть{}, // приплыть на тримаране rus_verbs:зажигать{}, // зажигать на танцах rus_verbs:закопать{}, // закопать на поляне rus_verbs:стирать{}, // стирать на берегу rus_verbs:подстерегать{}, // подстерегать на подходе rus_verbs:погулять{}, // погулять на свадьбе rus_verbs:огласить{}, // огласить на митинге rus_verbs:разбогатеть{}, // разбогатеть на прииске rus_verbs:грохотать{}, // грохотать на чердаке rus_verbs:расположить{}, // расположить на границе rus_verbs:реализоваться{}, // реализоваться на новой работе rus_verbs:застывать{}, // застывать на морозе rus_verbs:запечатлеть{}, // запечатлеть на пленке rus_verbs:тренироваться{}, // тренироваться на манекене rus_verbs:поспорить{}, // поспорить на совещании rus_verbs:затягивать{}, // затягивать на поясе rus_verbs:зиждиться{}, // зиждиться на твердой основе rus_verbs:построиться{}, // построиться на песке rus_verbs:надрываться{}, // надрываться на работе rus_verbs:закипать{}, // закипать на плите rus_verbs:затонуть{}, // затонуть на мелководье rus_verbs:побыть{}, // побыть на фазенде rus_verbs:сгорать{}, // сгорать на солнце инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице деепричастие:пописав{ aux stress="поп^исав" }, rus_verbs:подраться{}, // подраться на сцене rus_verbs:заправить{}, // заправить на последней заправке rus_verbs:обозначаться{}, // обозначаться на карте rus_verbs:просиживать{}, // просиживать на берегу rus_verbs:начертить{}, // начертить на листке rus_verbs:тормозить{}, // тормозить на льду rus_verbs:затевать{}, // затевать на космической базе rus_verbs:задерживать{}, // задерживать на таможне rus_verbs:прилетать{}, // прилетать на частном самолете rus_verbs:полулежать{}, // полулежать на травке rus_verbs:ерзать{}, // ерзать на табуретке rus_verbs:покопаться{}, // покопаться на складе rus_verbs:подвезти{}, // подвезти на машине rus_verbs:полежать{}, // полежать на водном матрасе rus_verbs:стыть{}, // стыть на улице rus_verbs:стынуть{}, // стынуть на улице rus_verbs:скреститься{}, // скреститься на груди rus_verbs:припарковать{}, // припарковать на стоянке rus_verbs:здороваться{}, // здороваться на кафедре rus_verbs:нацарапать{}, // нацарапать на парте rus_verbs:откопать{}, // откопать на поляне rus_verbs:смастерить{}, // смастерить на коленках rus_verbs:довезти{}, // довезти на машине rus_verbs:избивать{}, // избивать на крыше rus_verbs:сварить{}, // сварить на костре rus_verbs:истребить{}, // истребить на корню rus_verbs:раскопать{}, // раскопать на болоте rus_verbs:попить{}, // попить на кухне rus_verbs:заправлять{}, // заправлять на базе rus_verbs:кушать{}, // кушать на кухне rus_verbs:замолкать{}, // замолкать на половине фразы rus_verbs:измеряться{}, // измеряться на весах rus_verbs:сбываться{}, // сбываться на самом деле rus_verbs:изображаться{}, // изображается на сцене rus_verbs:фиксировать{}, // фиксировать на данной высоте rus_verbs:ослаблять{}, // ослаблять на шее rus_verbs:зреть{}, // зреть на грядке rus_verbs:зеленеть{}, // зеленеть на грядке rus_verbs:критиковать{}, // критиковать на страницах газеты rus_verbs:облететь{}, // облететь на самолете rus_verbs:заразиться{}, // заразиться на работе rus_verbs:рассеять{}, // рассеять на территории rus_verbs:печься{}, // печься на костре rus_verbs:поспать{}, // поспать на земле rus_verbs:сплетаться{}, // сплетаться на макушке rus_verbs:удерживаться{}, // удерживаться на расстоянии rus_verbs:помешаться{}, // помешаться на чистоте rus_verbs:ликвидировать{}, // ликвидировать на полигоне rus_verbs:проваляться{}, // проваляться на диване rus_verbs:лечиться{}, // лечиться на дому rus_verbs:обработать{}, // обработать на станке rus_verbs:защелкнуть{}, // защелкнуть на руках rus_verbs:разносить{}, // разносить на одежде rus_verbs:чесать{}, // чесать на груди rus_verbs:наладить{}, // наладить на конвейере выпуск rus_verbs:отряхнуться{}, // отряхнуться на улице rus_verbs:разыгрываться{}, // разыгрываться на скачках rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях rus_verbs:греться{}, // греться на вокзале rus_verbs:засидеться{}, // засидеться на одном месте rus_verbs:материализоваться{}, // материализоваться на границе rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин rus_verbs:перевозить{}, // перевозить на платформе rus_verbs:поиграть{}, // поиграть на скрипке rus_verbs:потоптаться{}, // потоптаться на одном месте rus_verbs:переправиться{}, // переправиться на плоту rus_verbs:забрезжить{}, // забрезжить на горизонте rus_verbs:завывать{}, // завывать на опушке rus_verbs:заваривать{}, // заваривать на кухоньке rus_verbs:перемещаться{}, // перемещаться на спасательном плоту инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке rus_verbs:праздновать{}, // праздновать на улицах rus_verbs:обучить{}, // обучить на корте rus_verbs:орудовать{}, // орудовать на складе rus_verbs:подрасти{}, // подрасти на глядке rus_verbs:шелестеть{}, // шелестеть на ветру rus_verbs:раздеваться{}, // раздеваться на публике rus_verbs:пообедать{}, // пообедать на газоне rus_verbs:жрать{}, // жрать на помойке rus_verbs:исполняться{}, // исполняться на флейте rus_verbs:похолодать{}, // похолодать на улице rus_verbs:гнить{}, // гнить на каторге rus_verbs:прослушать{}, // прослушать на концерте rus_verbs:совещаться{}, // совещаться на заседании rus_verbs:покачивать{}, // покачивать на волнах rus_verbs:отсидеть{}, // отсидеть на гаупвахте rus_verbs:формировать{}, // формировать на секретной базе rus_verbs:захрапеть{}, // захрапеть на кровати rus_verbs:объехать{}, // объехать на попутке rus_verbs:поселить{}, // поселить на верхних этажах rus_verbs:заворочаться{}, // заворочаться на сене rus_verbs:напрятать{}, // напрятать на теле rus_verbs:очухаться{}, // очухаться на земле rus_verbs:полистать{}, // полистать на досуге rus_verbs:завертеть{}, // завертеть на шесте rus_verbs:печатать{}, // печатать на ноуте rus_verbs:отыскаться{}, // отыскаться на складе rus_verbs:зафиксировать{}, // зафиксировать на пленке rus_verbs:расстилаться{}, // расстилаться на столе rus_verbs:заместить{}, // заместить на посту rus_verbs:угасать{}, // угасать на неуправляемом корабле rus_verbs:сразить{}, // сразить на ринге rus_verbs:расплываться{}, // расплываться на жаре rus_verbs:сосчитать{}, // сосчитать на пальцах rus_verbs:сгуститься{}, // сгуститься на небольшой высоте rus_verbs:цитировать{}, // цитировать на плите rus_verbs:ориентироваться{}, // ориентироваться на местности rus_verbs:расширить{}, // расширить на другом конце rus_verbs:обтереть{}, // обтереть на стоянке rus_verbs:подстрелить{}, // подстрелить на охоте rus_verbs:растереть{}, // растереть на твердой поверхности rus_verbs:подавлять{}, // подавлять на первом этапе rus_verbs:смешиваться{}, // смешиваться на поверхности // инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте // деепричастие:вычитав{}, rus_verbs:сократиться{}, // сократиться на втором этапе rus_verbs:занервничать{}, // занервничать на экзамене rus_verbs:соприкоснуться{}, // соприкоснуться на трассе rus_verbs:обозначить{}, // обозначить на плане rus_verbs:обучаться{}, // обучаться на производстве rus_verbs:снизиться{}, // снизиться на большой высоте rus_verbs:простудиться{}, // простудиться на ветру rus_verbs:поддерживаться{}, // поддерживается на встрече rus_verbs:уплыть{}, // уплыть на лодочке rus_verbs:резвиться{}, // резвиться на песочке rus_verbs:поерзать{}, // поерзать на скамеечке rus_verbs:похвастаться{}, // похвастаться на встрече rus_verbs:знакомиться{}, // знакомиться на уроке rus_verbs:проплывать{}, // проплывать на катере rus_verbs:засесть{}, // засесть на чердаке rus_verbs:подцепить{}, // подцепить на дискотеке rus_verbs:обыскать{}, // обыскать на входе rus_verbs:оправдаться{}, // оправдаться на суде rus_verbs:раскрываться{}, // раскрываться на сцене rus_verbs:одеваться{}, // одеваться на вещевом рынке rus_verbs:засветиться{}, // засветиться на фотографиях rus_verbs:употребляться{}, // употребляться на птицефабриках rus_verbs:грабить{}, // грабить на пустыре rus_verbs:гонять{}, // гонять на повышенных оборотах rus_verbs:развеваться{}, // развеваться на древке rus_verbs:основываться{}, // основываться на безусловных фактах rus_verbs:допрашивать{}, // допрашивать на базе rus_verbs:проработать{}, // проработать на стройке rus_verbs:сосредоточить{}, // сосредоточить на месте rus_verbs:сочинять{}, // сочинять на ходу rus_verbs:ползать{}, // ползать на камне rus_verbs:раскинуться{}, // раскинуться на пустыре rus_verbs:уставать{}, // уставать на работе rus_verbs:укрепить{}, // укрепить на конце rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь rus_verbs:одобрять{}, // одобрять на словах rus_verbs:приговорить{}, // приговорить на заседании тройки rus_verbs:чернеть{}, // чернеть на свету rus_verbs:гнуть{}, // гнуть на станке rus_verbs:размещаться{}, // размещаться на бирже rus_verbs:соорудить{}, // соорудить на даче rus_verbs:пастись{}, // пастись на лугу rus_verbs:формироваться{}, // формироваться на дне rus_verbs:таить{}, // таить на дне rus_verbs:приостановиться{}, // приостановиться на середине rus_verbs:топтаться{}, // топтаться на месте rus_verbs:громить{}, // громить на подступах rus_verbs:вычислить{}, // вычислить на бумажке rus_verbs:заказывать{}, // заказывать на сайте rus_verbs:осуществить{}, // осуществить на практике rus_verbs:обосноваться{}, // обосноваться на верхушке rus_verbs:пытать{}, // пытать на электрическом стуле rus_verbs:совершиться{}, // совершиться на заседании rus_verbs:свернуться{}, // свернуться на медленном огне rus_verbs:пролетать{}, // пролетать на дельтаплане rus_verbs:сбыться{}, // сбыться на самом деле rus_verbs:разговориться{}, // разговориться на уроке rus_verbs:разворачиваться{}, // разворачиваться на перекрестке rus_verbs:преподнести{}, // преподнести на блюдечке rus_verbs:напечатать{}, // напечатать на лазернике rus_verbs:прорвать{}, // прорвать на периферии rus_verbs:раскачиваться{}, // раскачиваться на доске rus_verbs:задерживаться{}, // задерживаться на старте rus_verbs:угощать{}, // угощать на вечеринке rus_verbs:шарить{}, // шарить на столе rus_verbs:увеличивать{}, // увеличивать на первом этапе rus_verbs:рехнуться{}, // рехнуться на старости лет rus_verbs:расцвести{}, // расцвести на грядке rus_verbs:закипеть{}, // закипеть на плите rus_verbs:подлететь{}, // подлететь на параплане rus_verbs:рыться{}, // рыться на свалке rus_verbs:добираться{}, // добираться на попутках rus_verbs:продержаться{}, // продержаться на вершине rus_verbs:разыскивать{}, // разыскивать на выставках rus_verbs:освобождать{}, // освобождать на заседании rus_verbs:передвигаться{}, // передвигаться на самокате rus_verbs:проявиться{}, // проявиться на свету rus_verbs:заскользить{}, // заскользить на льду rus_verbs:пересказать{}, // пересказать на сцене студенческого театра rus_verbs:протестовать{}, // протестовать на улице rus_verbs:указываться{}, // указываться на табличках rus_verbs:прискакать{}, // прискакать на лошадке rus_verbs:копошиться{}, // копошиться на свежем воздухе rus_verbs:подсчитать{}, // подсчитать на бумажке rus_verbs:разволноваться{}, // разволноваться на экзамене rus_verbs:завертеться{}, // завертеться на полу rus_verbs:ознакомиться{}, // ознакомиться на ходу rus_verbs:ржать{}, // ржать на уроке rus_verbs:раскинуть{}, // раскинуть на грядках rus_verbs:разгромить{}, // разгромить на ринге rus_verbs:подслушать{}, // подслушать на совещании rus_verbs:описываться{}, // описываться на страницах книги rus_verbs:качаться{}, // качаться на стуле rus_verbs:усилить{}, // усилить на флангах rus_verbs:набросать{}, // набросать на клочке картона rus_verbs:расстреливать{}, // расстреливать на подходе rus_verbs:запрыгать{}, // запрыгать на одной ноге rus_verbs:сыскать{}, // сыскать на чужбине rus_verbs:подтвердиться{}, // подтвердиться на практике rus_verbs:плескаться{}, // плескаться на мелководье rus_verbs:расширяться{}, // расширяться на конце rus_verbs:подержать{}, // подержать на солнце rus_verbs:планироваться{}, // планироваться на общем собрании rus_verbs:сгинуть{}, // сгинуть на чужбине rus_verbs:замкнуться{}, // замкнуться на точке rus_verbs:закачаться{}, // закачаться на ветру rus_verbs:перечитывать{}, // перечитывать на ходу rus_verbs:перелететь{}, // перелететь на дельтаплане rus_verbs:оживать{}, // оживать на солнце rus_verbs:женить{}, // женить на богатой невесте rus_verbs:заглохнуть{}, // заглохнуть на старте rus_verbs:копаться{}, // копаться на полу rus_verbs:развлекаться{}, // развлекаться на дискотеке rus_verbs:печататься{}, // печататься на струйном принтере rus_verbs:обрываться{}, // обрываться на полуслове rus_verbs:ускакать{}, // ускакать на лошадке rus_verbs:подписывать{}, // подписывать на столе rus_verbs:добывать{}, // добывать на выработке rus_verbs:скопиться{}, // скопиться на выходе rus_verbs:повстречать{}, // повстречать на пути rus_verbs:поцеловаться{}, // поцеловаться на площади rus_verbs:растянуть{}, // растянуть на столе rus_verbs:подаваться{}, // подаваться на благотворительном обеде rus_verbs:повстречаться{}, // повстречаться на митинге rus_verbs:примоститься{}, // примоститься на ступеньках rus_verbs:отразить{}, // отразить на страницах доклада rus_verbs:пояснять{}, // пояснять на страницах приложения rus_verbs:накормить{}, // накормить на кухне rus_verbs:поужинать{}, // поужинать на веранде инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге деепричастие:спев{}, инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить на мелководье rus_verbs:освоить{}, // освоить на практике rus_verbs:распластаться{}, // распластаться на травке rus_verbs:отплыть{}, // отплыть на старом каяке rus_verbs:улетать{}, // улетать на любом самолете rus_verbs:отстаивать{}, // отстаивать на корте rus_verbs:осуждать{}, // осуждать на словах rus_verbs:переговорить{}, // переговорить на обеде rus_verbs:укрыть{}, // укрыть на чердаке rus_verbs:томиться{}, // томиться на привязи rus_verbs:сжигать{}, // сжигать на полигоне rus_verbs:позавтракать{}, // позавтракать на лоне природы rus_verbs:функционировать{}, // функционирует на солнечной энергии rus_verbs:разместить{}, // разместить на сайте rus_verbs:пронести{}, // пронести на теле rus_verbs:нашарить{}, // нашарить на столе rus_verbs:корчиться{}, // корчиться на полу rus_verbs:распознать{}, // распознать на снимке rus_verbs:повеситься{}, // повеситься на шнуре rus_verbs:обозначиться{}, // обозначиться на картах rus_verbs:оступиться{}, // оступиться на скользком льду rus_verbs:подносить{}, // подносить на блюдечке rus_verbs:расстелить{}, // расстелить на газоне rus_verbs:обсуждаться{}, // обсуждаться на собрании rus_verbs:расписаться{}, // расписаться на бланке rus_verbs:плестись{}, // плестись на привязи rus_verbs:объявиться{}, // объявиться на сцене rus_verbs:повышаться{}, // повышаться на первом датчике rus_verbs:разрабатывать{}, // разрабатывать на заводе rus_verbs:прерывать{}, // прерывать на середине rus_verbs:каяться{}, // каяться на публике rus_verbs:освоиться{}, // освоиться на лошади rus_verbs:подплыть{}, // подплыть на плоту rus_verbs:оскорбить{}, // оскорбить на митинге rus_verbs:торжествовать{}, // торжествовать на пьедестале rus_verbs:поправлять{}, // поправлять на одежде rus_verbs:отражать{}, // отражать на картине rus_verbs:дремать{}, // дремать на кушетке rus_verbs:применяться{}, // применяться на производстве стали rus_verbs:поражать{}, // поражать на большой дистанции rus_verbs:расстрелять{}, // расстрелять на окраине хутора rus_verbs:рассчитать{}, // рассчитать на калькуляторе rus_verbs:записывать{}, // записывать на ленте rus_verbs:перебирать{}, // перебирать на ладони rus_verbs:разбиться{}, // разбиться на катере rus_verbs:поискать{}, // поискать на ферме rus_verbs:прятать{}, // прятать на заброшенном складе rus_verbs:пропеть{}, // пропеть на эстраде rus_verbs:замелькать{}, // замелькать на экране rus_verbs:грустить{}, // грустить на веранде rus_verbs:крутить{}, // крутить на оси rus_verbs:подготовить{}, // подготовить на конспиративной квартире rus_verbs:различать{}, // различать на картинке rus_verbs:киснуть{}, // киснуть на чужбине rus_verbs:оборваться{}, // оборваться на полуслове rus_verbs:запутаться{}, // запутаться на простейшем тесте rus_verbs:общаться{}, // общаться на уроке rus_verbs:производиться{}, // производиться на фабрике rus_verbs:сочинить{}, // сочинить на досуге rus_verbs:давить{}, // давить на лице rus_verbs:разработать{}, // разработать на секретном предприятии rus_verbs:качать{}, // качать на качелях rus_verbs:тушить{}, // тушить на крыше пожар rus_verbs:охранять{}, // охранять на территории базы rus_verbs:приметить{}, // приметить на взгорке rus_verbs:скрыть{}, // скрыть на теле rus_verbs:удерживать{}, // удерживать на руке rus_verbs:усвоить{}, // усвоить на уроке rus_verbs:растаять{}, // растаять на солнечной стороне rus_verbs:красоваться{}, // красоваться на виду rus_verbs:сохраняться{}, // сохраняться на холоде rus_verbs:лечить{}, // лечить на дому rus_verbs:прокатиться{}, // прокатиться на уницикле rus_verbs:договариваться{}, // договариваться на нейтральной территории rus_verbs:качнуться{}, // качнуться на одной ноге rus_verbs:опубликовать{}, // опубликовать на сайте rus_verbs:отражаться{}, // отражаться на поверхности воды rus_verbs:обедать{}, // обедать на веранде rus_verbs:посидеть{}, // посидеть на лавочке rus_verbs:сообщаться{}, // сообщаться на официальном сайте rus_verbs:свершиться{}, // свершиться на заседании rus_verbs:ночевать{}, // ночевать на даче rus_verbs:темнеть{}, // темнеть на свету rus_verbs:гибнуть{}, // гибнуть на территории полигона rus_verbs:усиливаться{}, // усиливаться на территории округа rus_verbs:проживать{}, // проживать на даче rus_verbs:исследовать{}, // исследовать на большой глубине rus_verbs:обитать{}, // обитать на громадной глубине rus_verbs:сталкиваться{}, // сталкиваться на большой высоте rus_verbs:таиться{}, // таиться на большой глубине rus_verbs:спасать{}, // спасать на пожаре rus_verbs:сказываться{}, // сказываться на общем результате rus_verbs:заблудиться{}, // заблудиться на стройке rus_verbs:пошарить{}, // пошарить на полках rus_verbs:планировать{}, // планировать на бумаге rus_verbs:ранить{}, // ранить на полигоне rus_verbs:хлопать{}, // хлопать на сцене rus_verbs:основать{}, // основать на горе новый монастырь rus_verbs:отбить{}, // отбить на столе rus_verbs:отрицать{}, // отрицать на заседании комиссии rus_verbs:устоять{}, // устоять на ногах rus_verbs:отзываться{}, // отзываться на страницах отчёта rus_verbs:притормозить{}, // притормозить на обочине rus_verbs:читаться{}, // читаться на лице rus_verbs:заиграть{}, // заиграть на саксофоне rus_verbs:зависнуть{}, // зависнуть на игровой площадке rus_verbs:сознаться{}, // сознаться на допросе rus_verbs:выясняться{}, // выясняться на очной ставке rus_verbs:наводить{}, // наводить на столе порядок rus_verbs:покоиться{}, // покоиться на кладбище rus_verbs:значиться{}, // значиться на бейджике rus_verbs:съехать{}, // съехать на санках rus_verbs:познакомить{}, // познакомить на свадьбе rus_verbs:завязать{}, // завязать на спине rus_verbs:грохнуть{}, // грохнуть на площади rus_verbs:разъехаться{}, // разъехаться на узкой дороге rus_verbs:столпиться{}, // столпиться на крыльце rus_verbs:порыться{}, // порыться на полках rus_verbs:ослабить{}, // ослабить на шее rus_verbs:оправдывать{}, // оправдывать на суде rus_verbs:обнаруживаться{}, // обнаруживаться на складе rus_verbs:спастись{}, // спастись на дереве rus_verbs:прерваться{}, // прерваться на полуслове rus_verbs:строиться{}, // строиться на пустыре rus_verbs:познать{}, // познать на практике rus_verbs:путешествовать{}, // путешествовать на поезде rus_verbs:побеждать{}, // побеждать на ринге rus_verbs:рассматриваться{}, // рассматриваться на заседании rus_verbs:продаваться{}, // продаваться на открытом рынке rus_verbs:разместиться{}, // разместиться на базе rus_verbs:завыть{}, // завыть на холме rus_verbs:настигнуть{}, // настигнуть на окраине rus_verbs:укрыться{}, // укрыться на чердаке rus_verbs:расплакаться{}, // расплакаться на заседании комиссии rus_verbs:заканчивать{}, // заканчивать на последнем задании rus_verbs:пролежать{}, // пролежать на столе rus_verbs:громоздиться{}, // громоздиться на полу rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе rus_verbs:поскользнуться{}, // поскользнуться на льду rus_verbs:таскать{}, // таскать на спине rus_verbs:просматривать{}, // просматривать на сайте rus_verbs:обдумать{}, // обдумать на досуге rus_verbs:гадать{}, // гадать на кофейной гуще rus_verbs:останавливать{}, // останавливать на выходе rus_verbs:обозначать{}, // обозначать на странице rus_verbs:долететь{}, // долететь на спортивном байке rus_verbs:тесниться{}, // тесниться на чердачке rus_verbs:хоронить{}, // хоронить на частном кладбище rus_verbs:установиться{}, // установиться на юге rus_verbs:прикидывать{}, // прикидывать на клочке бумаги rus_verbs:затаиться{}, // затаиться на дереве rus_verbs:раздобыть{}, // раздобыть на складе rus_verbs:перебросить{}, // перебросить на вертолетах rus_verbs:захватывать{}, // захватывать на базе rus_verbs:сказаться{}, // сказаться на итоговых оценках rus_verbs:покачиваться{}, // покачиваться на волнах rus_verbs:крутиться{}, // крутиться на кухне rus_verbs:помещаться{}, // помещаться на полке rus_verbs:питаться{}, // питаться на помойке rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле rus_verbs:кататься{}, // кататься на велике rus_verbs:поработать{}, // поработать на стройке rus_verbs:ограбить{}, // ограбить на пустыре rus_verbs:зарабатывать{}, // зарабатывать на бирже rus_verbs:преуспеть{}, // преуспеть на ниве искусства rus_verbs:заерзать{}, // заерзать на стуле rus_verbs:разъяснить{}, // разъяснить на полях rus_verbs:отчеканить{}, // отчеканить на медной пластине rus_verbs:торговать{}, // торговать на рынке rus_verbs:поколебаться{}, // поколебаться на пороге rus_verbs:прикинуть{}, // прикинуть на бумажке rus_verbs:рассечь{}, // рассечь на тупом конце rus_verbs:посмеяться{}, // посмеяться на переменке rus_verbs:остыть{}, // остыть на морозном воздухе rus_verbs:запереться{}, // запереться на чердаке rus_verbs:обогнать{}, // обогнать на повороте rus_verbs:подтянуться{}, // подтянуться на турнике rus_verbs:привозить{}, // привозить на машине rus_verbs:подбирать{}, // подбирать на полу rus_verbs:уничтожать{}, // уничтожать на подходе rus_verbs:притаиться{}, // притаиться на вершине rus_verbs:плясать{}, // плясать на костях rus_verbs:поджидать{}, // поджидать на вокзале rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!) rus_verbs:смениться{}, // смениться на посту rus_verbs:посчитать{}, // посчитать на пальцах rus_verbs:прицелиться{}, // прицелиться на бегу rus_verbs:нарисовать{}, // нарисовать на стене rus_verbs:прыгать{}, // прыгать на сцене rus_verbs:повертеть{}, // повертеть на пальце rus_verbs:попрощаться{}, // попрощаться на панихиде инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване rus_verbs:разобрать{}, // разобрать на столе rus_verbs:помереть{}, // помереть на чужбине rus_verbs:различить{}, // различить на нечеткой фотографии rus_verbs:рисовать{}, // рисовать на доске rus_verbs:проследить{}, // проследить на экране rus_verbs:задремать{}, // задремать на диване rus_verbs:ругаться{}, // ругаться на людях rus_verbs:сгореть{}, // сгореть на работе rus_verbs:зазвучать{}, // зазвучать на коротких волнах rus_verbs:задохнуться{}, // задохнуться на вершине горы rus_verbs:порождать{}, // порождать на поверхности небольшую рябь rus_verbs:отдыхать{}, // отдыхать на курорте rus_verbs:образовать{}, // образовать на дне толстый слой rus_verbs:поправиться{}, // поправиться на дармовых харчах rus_verbs:отмечать{}, // отмечать на календаре rus_verbs:реять{}, // реять на флагштоке rus_verbs:ползти{}, // ползти на коленях rus_verbs:продавать{}, // продавать на аукционе rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче rus_verbs:рыскать{}, // мышки рыскали на кухне rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы rus_verbs:напасть{}, // напасть на территории другого государства rus_verbs:издать{}, // издать на западе rus_verbs:оставаться{}, // оставаться на страже порядка rus_verbs:появиться{}, // наконец появиться на экране rus_verbs:лежать{}, // лежать на столе rus_verbs:ждать{}, // ждать на берегу инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге глагол:писать{aux stress="пис^ать"}, rus_verbs:оказываться{}, // оказываться на полу rus_verbs:поставить{}, // поставить на столе rus_verbs:держать{}, // держать на крючке rus_verbs:выходить{}, // выходить на остановке rus_verbs:заговорить{}, // заговорить на китайском языке rus_verbs:ожидать{}, // ожидать на стоянке rus_verbs:закричать{}, // закричал на минарете муэдзин rus_verbs:простоять{}, // простоять на посту rus_verbs:продолжить{}, // продолжить на первом этаже rus_verbs:ощутить{}, // ощутить на себе влияние кризиса rus_verbs:состоять{}, // состоять на учете rus_verbs:готовиться{}, инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте глагол:акклиматизироваться{вид:несоверш}, rus_verbs:арестовать{}, // грабители были арестованы на месте преступления rus_verbs:схватить{}, // грабители были схвачены на месте преступления инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе глагол:атаковать{ вид:соверш }, прилагательное:атакованный{ вид:соверш }, прилагательное:атаковавший{ вид:соверш }, rus_verbs:базировать{}, // установка будет базирована на границе rus_verbs:базироваться{}, // установка базируется на границе rus_verbs:барахтаться{}, // дети барахтались на мелководье rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке rus_verbs:бренчать{}, // парень что-то бренчал на гитаре rus_verbs:бренькать{}, // парень что-то бренькает на гитаре rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории. rus_verbs:буксовать{}, // Колеса буксуют на льду rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле rus_verbs:взвести{}, // Боец взвел на оружии предохранитель rus_verbs:вилять{}, // Машина сильно виляла на дороге rus_verbs:висеть{}, // Яблоко висит на ветке rus_verbs:возлежать{}, // возлежать на лежанке rus_verbs:подниматься{}, // Мы поднимаемся на лифте rus_verbs:подняться{}, // Мы поднимемся на лифте rus_verbs:восседать{}, // Коля восседает на лошади rus_verbs:воссиять{}, // Луна воссияла на небе rus_verbs:воцариться{}, // Мир воцарился на всей земле rus_verbs:воцаряться{}, // Мир воцаряется на всей земле rus_verbs:вращать{}, // вращать на поясе rus_verbs:вращаться{}, // вращаться на поясе rus_verbs:встретить{}, // встретить друга на улице rus_verbs:встретиться{}, // встретиться на занятиях rus_verbs:встречать{}, // встречать на занятиях rus_verbs:въебывать{}, // въебывать на работе rus_verbs:въезжать{}, // въезжать на автомобиле rus_verbs:въехать{}, // въехать на автомобиле rus_verbs:выгорать{}, // ткань выгорает на солнце rus_verbs:выгореть{}, // ткань выгорела на солнце rus_verbs:выгравировать{}, // выгравировать на табличке надпись rus_verbs:выжить{}, // выжить на необитаемом острове rus_verbs:вылежаться{}, // помидоры вылежались на солнце rus_verbs:вылеживаться{}, // вылеживаться на солнце rus_verbs:выместить{}, // выместить на ком-то злобу rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение rus_verbs:вымещаться{}, // вымещаться на ком-то rus_verbs:выращивать{}, // выращивать на грядке помидоры rus_verbs:выращиваться{}, // выращиваться на грядке инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись глагол:вырезать{вид:соверш}, инфинитив:вырезать{вид:несоверш}, глагол:вырезать{вид:несоверш}, rus_verbs:вырисоваться{}, // вырисоваться на графике rus_verbs:вырисовываться{}, // вырисовываться на графике rus_verbs:высаживать{}, // высаживать на необитаемом острове rus_verbs:высаживаться{}, // высаживаться на острове rus_verbs:высвечивать{}, // высвечивать на дисплее температуру rus_verbs:высвечиваться{}, // высвечиваться на дисплее rus_verbs:выстроить{}, // выстроить на фундаменте rus_verbs:выстроиться{}, // выстроиться на плацу rus_verbs:выстудить{}, // выстудить на морозе rus_verbs:выстудиться{}, // выстудиться на морозе rus_verbs:выстужать{}, // выстужать на морозе rus_verbs:выстуживать{}, // выстуживать на морозе rus_verbs:выстуживаться{}, // выстуживаться на морозе rus_verbs:выстукать{}, // выстукать на клавиатуре rus_verbs:выстукивать{}, // выстукивать на клавиатуре rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре rus_verbs:выступать{}, // выступать на сцене rus_verbs:выступить{}, // выступить на сцене rus_verbs:выстучать{}, // выстучать на клавиатуре rus_verbs:выстывать{}, // выстывать на морозе rus_verbs:выстыть{}, // выстыть на морозе rus_verbs:вытатуировать{}, // вытатуировать на руке якорь rus_verbs:говорить{}, // говорить на повышенных тонах rus_verbs:заметить{}, // заметить на берегу rus_verbs:стоять{}, // твёрдо стоять на ногах rus_verbs:оказаться{}, // оказаться на передовой линии rus_verbs:почувствовать{}, // почувствовать на своей шкуре rus_verbs:остановиться{}, // остановиться на первом пункте rus_verbs:показаться{}, // показаться на горизонте rus_verbs:чувствовать{}, // чувствовать на своей шкуре rus_verbs:искать{}, // искать на открытом пространстве rus_verbs:иметься{}, // иметься на складе rus_verbs:клясться{}, // клясться на Коране rus_verbs:прервать{}, // прервать на полуслове rus_verbs:играть{}, // играть на чувствах rus_verbs:спуститься{}, // спуститься на парашюте rus_verbs:понадобиться{}, // понадобиться на экзамене rus_verbs:служить{}, // служить на флоте rus_verbs:подобрать{}, // подобрать на улице rus_verbs:появляться{}, // появляться на сцене rus_verbs:селить{}, // селить на чердаке rus_verbs:поймать{}, // поймать на границе rus_verbs:увидать{}, // увидать на опушке rus_verbs:подождать{}, // подождать на перроне rus_verbs:прочесть{}, // прочесть на полях rus_verbs:тонуть{}, // тонуть на мелководье rus_verbs:ощущать{}, // ощущать на коже rus_verbs:отметить{}, // отметить на полях rus_verbs:показывать{}, // показывать на графике rus_verbs:разговаривать{}, // разговаривать на иностранном языке rus_verbs:прочитать{}, // прочитать на сайте rus_verbs:попробовать{}, // попробовать на практике rus_verbs:замечать{}, // замечать на коже грязь rus_verbs:нести{}, // нести на плечах rus_verbs:носить{}, // носить на голове rus_verbs:гореть{}, // гореть на работе rus_verbs:застыть{}, // застыть на пороге инфинитив:жениться{ вид:соверш }, // жениться на королеве глагол:жениться{ вид:соверш }, прилагательное:женатый{}, прилагательное:женившийся{}, rus_verbs:спрятать{}, // спрятать на чердаке rus_verbs:развернуться{}, // развернуться на плацу rus_verbs:строить{}, // строить на песке rus_verbs:устроить{}, // устроить на даче тестральный вечер rus_verbs:настаивать{}, // настаивать на выполнении приказа rus_verbs:находить{}, // находить на берегу rus_verbs:мелькнуть{}, // мелькнуть на экране rus_verbs:очутиться{}, // очутиться на опушке леса инфинитив:использовать{вид:соверш}, // использовать на работе глагол:использовать{вид:соверш}, инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, прилагательное:использованный{}, прилагательное:использующий{}, прилагательное:использовавший{}, rus_verbs:лететь{}, // лететь на воздушном шаре rus_verbs:смеяться{}, // смеяться на сцене rus_verbs:ездить{}, // ездить на мопеде rus_verbs:заснуть{}, // заснуть на диване rus_verbs:застать{}, // застать на рабочем месте rus_verbs:очнуться{}, // очнуться на больничной койке rus_verbs:разглядеть{}, // разглядеть на фотографии rus_verbs:обойти{}, // обойти на вираже rus_verbs:удержаться{}, // удержаться на троне rus_verbs:побывать{}, // побывать на другой планете rus_verbs:заняться{}, // заняться на выходных делом rus_verbs:вянуть{}, // вянуть на солнце rus_verbs:постоять{}, // постоять на голове rus_verbs:приобрести{}, // приобрести на распродаже rus_verbs:попасться{}, // попасться на краже rus_verbs:продолжаться{}, // продолжаться на земле rus_verbs:открывать{}, // открывать на арене rus_verbs:создавать{}, // создавать на сцене rus_verbs:обсуждать{}, // обсуждать на кухне rus_verbs:отыскать{}, // отыскать на полу rus_verbs:уснуть{}, // уснуть на диване rus_verbs:задержаться{}, // задержаться на работе rus_verbs:курить{}, // курить на свежем воздухе rus_verbs:приподняться{}, // приподняться на локтях rus_verbs:установить{}, // установить на вершине rus_verbs:запереть{}, // запереть на балконе rus_verbs:синеть{}, // синеть на воздухе rus_verbs:убивать{}, // убивать на нейтральной территории rus_verbs:скрываться{}, // скрываться на даче rus_verbs:родить{}, // родить на полу rus_verbs:описать{}, // описать на страницах книги rus_verbs:перехватить{}, // перехватить на подлете rus_verbs:скрывать{}, // скрывать на даче rus_verbs:сменить{}, // сменить на посту rus_verbs:мелькать{}, // мелькать на экране rus_verbs:присутствовать{}, // присутствовать на мероприятии rus_verbs:украсть{}, // украсть на рынке rus_verbs:победить{}, // победить на ринге rus_verbs:упомянуть{}, // упомянуть на страницах романа rus_verbs:плыть{}, // плыть на старой лодке rus_verbs:повиснуть{}, // повиснуть на перекладине rus_verbs:нащупать{}, // нащупать на дне rus_verbs:затихнуть{}, // затихнуть на дне rus_verbs:построить{}, // построить на участке rus_verbs:поддерживать{}, // поддерживать на поверхности rus_verbs:заработать{}, // заработать на бирже rus_verbs:провалиться{}, // провалиться на экзамене rus_verbs:сохранить{}, // сохранить на диске rus_verbs:располагаться{}, // располагаться на софе rus_verbs:поклясться{}, // поклясться на библии rus_verbs:сражаться{}, // сражаться на арене rus_verbs:спускаться{}, // спускаться на дельтаплане rus_verbs:уничтожить{}, // уничтожить на подступах rus_verbs:изучить{}, // изучить на практике rus_verbs:рождаться{}, // рождаться на праздниках rus_verbs:прилететь{}, // прилететь на самолете rus_verbs:догнать{}, // догнать на перекрестке rus_verbs:изобразить{}, // изобразить на бумаге rus_verbs:проехать{}, // проехать на тракторе rus_verbs:приготовить{}, // приготовить на масле rus_verbs:споткнуться{}, // споткнуться на полу rus_verbs:собирать{}, // собирать на берегу rus_verbs:отсутствовать{}, // отсутствовать на тусовке rus_verbs:приземлиться{}, // приземлиться на военном аэродроме rus_verbs:сыграть{}, // сыграть на трубе rus_verbs:прятаться{}, // прятаться на даче rus_verbs:спрятаться{}, // спрятаться на чердаке rus_verbs:провозгласить{}, // провозгласить на митинге rus_verbs:изложить{}, // изложить на бумаге rus_verbs:использоваться{}, // использоваться на практике rus_verbs:замяться{}, // замяться на входе rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота rus_verbs:сверкнуть{}, // сверкнуть на солнце rus_verbs:сверкать{}, // сверкать на свету rus_verbs:задержать{}, // задержать на митинге rus_verbs:осечься{}, // осечься на первом слове rus_verbs:хранить{}, // хранить на банковском счету rus_verbs:шутить{}, // шутить на уроке rus_verbs:кружиться{}, // кружиться на балу rus_verbs:чертить{}, // чертить на доске rus_verbs:отразиться{}, // отразиться на оценках rus_verbs:греть{}, // греть на солнце rus_verbs:рассуждать{}, // рассуждать на страницах своей книги rus_verbs:окружать{}, // окружать на острове rus_verbs:сопровождать{}, // сопровождать на охоте rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте rus_verbs:содержаться{}, // содержаться на приусадебном участке rus_verbs:поселиться{}, // поселиться на даче rus_verbs:запеть{}, // запеть на сцене инфинитив:провозить{ вид:несоверш }, // провозить на теле глагол:провозить{ вид:несоверш }, прилагательное:провезенный{}, прилагательное:провозивший{вид:несоверш}, прилагательное:провозящий{вид:несоверш}, деепричастие:провозя{}, rus_verbs:мочить{}, // мочить на месте rus_verbs:преследовать{}, // преследовать на территории другого штата rus_verbs:пролететь{}, // пролетел на параплане rus_verbs:драться{}, // драться на рапирах rus_verbs:просидеть{}, // просидеть на занятиях rus_verbs:убираться{}, // убираться на балконе rus_verbs:таять{}, // таять на солнце rus_verbs:проверять{}, // проверять на полиграфе rus_verbs:убеждать{}, // убеждать на примере rus_verbs:скользить{}, // скользить на льду rus_verbs:приобретать{}, // приобретать на распродаже rus_verbs:летать{}, // летать на метле rus_verbs:толпиться{}, // толпиться на перроне rus_verbs:плавать{}, // плавать на надувном матрасе rus_verbs:описывать{}, // описывать на страницах повести rus_verbs:пробыть{}, // пробыть на солнце слишком долго rus_verbs:застрять{}, // застрять на верхнем этаже rus_verbs:метаться{}, // метаться на полу rus_verbs:сжечь{}, // сжечь на костре rus_verbs:расслабиться{}, // расслабиться на кушетке rus_verbs:услыхать{}, // услыхать на рынке rus_verbs:удержать{}, // удержать на прежнем уровне rus_verbs:образоваться{}, // образоваться на дне rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа rus_verbs:уезжать{}, // уезжать на попутке rus_verbs:похоронить{}, // похоронить на закрытом кладбище rus_verbs:настоять{}, // настоять на пересмотре оценок rus_verbs:растянуться{}, // растянуться на горячем песке rus_verbs:покрутить{}, // покрутить на шесте rus_verbs:обнаружиться{}, // обнаружиться на болоте rus_verbs:гулять{}, // гулять на свадьбе rus_verbs:утонуть{}, // утонуть на курорте rus_verbs:храниться{}, // храниться на депозите rus_verbs:танцевать{}, // танцевать на свадьбе rus_verbs:трудиться{}, // трудиться на заводе инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати глагол:засыпать{переходность:непереходный вид:несоверш}, деепричастие:засыпая{переходность:непереходный вид:несоверш}, прилагательное:засыпавший{переходность:непереходный вид:несоверш}, прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках rus_verbs:сушить{}, // сушить на открытом воздухе rus_verbs:зашевелиться{}, // зашевелиться на чердаке rus_verbs:обдумывать{}, // обдумывать на досуге rus_verbs:докладывать{}, // докладывать на научной конференции rus_verbs:промелькнуть{}, // промелькнуть на экране // прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории прилагательное:написанный{}, // слово, написанное на заборе rus_verbs:умещаться{}, // компьютер, умещающийся на ладони rus_verbs:открыть{}, // книга, открытая на последней странице rus_verbs:спать{}, // йог, спящий на гвоздях rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте rus_verbs:отобразиться{}, // удивление, отобразившееся на лице rus_verbs:увидеть{}, // на полу я увидел чьи-то следы rus_verbs:видеть{}, // на полу я вижу чьи-то следы rus_verbs:оставить{}, // Мел оставил на доске белый след. rus_verbs:оставлять{}, // Мел оставляет на доске белый след. rus_verbs:встречаться{}, // встречаться на лекциях rus_verbs:познакомиться{}, // познакомиться на занятиях rus_verbs:устроиться{}, // она устроилась на кровати rus_verbs:ложиться{}, // ложись на полу rus_verbs:останавливаться{}, // останавливаться на достигнутом rus_verbs:спотыкаться{}, // спотыкаться на ровном месте rus_verbs:распечатать{}, // распечатать на бумаге rus_verbs:распечатывать{}, // распечатывать на бумаге rus_verbs:просмотреть{}, // просмотреть на бумаге rus_verbs:закрепляться{}, // закрепляться на плацдарме rus_verbs:погреться{}, // погреться на солнышке rus_verbs:мешать{}, // Он мешал краски на палитре. rus_verbs:занять{}, // Он занял первое место на соревнованиях. rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках. деепричастие:женившись{ вид:соверш }, rus_verbs:везти{}, // Он везёт песок на тачке. прилагательное:казненный{}, // Он был казнён на электрическом стуле. rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче. rus_verbs:принести{}, // Официантка принесла нам обед на подносе. rus_verbs:переписать{}, // Перепишите эту рукопись на машинке. rus_verbs:идти{}, // Поезд идёт на малой скорости. rus_verbs:петь{}, // птички поют на рассвете rus_verbs:смотреть{}, // Смотри на обороте. rus_verbs:прибрать{}, // прибрать на столе rus_verbs:прибраться{}, // прибраться на столе rus_verbs:растить{}, // растить капусту на огороде rus_verbs:тащить{}, // тащить ребенка на руках rus_verbs:убирать{}, // убирать на столе rus_verbs:простыть{}, // Я простыл на морозе. rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе. rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках. rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге. rus_verbs:вскочить{}, // У него вскочил прыщ на носу. rus_verbs:свить{}, // У нас на балконе воробей свил гнездо. rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица. rus_verbs:восходить{}, // Солнце восходит на востоке. rus_verbs:блестеть{}, // Снег блестит на солнце. rus_verbs:побить{}, // Рысак побил всех лошадей на скачках. rus_verbs:литься{}, // Реки крови льются на войне. rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах. rus_verbs:клубиться{}, // Пыль клубится на дороге. инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке. // глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути // инфинитив:находиться{вид:несоверш}, rus_verbs:жить{}, // Было интересно жить на курорте. rus_verbs:повидать{}, // Он много повидал на своём веку. rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду. rus_verbs:расположиться{}, // Оба села расположились на берегу реки. rus_verbs:объясняться{}, // Они объясняются на иностранном языке. rus_verbs:прощаться{}, // Они долго прощались на вокзале. rus_verbs:работать{}, // Она работает на ткацкой фабрике. rus_verbs:купить{}, // Она купила молоко на рынке. rus_verbs:поместиться{}, // Все книги поместились на полке. глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике. rus_verbs:пожить{}, // Недолго она пожила на свете. rus_verbs:краснеть{}, // Небо краснеет на закате. rus_verbs:бывать{}, // На Волге бывает сильное волнение. rus_verbs:ехать{}, // Мы туда ехали на автобусе. rus_verbs:провести{}, // Мы провели месяц на даче. rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице. rus_verbs:расти{}, // Арбузы растут теперь не только на юге. ГЛ_ИНФ(сидеть), // три больших пса сидят на траве ГЛ_ИНФ(сесть), // три больших пса сели на траву ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль ГЛ_ИНФ(повезти), // я повезу тебя на машине ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси ГЛ_ИНФ(пить), // пить на кухне чай ГЛ_ИНФ(найти), // найти на острове ГЛ_ИНФ(быть), // на этих костях есть следы зубов ГЛ_ИНФ(высадиться), // помощники высадились на острове ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове ГЛ_ИНФ(случиться), // это случилось на опушке леса ГЛ_ИНФ(продать), ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: смотреть на youtube fact гл_предл { if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} } then return true } // локатив fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} } then return true } #endregion ПРЕДЛОЖНЫЙ #region ВИНИТЕЛЬНЫЙ // НА+винительный падеж: // ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ #region VerbList wordentry_set Гл_НА_Вин= { rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили. rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку. rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай. rus_verbs:умножить{}, // Умножьте это количество примерно на 10. //rus_verbs:умножать{}, rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу. rus_verbs:откатывать{}, rus_verbs:доносить{}, // Вот и побежали на вас доносить. rus_verbs:донести{}, rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали. безлич_глагол:хватит{}, // - На одну атаку хватит. rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты. rus_verbs:поскупиться{}, // Не поскупись на похвалы! rus_verbs:подыматься{}, rus_verbs:транспортироваться{}, rus_verbs:бахнуть{}, // Бахнуть стакан на пол rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ) rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ) rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ) rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ) rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ) rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ) rus_verbs:БРЫЗГАТЬ{}, rus_verbs:БРЫЗНУТЬ{}, rus_verbs:КАПНУТЬ{}, rus_verbs:КАПАТЬ{}, rus_verbs:ПОКАПАТЬ{}, rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ) rus_verbs:ОХОТИТЬСЯ{}, // rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ) rus_verbs:НАРВАТЬСЯ{}, // rus_verbs:НАТОЛКНУТЬСЯ{}, // rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ) прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ) rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ) rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ) rus_verbs:СТАЛКИВАТЬ{}, // rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ) rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ) rus_verbs:ПЕРЕБРОСИТЬ{}, // rus_verbs:НАБРАСЫВАТЬ{}, // rus_verbs:НАБРОСИТЬ{}, // rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ) rus_verbs:СВОРАЧИВАТЬ{}, // // rus_verbs:ПОВЕРНУТЬ{}, // rus_verbs:ПОВОРАЧИВАТЬ{}, // rus_verbs:наорать{}, rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ) rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ) rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:перегонять{}, rus_verbs:выгонять{}, rus_verbs:выгнать{}, rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ) rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ) rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ) rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ) rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций rus_verbs:назначаться{}, // назначаться на пост rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин) rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА) // rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА) rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА) rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин) rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА) rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА) rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин) rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА) rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА) прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА) rus_verbs:посыпаться{}, // на Нину посыпались снежинки инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод. глагол:нарезаться{ вид:несоверш }, rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу rus_verbs:показать{}, // Вадим показал на Колю rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА) rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на) rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА) rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА) rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на) rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА) rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА) rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на) rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на) rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на) rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на) rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на) rus_verbs:верить{}, // верить людям на слово (верить на слово) rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру. rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору. rus_verbs:пасть{}, // Жребий пал на меня. rus_verbs:ездить{}, // Вчера мы ездили на оперу. rus_verbs:влезть{}, // Мальчик влез на дерево. rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу. rus_verbs:разбиться{}, // окно разбилось на мелкие осколки rus_verbs:бежать{}, // я бегу на урок rus_verbs:сбегаться{}, // сбегаться на происшествие rus_verbs:присылать{}, // присылать на испытание rus_verbs:надавить{}, // надавить на педать rus_verbs:внести{}, // внести законопроект на рассмотрение rus_verbs:вносить{}, // вносить законопроект на рассмотрение rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек. rus_verbs:оглядываться{}, // оглядываться на девушек rus_verbs:расходиться{}, // расходиться на отдых rus_verbs:поскакать{}, // поскакать на службу rus_verbs:прыгать{}, // прыгать на сцену rus_verbs:приглашать{}, // приглашать на обед rus_verbs:рваться{}, // Кусок ткани рвется на части rus_verbs:понестись{}, // понестись на волю rus_verbs:распространяться{}, // распространяться на всех жителей штата инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, деепричастие:просыпавшись{}, деепричастие:просыпаясь{}, rus_verbs:заехать{}, // заехать на пандус rus_verbs:разобрать{}, // разобрать на составляющие rus_verbs:опускаться{}, // опускаться на колени rus_verbs:переехать{}, // переехать на конспиративную квартиру rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов rus_verbs:поместить{}, // поместить на поднос rus_verbs:отходить{}, // отходить на подготовленные позиции rus_verbs:сыпаться{}, // сыпаться на плечи rus_verbs:отвезти{}, // отвезти на занятия rus_verbs:накинуть{}, // накинуть на плечи rus_verbs:отлететь{}, // отлететь на пол rus_verbs:закинуть{}, // закинуть на чердак rus_verbs:зашипеть{}, // зашипеть на собаку rus_verbs:прогреметь{}, // прогреметь на всю страну rus_verbs:повалить{}, // повалить на стол rus_verbs:опереть{}, // опереть на фундамент rus_verbs:забросить{}, // забросить на антресоль rus_verbs:подействовать{}, // подействовать на материал rus_verbs:разделять{}, // разделять на части rus_verbs:прикрикнуть{}, // прикрикнуть на детей rus_verbs:разложить{}, // разложить на множители rus_verbs:провожать{}, // провожать на работу rus_verbs:катить{}, // катить на стройку rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью rus_verbs:сохранять{}, // сохранять на память rus_verbs:злиться{}, // злиться на друга rus_verbs:оборачиваться{}, // оборачиваться на свист rus_verbs:сползти{}, // сползти на землю rus_verbs:записывать{}, // записывать на ленту rus_verbs:загнать{}, // загнать на дерево rus_verbs:забормотать{}, // забормотать на ухо rus_verbs:протиснуться{}, // протиснуться на самый край rus_verbs:заторопиться{}, // заторопиться на вручение премии rus_verbs:гаркнуть{}, // гаркнуть на шалунов rus_verbs:навалиться{}, // навалиться на виновника всей толпой rus_verbs:проскользнуть{}, // проскользнуть на крышу дома rus_verbs:подтянуть{}, // подтянуть на палубу rus_verbs:скатиться{}, // скатиться на двойки rus_verbs:давить{}, // давить на жалость rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства rus_verbs:замахнуться{}, // замахнуться на святое rus_verbs:заменить{}, // заменить на свежую салфетку rus_verbs:свалить{}, // свалить на землю rus_verbs:стекать{}, // стекать на оголенные провода rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов rus_verbs:развалиться{}, // развалиться на части rus_verbs:сердиться{}, // сердиться на товарища rus_verbs:обронить{}, // обронить на пол rus_verbs:подсесть{}, // подсесть на наркоту rus_verbs:реагировать{}, // реагировать на импульсы rus_verbs:отпускать{}, // отпускать на волю rus_verbs:прогнать{}, // прогнать на рабочее место rus_verbs:ложить{}, // ложить на стол rus_verbs:рвать{}, // рвать на части rus_verbs:разлететься{}, // разлететься на кусочки rus_verbs:превышать{}, // превышать на существенную величину rus_verbs:сбиться{}, // сбиться на рысь rus_verbs:пристроиться{}, // пристроиться на хорошую работу rus_verbs:удрать{}, // удрать на пастбище rus_verbs:толкать{}, // толкать на преступление rus_verbs:посматривать{}, // посматривать на экран rus_verbs:набирать{}, // набирать на судно rus_verbs:отступать{}, // отступать на дерево rus_verbs:подуть{}, // подуть на молоко rus_verbs:плеснуть{}, // плеснуть на голову rus_verbs:соскользнуть{}, // соскользнуть на землю rus_verbs:затаить{}, // затаить на кого-то обиду rus_verbs:обижаться{}, // обижаться на Колю rus_verbs:смахнуть{}, // смахнуть на пол rus_verbs:застегнуть{}, // застегнуть на все пуговицы rus_verbs:спускать{}, // спускать на землю rus_verbs:греметь{}, // греметь на всю округу rus_verbs:скосить{}, // скосить на соседа глаз rus_verbs:отважиться{}, // отважиться на прыжок rus_verbs:литься{}, // литься на землю rus_verbs:порвать{}, // порвать на тряпки rus_verbs:проследовать{}, // проследовать на сцену rus_verbs:надевать{}, // надевать на голову rus_verbs:проскочить{}, // проскочить на красный свет rus_verbs:прилечь{}, // прилечь на диванчик rus_verbs:разделиться{}, // разделиться на небольшие группы rus_verbs:завыть{}, // завыть на луну rus_verbs:переносить{}, // переносить на другую машину rus_verbs:наговорить{}, // наговорить на сотню рублей rus_verbs:намекать{}, // намекать на новые обстоятельства rus_verbs:нападать{}, // нападать на охранников rus_verbs:убегать{}, // убегать на другое место rus_verbs:тратить{}, // тратить на развлечения rus_verbs:присаживаться{}, // присаживаться на корточки rus_verbs:переместиться{}, // переместиться на вторую линию rus_verbs:завалиться{}, // завалиться на диван rus_verbs:удалиться{}, // удалиться на покой rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов rus_verbs:обрушить{}, // обрушить на голову rus_verbs:резать{}, // резать на части rus_verbs:умчаться{}, // умчаться на юг rus_verbs:навернуться{}, // навернуться на камень rus_verbs:примчаться{}, // примчаться на матч rus_verbs:издавать{}, // издавать на собственные средства rus_verbs:переключить{}, // переключить на другой язык rus_verbs:отправлять{}, // отправлять на пенсию rus_verbs:залечь{}, // залечь на дно rus_verbs:установиться{}, // установиться на диск rus_verbs:направлять{}, // направлять на дополнительное обследование rus_verbs:разрезать{}, // разрезать на части rus_verbs:оскалиться{}, // оскалиться на прохожего rus_verbs:рычать{}, // рычать на пьяных rus_verbs:погружаться{}, // погружаться на дно rus_verbs:опираться{}, // опираться на костыли rus_verbs:поторопиться{}, // поторопиться на учебу rus_verbs:сдвинуться{}, // сдвинуться на сантиметр rus_verbs:увеличить{}, // увеличить на процент rus_verbs:опускать{}, // опускать на землю rus_verbs:созвать{}, // созвать на митинг rus_verbs:делить{}, // делить на части rus_verbs:пробиться{}, // пробиться на заключительную часть rus_verbs:простираться{}, // простираться на много миль rus_verbs:забить{}, // забить на учебу rus_verbs:переложить{}, // переложить на чужие плечи rus_verbs:грохнуться{}, // грохнуться на землю rus_verbs:прорваться{}, // прорваться на сцену rus_verbs:разлить{}, // разлить на землю rus_verbs:укладываться{}, // укладываться на ночевку rus_verbs:уволить{}, // уволить на пенсию rus_verbs:наносить{}, // наносить на кожу rus_verbs:набежать{}, // набежать на берег rus_verbs:заявиться{}, // заявиться на стрельбище rus_verbs:налиться{}, // налиться на крышку rus_verbs:надвигаться{}, // надвигаться на берег rus_verbs:распустить{}, // распустить на каникулы rus_verbs:переключиться{}, // переключиться на другую задачу rus_verbs:чихнуть{}, // чихнуть на окружающих rus_verbs:шлепнуться{}, // шлепнуться на спину rus_verbs:устанавливать{}, // устанавливать на крышу rus_verbs:устанавливаться{}, // устанавливаться на крышу rus_verbs:устраиваться{}, // устраиваться на работу rus_verbs:пропускать{}, // пропускать на стадион инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, деепричастие:сбегав{}, деепричастие:сбегая{}, rus_verbs:показываться{}, // показываться на глаза rus_verbs:прибегать{}, // прибегать на урок rus_verbs:съездить{}, // съездить на ферму rus_verbs:прославиться{}, // прославиться на всю страну rus_verbs:опрокинуться{}, // опрокинуться на спину rus_verbs:насыпать{}, // насыпать на землю rus_verbs:употреблять{}, // употреблять на корм скоту rus_verbs:пристроить{}, // пристроить на работу rus_verbs:заворчать{}, // заворчать на вошедшего rus_verbs:завязаться{}, // завязаться на поставщиков rus_verbs:сажать{}, // сажать на стул rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры rus_verbs:заменять{}, // заменять на исправную rus_verbs:нацепить{}, // нацепить на голову rus_verbs:сыпать{}, // сыпать на землю rus_verbs:закрываться{}, // закрываться на ремонт rus_verbs:распространиться{}, // распространиться на всю популяцию rus_verbs:поменять{}, // поменять на велосипед rus_verbs:пересесть{}, // пересесть на велосипеды rus_verbs:подоспеть{}, // подоспеть на разбор rus_verbs:шипеть{}, // шипеть на собак rus_verbs:поделить{}, // поделить на части rus_verbs:подлететь{}, // подлететь на расстояние выстрела rus_verbs:нажимать{}, // нажимать на все кнопки rus_verbs:распасться{}, // распасться на части rus_verbs:приволочь{}, // приволочь на диван rus_verbs:пожить{}, // пожить на один доллар rus_verbs:устремляться{}, // устремляться на свободу rus_verbs:смахивать{}, // смахивать на пол rus_verbs:забежать{}, // забежать на обед rus_verbs:увеличиться{}, // увеличиться на существенную величину rus_verbs:прокрасться{}, // прокрасться на склад rus_verbs:пущать{}, // пущать на постой rus_verbs:отклонить{}, // отклонить на несколько градусов rus_verbs:насмотреться{}, // насмотреться на безобразия rus_verbs:настроить{}, // настроить на короткие волны rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров rus_verbs:поменяться{}, // поменяться на другую книжку rus_verbs:расколоться{}, // расколоться на части rus_verbs:разлиться{}, // разлиться на землю rus_verbs:срываться{}, // срываться на жену rus_verbs:осудить{}, // осудить на пожизненное заключение rus_verbs:передвинуть{}, // передвинуть на первое место rus_verbs:допускаться{}, // допускаться на полигон rus_verbs:задвинуть{}, // задвинуть на полку rus_verbs:повлиять{}, // повлиять на оценку rus_verbs:отбавлять{}, // отбавлять на осмотр rus_verbs:сбрасывать{}, // сбрасывать на землю rus_verbs:накинуться{}, // накинуться на случайных прохожих rus_verbs:пролить{}, // пролить на кожу руки rus_verbs:затащить{}, // затащить на сеновал rus_verbs:перебежать{}, // перебежать на сторону противника rus_verbs:наливать{}, // наливать на скатерть rus_verbs:пролезть{}, // пролезть на сцену rus_verbs:откладывать{}, // откладывать на черный день rus_verbs:распадаться{}, // распадаться на небольшие фрагменты rus_verbs:перечислить{}, // перечислить на счет rus_verbs:закачаться{}, // закачаться на верхний уровень rus_verbs:накрениться{}, // накрениться на правый борт rus_verbs:подвинуться{}, // подвинуться на один уровень rus_verbs:разнести{}, // разнести на мелкие кусочки rus_verbs:зажить{}, // зажить на широкую ногу rus_verbs:оглохнуть{}, // оглохнуть на правое ухо rus_verbs:посетовать{}, // посетовать на бюрократизм rus_verbs:уводить{}, // уводить на осмотр rus_verbs:ускакать{}, // ускакать на забег rus_verbs:посветить{}, // посветить на стену rus_verbs:разрываться{}, // разрываться на части rus_verbs:побросать{}, // побросать на землю rus_verbs:карабкаться{}, // карабкаться на скалу rus_verbs:нахлынуть{}, // нахлынуть на кого-то rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки rus_verbs:среагировать{}, // среагировать на сигнал rus_verbs:претендовать{}, // претендовать на приз rus_verbs:дунуть{}, // дунуть на одуванчик rus_verbs:переводиться{}, // переводиться на другую работу rus_verbs:перевезти{}, // перевезти на другую площадку rus_verbs:топать{}, // топать на урок rus_verbs:относить{}, // относить на склад rus_verbs:сбивать{}, // сбивать на землю rus_verbs:укладывать{}, // укладывать на спину rus_verbs:укатить{}, // укатить на отдых rus_verbs:убирать{}, // убирать на полку rus_verbs:опасть{}, // опасть на землю rus_verbs:ронять{}, // ронять на снег rus_verbs:пялиться{}, // пялиться на тело rus_verbs:глазеть{}, // глазеть на тело rus_verbs:снижаться{}, // снижаться на безопасную высоту rus_verbs:запрыгнуть{}, // запрыгнуть на платформу rus_verbs:разбиваться{}, // разбиваться на главы rus_verbs:сгодиться{}, // сгодиться на фарш rus_verbs:перескочить{}, // перескочить на другую страницу rus_verbs:нацелиться{}, // нацелиться на главную добычу rus_verbs:заезжать{}, // заезжать на бордюр rus_verbs:забираться{}, // забираться на крышу rus_verbs:проорать{}, // проорать на всё село rus_verbs:сбежаться{}, // сбежаться на шум rus_verbs:сменять{}, // сменять на хлеб rus_verbs:мотать{}, // мотать на ус rus_verbs:раскалываться{}, // раскалываться на две половинки rus_verbs:коситься{}, // коситься на режиссёра rus_verbs:плевать{}, // плевать на законы rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение rus_verbs:наставить{}, // наставить на путь истинный rus_verbs:завывать{}, // завывать на Луну rus_verbs:опаздывать{}, // опаздывать на совещание rus_verbs:залюбоваться{}, // залюбоваться на пейзаж rus_verbs:повергнуть{}, // повергнуть на землю rus_verbs:надвинуть{}, // надвинуть на лоб rus_verbs:стекаться{}, // стекаться на площадь rus_verbs:обозлиться{}, // обозлиться на тренера rus_verbs:оттянуть{}, // оттянуть на себя rus_verbs:истратить{}, // истратить на дешевых шлюх rus_verbs:вышвырнуть{}, // вышвырнуть на улицу rus_verbs:затолкать{}, // затолкать на верхнюю полку rus_verbs:заскочить{}, // заскочить на огонек rus_verbs:проситься{}, // проситься на улицу rus_verbs:натыкаться{}, // натыкаться на борщевик rus_verbs:обрушиваться{}, // обрушиваться на митингующих rus_verbs:переписать{}, // переписать на чистовик rus_verbs:переноситься{}, // переноситься на другое устройство rus_verbs:напроситься{}, // напроситься на обидный ответ rus_verbs:натягивать{}, // натягивать на ноги rus_verbs:кидаться{}, // кидаться на прохожих rus_verbs:откликаться{}, // откликаться на призыв rus_verbs:поспевать{}, // поспевать на балет rus_verbs:обратиться{}, // обратиться на кафедру rus_verbs:полюбоваться{}, // полюбоваться на бюст rus_verbs:таращиться{}, // таращиться на мустангов rus_verbs:напороться{}, // напороться на колючки rus_verbs:раздать{}, // раздать на руки rus_verbs:дивиться{}, // дивиться на танцовщиц rus_verbs:назначать{}, // назначать на ответственнейший пост rus_verbs:кидать{}, // кидать на балкон rus_verbs:нахлобучить{}, // нахлобучить на башку rus_verbs:увлекать{}, // увлекать на луг rus_verbs:ругнуться{}, // ругнуться на животину rus_verbs:переселиться{}, // переселиться на хутор rus_verbs:разрывать{}, // разрывать на части rus_verbs:утащить{}, // утащить на дерево rus_verbs:наставлять{}, // наставлять на путь rus_verbs:соблазнить{}, // соблазнить на обмен rus_verbs:накладывать{}, // накладывать на рану rus_verbs:набрести{}, // набрести на грибную поляну rus_verbs:наведываться{}, // наведываться на прежнюю работу rus_verbs:погулять{}, // погулять на чужие деньги rus_verbs:уклоняться{}, // уклоняться на два градуса влево rus_verbs:слезать{}, // слезать на землю rus_verbs:клевать{}, // клевать на мотыля // rus_verbs:назначаться{}, // назначаться на пост rus_verbs:напялить{}, // напялить на голову rus_verbs:натянуться{}, // натянуться на рамку rus_verbs:разгневаться{}, // разгневаться на придворных rus_verbs:эмигрировать{}, // эмигрировать на Кипр rus_verbs:накатить{}, // накатить на основу rus_verbs:пригнать{}, // пригнать на пастбище rus_verbs:обречь{}, // обречь на мучения rus_verbs:сокращаться{}, // сокращаться на четверть rus_verbs:оттеснить{}, // оттеснить на пристань rus_verbs:подбить{}, // подбить на аферу rus_verbs:заманить{}, // заманить на дерево инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик // деепричастие:пописав{ aux stress="поп^исать" }, rus_verbs:посходить{}, // посходить на перрон rus_verbs:налечь{}, // налечь на мясцо rus_verbs:отбирать{}, // отбирать на флот rus_verbs:нашептывать{}, // нашептывать на ухо rus_verbs:откладываться{}, // откладываться на будущее rus_verbs:залаять{}, // залаять на грабителя rus_verbs:настроиться{}, // настроиться на прием rus_verbs:разбивать{}, // разбивать на куски rus_verbs:пролиться{}, // пролиться на почву rus_verbs:сетовать{}, // сетовать на объективные трудности rus_verbs:подвезти{}, // подвезти на митинг rus_verbs:припереться{}, // припереться на праздник rus_verbs:подталкивать{}, // подталкивать на прыжок rus_verbs:прорываться{}, // прорываться на сцену rus_verbs:снижать{}, // снижать на несколько процентов rus_verbs:нацелить{}, // нацелить на танк rus_verbs:расколоть{}, // расколоть на два куска rus_verbs:увозить{}, // увозить на обкатку rus_verbs:оседать{}, // оседать на дно rus_verbs:съедать{}, // съедать на ужин rus_verbs:навлечь{}, // навлечь на себя rus_verbs:равняться{}, // равняться на лучших rus_verbs:сориентироваться{}, // сориентироваться на местности rus_verbs:снизить{}, // снизить на несколько процентов rus_verbs:перенестись{}, // перенестись на много лет назад rus_verbs:завезти{}, // завезти на склад rus_verbs:проложить{}, // проложить на гору rus_verbs:понадеяться{}, // понадеяться на удачу rus_verbs:заступить{}, // заступить на вахту rus_verbs:засеменить{}, // засеменить на выход rus_verbs:запирать{}, // запирать на ключ rus_verbs:скатываться{}, // скатываться на землю rus_verbs:дробить{}, // дробить на части rus_verbs:разваливаться{}, // разваливаться на кусочки rus_verbs:завозиться{}, // завозиться на склад rus_verbs:нанимать{}, // нанимать на дневную работу rus_verbs:поспеть{}, // поспеть на концерт rus_verbs:променять{}, // променять на сытость rus_verbs:переправить{}, // переправить на север rus_verbs:налетать{}, // налетать на силовое поле rus_verbs:затворить{}, // затворить на замок rus_verbs:подогнать{}, // подогнать на пристань rus_verbs:наехать{}, // наехать на камень rus_verbs:распевать{}, // распевать на разные голоса rus_verbs:разносить{}, // разносить на клочки rus_verbs:преувеличивать{}, // преувеличивать на много килограммов rus_verbs:хромать{}, // хромать на одну ногу rus_verbs:телеграфировать{}, // телеграфировать на базу rus_verbs:порезать{}, // порезать на лоскуты rus_verbs:порваться{}, // порваться на части rus_verbs:загонять{}, // загонять на дерево rus_verbs:отбывать{}, // отбывать на место службы rus_verbs:усаживаться{}, // усаживаться на трон rus_verbs:накопить{}, // накопить на квартиру rus_verbs:зыркнуть{}, // зыркнуть на визитера rus_verbs:копить{}, // копить на машину rus_verbs:помещать{}, // помещать на верхнюю грань rus_verbs:сползать{}, // сползать на снег rus_verbs:попроситься{}, // попроситься на улицу rus_verbs:перетащить{}, // перетащить на чердак rus_verbs:растащить{}, // растащить на сувениры rus_verbs:ниспадать{}, // ниспадать на землю rus_verbs:сфотографировать{}, // сфотографировать на память rus_verbs:нагонять{}, // нагонять на конкурентов страх rus_verbs:покушаться{}, // покушаться на понтифика rus_verbs:покуситься{}, rus_verbs:наняться{}, // наняться на службу rus_verbs:просачиваться{}, // просачиваться на поверхность rus_verbs:пускаться{}, // пускаться на ветер rus_verbs:отваживаться{}, // отваживаться на прыжок rus_verbs:досадовать{}, // досадовать на объективные трудности rus_verbs:унестись{}, // унестись на небо rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов rus_verbs:насадить{}, // насадить на копьё rus_verbs:нагрянуть{}, // нагрянуть на праздник rus_verbs:зашвырнуть{}, // зашвырнуть на полку rus_verbs:грешить{}, // грешить на постояльцев rus_verbs:просочиться{}, // просочиться на поверхность rus_verbs:надоумить{}, // надоумить на глупость rus_verbs:намотать{}, // намотать на шпиндель rus_verbs:замкнуть{}, // замкнуть на корпус rus_verbs:цыкнуть{}, // цыкнуть на детей rus_verbs:переворачиваться{}, // переворачиваться на спину rus_verbs:соваться{}, // соваться на площать rus_verbs:отлучиться{}, // отлучиться на обед rus_verbs:пенять{}, // пенять на себя rus_verbs:нарезать{}, // нарезать на ломтики rus_verbs:поставлять{}, // поставлять на Кипр rus_verbs:залезать{}, // залезать на балкон rus_verbs:отлучаться{}, // отлучаться на обед rus_verbs:сбиваться{}, // сбиваться на шаг rus_verbs:таращить{}, // таращить глаза на вошедшего rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню rus_verbs:опережать{}, // опережать на пару сантиметров rus_verbs:переставить{}, // переставить на стол rus_verbs:раздирать{}, // раздирать на части rus_verbs:затвориться{}, // затвориться на засовы rus_verbs:материться{}, // материться на кого-то rus_verbs:наскочить{}, // наскочить на риф rus_verbs:набираться{}, // набираться на борт rus_verbs:покрикивать{}, // покрикивать на помощников rus_verbs:заменяться{}, // заменяться на более новый rus_verbs:подсадить{}, // подсадить на верхнюю полку rus_verbs:проковылять{}, // проковылять на кухню rus_verbs:прикатить{}, // прикатить на старт rus_verbs:залететь{}, // залететь на чужую территорию rus_verbs:загрузить{}, // загрузить на конвейер rus_verbs:уплывать{}, // уплывать на материк rus_verbs:опозорить{}, // опозорить на всю деревню rus_verbs:провоцировать{}, // провоцировать на ответную агрессию rus_verbs:забивать{}, // забивать на учебу rus_verbs:набегать{}, // набегать на прибрежные деревни rus_verbs:запираться{}, // запираться на ключ rus_verbs:фотографировать{}, // фотографировать на мыльницу rus_verbs:подымать{}, // подымать на недосягаемую высоту rus_verbs:съезжаться{}, // съезжаться на симпозиум rus_verbs:отвлекаться{}, // отвлекаться на игру rus_verbs:проливать{}, // проливать на брюки rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца rus_verbs:уползти{}, // уползти на вершину холма rus_verbs:переместить{}, // переместить на вторую палубу rus_verbs:превысить{}, // превысить на несколько метров rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку rus_verbs:спровоцировать{}, // спровоцировать на бросок rus_verbs:сместиться{}, // сместиться на соседнюю клетку rus_verbs:заготовить{}, // заготовить на зиму rus_verbs:плеваться{}, // плеваться на пол rus_verbs:переселить{}, // переселить на север rus_verbs:напирать{}, // напирать на дверь rus_verbs:переезжать{}, // переезжать на другой этаж rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров rus_verbs:трогаться{}, // трогаться на красный свет rus_verbs:надвинуться{}, // надвинуться на глаза rus_verbs:засмотреться{}, // засмотреться на купальники rus_verbs:убыть{}, // убыть на фронт rus_verbs:передвигать{}, // передвигать на второй уровень rus_verbs:отвозить{}, // отвозить на свалку rus_verbs:обрекать{}, // обрекать на гибель rus_verbs:записываться{}, // записываться на танцы rus_verbs:настраивать{}, // настраивать на другой диапазон rus_verbs:переписывать{}, // переписывать на диск rus_verbs:израсходовать{}, // израсходовать на гонки rus_verbs:обменять{}, // обменять на перспективного игрока rus_verbs:трубить{}, // трубить на всю округу rus_verbs:набрасываться{}, // набрасываться на жертву rus_verbs:чихать{}, // чихать на правила rus_verbs:наваливаться{}, // наваливаться на рычаг rus_verbs:сподобиться{}, // сподобиться на повторный анализ rus_verbs:намазать{}, // намазать на хлеб rus_verbs:прореагировать{}, // прореагировать на вызов rus_verbs:зачислить{}, // зачислить на факультет rus_verbs:наведаться{}, // наведаться на склад rus_verbs:откидываться{}, // откидываться на спинку кресла rus_verbs:захромать{}, // захромать на левую ногу rus_verbs:перекочевать{}, // перекочевать на другой берег rus_verbs:накатываться{}, // накатываться на песчаный берег rus_verbs:приостановить{}, // приостановить на некоторое время rus_verbs:запрятать{}, // запрятать на верхнюю полочку rus_verbs:прихрамывать{}, // прихрамывать на правую ногу rus_verbs:упорхнуть{}, // упорхнуть на свободу rus_verbs:расстегивать{}, // расстегивать на пальто rus_verbs:напуститься{}, // напуститься на бродягу rus_verbs:накатывать{}, // накатывать на оригинал rus_verbs:наезжать{}, // наезжать на простофилю rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека rus_verbs:отрядить{}, // отрядить на починку rus_verbs:положиться{}, // положиться на главаря rus_verbs:опрокидывать{}, // опрокидывать на голову rus_verbs:поторапливаться{}, // поторапливаться на рейс rus_verbs:налагать{}, // налагать на заемщика rus_verbs:скопировать{}, // скопировать на диск rus_verbs:опадать{}, // опадать на землю rus_verbs:купиться{}, // купиться на посулы rus_verbs:гневаться{}, // гневаться на слуг rus_verbs:слететься{}, // слететься на раздачу rus_verbs:убавить{}, // убавить на два уровня rus_verbs:спихнуть{}, // спихнуть на соседа rus_verbs:накричать{}, // накричать на ребенка rus_verbs:приберечь{}, // приберечь на ужин rus_verbs:приклеить{}, // приклеить на ветровое стекло rus_verbs:ополчиться{}, // ополчиться на посредников rus_verbs:тратиться{}, // тратиться на сувениры rus_verbs:слетаться{}, // слетаться на свет rus_verbs:доставляться{}, // доставляться на базу rus_verbs:поплевать{}, // поплевать на руки rus_verbs:огрызаться{}, // огрызаться на замечание rus_verbs:попереться{}, // попереться на рынок rus_verbs:растягиваться{}, // растягиваться на полу rus_verbs:повергать{}, // повергать на землю rus_verbs:ловиться{}, // ловиться на мотыля rus_verbs:наседать{}, // наседать на обороняющихся rus_verbs:развалить{}, // развалить на кирпичи rus_verbs:разломить{}, // разломить на несколько частей rus_verbs:примерить{}, // примерить на себя rus_verbs:лепиться{}, // лепиться на стену rus_verbs:скопить{}, // скопить на старость rus_verbs:затратить{}, // затратить на ликвидацию последствий rus_verbs:притащиться{}, // притащиться на гулянку rus_verbs:осерчать{}, // осерчать на прислугу rus_verbs:натравить{}, // натравить на медведя rus_verbs:ссыпать{}, // ссыпать на землю rus_verbs:подвозить{}, // подвозить на пристань rus_verbs:мобилизовать{}, // мобилизовать на сборы rus_verbs:смотаться{}, // смотаться на работу rus_verbs:заглядеться{}, // заглядеться на девчонок rus_verbs:таскаться{}, // таскаться на работу rus_verbs:разгружать{}, // разгружать на транспортер rus_verbs:потреблять{}, // потреблять на кондиционирование инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу деепричастие:сгоняв{}, rus_verbs:посылаться{}, // посылаться на разведку rus_verbs:окрыситься{}, // окрыситься на кого-то rus_verbs:отлить{}, // отлить на сковороду rus_verbs:шикнуть{}, // шикнуть на детишек rus_verbs:уповать{}, // уповать на бескорысную помощь rus_verbs:класться{}, // класться на стол rus_verbs:поковылять{}, // поковылять на выход rus_verbs:навевать{}, // навевать на собравшихся скуку rus_verbs:накладываться{}, // накладываться на грунтовку rus_verbs:наноситься{}, // наноситься на чистую кожу // rus_verbs:запланировать{}, // запланировать на среду rus_verbs:кувыркнуться{}, // кувыркнуться на землю rus_verbs:гавкнуть{}, // гавкнуть на хозяина rus_verbs:перестроиться{}, // перестроиться на новый лад rus_verbs:расходоваться{}, // расходоваться на образование rus_verbs:дуться{}, // дуться на бабушку rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол rus_verbs:издаться{}, // издаться на деньги спонсоров rus_verbs:смещаться{}, // смещаться на несколько миллиметров rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу rus_verbs:пикировать{}, // пикировать на окопы rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей rus_verbs:зудить{}, // зудить на ухо rus_verbs:подразделяться{}, // подразделяться на группы rus_verbs:изливаться{}, // изливаться на землю rus_verbs:помочиться{}, // помочиться на траву rus_verbs:примерять{}, // примерять на себя rus_verbs:разрядиться{}, // разрядиться на землю rus_verbs:мотнуться{}, // мотнуться на крышу rus_verbs:налегать{}, // налегать на весла rus_verbs:зацокать{}, // зацокать на куриц rus_verbs:наниматься{}, // наниматься на корабль rus_verbs:сплевывать{}, // сплевывать на землю rus_verbs:настучать{}, // настучать на саботажника rus_verbs:приземляться{}, // приземляться на брюхо rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу rus_verbs:серчать{}, // серчать на нерасторопную помощницу rus_verbs:сваливать{}, // сваливать на подоконник rus_verbs:засобираться{}, // засобираться на работу rus_verbs:распилить{}, // распилить на одинаковые бруски //rus_verbs:умножать{}, // умножать на константу rus_verbs:копировать{}, // копировать на диск rus_verbs:накрутить{}, // накрутить на руку rus_verbs:навалить{}, // навалить на телегу rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль rus_verbs:шлепаться{}, // шлепаться на бетон rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение rus_verbs:посягнуть{}, // посягнуть на святое rus_verbs:разменять{}, // разменять на мелочь rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции rus_verbs:усаживать{}, // усаживать на скамейку rus_verbs:натаскать{}, // натаскать на поиск наркотиков rus_verbs:зашикать{}, // зашикать на кошку rus_verbs:разломать{}, // разломать на равные части rus_verbs:приглашаться{}, // приглашаться на сцену rus_verbs:присягать{}, // присягать на верность rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку rus_verbs:расщедриться{}, // расщедриться на новый компьютер rus_verbs:насесть{}, // насесть на двоечников rus_verbs:созывать{}, // созывать на собрание rus_verbs:позариться{}, // позариться на чужое добро rus_verbs:перекидываться{}, // перекидываться на соседние здания rus_verbs:наползать{}, // наползать на неповрежденную ткань rus_verbs:изрубить{}, // изрубить на мелкие кусочки rus_verbs:наворачиваться{}, // наворачиваться на глаза rus_verbs:раскричаться{}, // раскричаться на всю округу rus_verbs:переползти{}, // переползти на светлую сторону rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию rus_verbs:мочиться{}, // мочиться на трупы убитых врагов rus_verbs:радировать{}, // радировать на базу rus_verbs:промотать{}, // промотать на начало rus_verbs:заснять{}, // заснять на видео rus_verbs:подбивать{}, // подбивать на матч-реванш rus_verbs:наплевать{}, // наплевать на справедливость rus_verbs:подвывать{}, // подвывать на луну rus_verbs:расплескать{}, // расплескать на пол rus_verbs:польститься{}, // польститься на бесплатный сыр rus_verbs:помчать{}, // помчать на работу rus_verbs:съезжать{}, // съезжать на обочину rus_verbs:нашептать{}, // нашептать кому-то на ухо rus_verbs:наклеить{}, // наклеить на доску объявлений rus_verbs:завозить{}, // завозить на склад rus_verbs:заявляться{}, // заявляться на любимую работу rus_verbs:наглядеться{}, // наглядеться на воробьев rus_verbs:хлопнуться{}, // хлопнуться на живот rus_verbs:забредать{}, // забредать на поляну rus_verbs:посягать{}, // посягать на исконные права собственности rus_verbs:сдвигать{}, // сдвигать на одну позицию rus_verbs:спрыгивать{}, // спрыгивать на землю rus_verbs:сдвигаться{}, // сдвигаться на две позиции rus_verbs:разделать{}, // разделать на орехи rus_verbs:разлагать{}, // разлагать на элементарные элементы rus_verbs:обрушивать{}, // обрушивать на головы врагов rus_verbs:натечь{}, // натечь на пол rus_verbs:политься{}, // вода польется на землю rus_verbs:успеть{}, // Они успеют на поезд. инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш }, деепричастие:мигрируя{}, инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш }, деепричастие:мигрировав{}, rus_verbs:двинуться{}, // Мы скоро двинемся на дачу. rus_verbs:подойти{}, // Он не подойдёт на должность секретаря. rus_verbs:потянуть{}, // Он не потянет на директора. rus_verbs:тянуть{}, // Он не тянет на директора. rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:жаловаться{}, // Он жалуется на нездоровье. rus_verbs:издать{}, // издать на деньги спонсоров rus_verbs:показаться{}, // показаться на глаза rus_verbs:высаживать{}, // высаживать на необитаемый остров rus_verbs:вознестись{}, // вознестись на самую вершину славы rus_verbs:залить{}, // залить на youtube rus_verbs:закачать{}, // закачать на youtube rus_verbs:сыграть{}, // сыграть на деньги rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных глагол:экстраполироваться{ вид:несоверш}, инфинитив:экстраполироваться{ вид:соверш}, глагол:экстраполироваться{ вид:соверш}, деепричастие:экстраполируясь{}, инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы глагол:акцентировать{вид:соверш}, инфинитив:акцентировать{вид:несоверш}, глагол:акцентировать{вид:несоверш}, прилагательное:акцентировавший{вид:несоверш}, //прилагательное:акцентировавший{вид:соверш}, прилагательное:акцентирующий{}, деепричастие:акцентировав{}, деепричастие:акцентируя{}, rus_verbs:бабахаться{}, // он бабахался на пол rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина rus_verbs:бахаться{}, // Наездники бахались на землю rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю rus_verbs:благословить{}, // батюшка благословил отрока на подвиг rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг rus_verbs:блевануть{}, // Он блеванул на землю rus_verbs:блевать{}, // Он блюет на землю rus_verbs:бухнуться{}, // Наездник бухнулся на землю rus_verbs:валить{}, // Ветер валил деревья на землю rus_verbs:спилить{}, // Спиленное дерево валится на землю rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес rus_verbs:вестись{}, // Не ведись на эти уловки! rus_verbs:вешать{}, // Гости вешают одежду на вешалку rus_verbs:вешаться{}, // Одежда вешается на вешалки rus_verbs:вещать{}, // радиостанция вещает на всю страну rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм rus_verbs:взбредать{}, // Что иногда взбредает на ум rus_verbs:взбрести{}, // Что-то взбрело на ум rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи rus_verbs:взглянуть{}, // Кошка взглянула на мышку rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух rus_verbs:взобраться{}, // Туристы взобрались на гору rus_verbs:взойти{}, // Туристы взошли на гору rus_verbs:взъесться{}, // Отец взъелся на непутевого сына rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка rus_verbs:водворить{}, // водворить нарушителя на место rus_verbs:водвориться{}, // водвориться на свое место rus_verbs:водворять{}, // водворять вещь на свое место rus_verbs:водворяться{}, // водворяться на свое место rus_verbs:водружать{}, // водружать флаг на флагшток rus_verbs:водружаться{}, // Флаг водружается на флагшток rus_verbs:водрузить{}, // водрузить флаг на флагшток rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы rus_verbs:воздействовать{}, // Излучение воздействует на кожу rus_verbs:воззреть{}, // воззреть на поле боя rus_verbs:воззриться{}, // воззриться на поле боя rus_verbs:возить{}, // возить туристов на гору rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу rus_verbs:возлагаться{}, // Ответственность возлагается на начальство rus_verbs:возлечь{}, // возлечь на лежанку rus_verbs:возложить{}, // возложить цветы на могилу поэта rus_verbs:вознести{}, // вознести кого-то на вершину славы rus_verbs:возноситься{}, // возносится на вершину успеха rus_verbs:возносить{}, // возносить счастливчика на вершину успеха rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж rus_verbs:подняться{}, // Мы поднялись на восьмой этаж rus_verbs:вонять{}, // Кусок сыра воняет на всю округу rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги rus_verbs:ворчать{}, // Старый пес ворчит на прохожих rus_verbs:воспринимать{}, // воспринимать сообщение на слух rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух rus_verbs:воспринять{}, // воспринять сообщение на слух rus_verbs:восприняться{}, // восприняться на слух rus_verbs:воссесть{}, // Коля воссел на трон rus_verbs:вправить{}, // вправить мозг на место rus_verbs:вправлять{}, // вправлять мозги на место rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:врубать{}, // врубать на полную мощность rus_verbs:врубить{}, // врубить на полную мощность rus_verbs:врубиться{}, // врубиться на полную мощность rus_verbs:врываться{}, // врываться на собрание rus_verbs:вскарабкаться{}, // вскарабкаться на утёс rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс rus_verbs:вскочить{}, // вскочить на ноги rus_verbs:всплывать{}, // всплывать на поверхность воды rus_verbs:всплыть{}, // всплыть на поверхность воды rus_verbs:вспрыгивать{}, // вспрыгивать на платформу rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу rus_verbs:встать{}, // встать на защиту чести и достоинства rus_verbs:вторгаться{}, // вторгаться на чужую территорию rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию rus_verbs:въезжать{}, // въезжать на пандус rus_verbs:наябедничать{}, // наябедничать на соседа по парте rus_verbs:выблевать{}, // выблевать завтрак на пол rus_verbs:выблеваться{}, // выблеваться на пол rus_verbs:выблевывать{}, // выблевывать завтрак на пол rus_verbs:выблевываться{}, // выблевываться на пол rus_verbs:вывезти{}, // вывезти мусор на свалку rus_verbs:вывесить{}, // вывесить белье на просушку rus_verbs:вывести{}, // вывести собаку на прогулку rus_verbs:вывешивать{}, // вывешивать белье на веревку rus_verbs:вывозить{}, // вывозить детей на природу rus_verbs:вызывать{}, // Начальник вызывает на ковер rus_verbs:выйти{}, // выйти на свободу rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение rus_verbs:выливать{}, // выливать на землю rus_verbs:выливаться{}, // выливаться на землю rus_verbs:вылить{}, // вылить жидкость на землю rus_verbs:вылиться{}, // Топливо вылилось на землю rus_verbs:выложить{}, // выложить на берег rus_verbs:выменивать{}, // выменивать золото на хлеб rus_verbs:вымениваться{}, // Золото выменивается на хлеб rus_verbs:выменять{}, // выменять золото на хлеб rus_verbs:выпадать{}, // снег выпадает на землю rus_verbs:выплевывать{}, // выплевывать на землю rus_verbs:выплевываться{}, // выплевываться на землю rus_verbs:выплескать{}, // выплескать на землю rus_verbs:выплескаться{}, // выплескаться на землю rus_verbs:выплескивать{}, // выплескивать на землю rus_verbs:выплескиваться{}, // выплескиваться на землю rus_verbs:выплывать{}, // выплывать на поверхность rus_verbs:выплыть{}, // выплыть на поверхность rus_verbs:выплюнуть{}, // выплюнуть на пол rus_verbs:выползать{}, // выползать на свежий воздух rus_verbs:выпроситься{}, // выпроситься на улицу rus_verbs:выпрыгивать{}, // выпрыгивать на свободу rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон rus_verbs:выпускать{}, // выпускать на свободу rus_verbs:выпустить{}, // выпустить на свободу rus_verbs:выпучивать{}, // выпучивать на кого-то глаза rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то rus_verbs:выпучить{}, // выпучить глаза на кого-то rus_verbs:выпучиться{}, // выпучиться на кого-то rus_verbs:выронить{}, // выронить на землю rus_verbs:высадить{}, // высадить на берег rus_verbs:высадиться{}, // высадиться на берег rus_verbs:высаживаться{}, // высаживаться на остров rus_verbs:выскальзывать{}, // выскальзывать на землю rus_verbs:выскочить{}, // выскочить на сцену rus_verbs:высморкаться{}, // высморкаться на землю rus_verbs:высморкнуться{}, // высморкнуться на землю rus_verbs:выставить{}, // выставить на всеобщее обозрение rus_verbs:выставиться{}, // выставиться на всеобщее обозрение rus_verbs:выставлять{}, // выставлять на всеобщее обозрение rus_verbs:выставляться{}, // выставляться на всеобщее обозрение инфинитив:высыпать{вид:соверш}, // высыпать на землю инфинитив:высыпать{вид:несоверш}, глагол:высыпать{вид:соверш}, глагол:высыпать{вид:несоверш}, деепричастие:высыпав{}, деепричастие:высыпая{}, прилагательное:высыпавший{вид:соверш}, //++прилагательное:высыпавший{вид:несоверш}, прилагательное:высыпающий{вид:несоверш}, rus_verbs:высыпаться{}, // высыпаться на землю rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя rus_verbs:вытаращиваться{}, // вытаращиваться на медведя rus_verbs:вытаращить{}, // вытаращить глаза на медведя rus_verbs:вытаращиться{}, // вытаращиться на медведя rus_verbs:вытекать{}, // вытекать на землю rus_verbs:вытечь{}, // вытечь на землю rus_verbs:выучиваться{}, // выучиваться на кого-то rus_verbs:выучиться{}, // выучиться на кого-то rus_verbs:посмотреть{}, // посмотреть на экран rus_verbs:нашить{}, // нашить что-то на одежду rus_verbs:придти{}, // придти на помощь кому-то инфинитив:прийти{}, // прийти на помощь кому-то глагол:прийти{}, деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты. rus_verbs:поднять{}, // поднять на вершину rus_verbs:согласиться{}, // согласиться на ничью rus_verbs:послать{}, // послать на фронт rus_verbs:слать{}, // слать на фронт rus_verbs:надеяться{}, // надеяться на лучшее rus_verbs:крикнуть{}, // крикнуть на шалунов rus_verbs:пройти{}, // пройти на пляж rus_verbs:прислать{}, // прислать на экспертизу rus_verbs:жить{}, // жить на подачки rus_verbs:становиться{}, // становиться на ноги rus_verbs:наслать{}, // наслать на кого-то rus_verbs:принять{}, // принять на заметку rus_verbs:собираться{}, // собираться на экзамен rus_verbs:оставить{}, // оставить на всякий случай rus_verbs:звать{}, // звать на помощь rus_verbs:направиться{}, // направиться на прогулку rus_verbs:отвечать{}, // отвечать на звонки rus_verbs:отправиться{}, // отправиться на прогулку rus_verbs:поставить{}, // поставить на пол rus_verbs:обернуться{}, // обернуться на зов rus_verbs:отозваться{}, // отозваться на просьбу rus_verbs:закричать{}, // закричать на собаку rus_verbs:опустить{}, // опустить на землю rus_verbs:принести{}, // принести на пляж свой жезлонг rus_verbs:указать{}, // указать на дверь rus_verbs:ходить{}, // ходить на занятия rus_verbs:уставиться{}, // уставиться на листок rus_verbs:приходить{}, // приходить на экзамен rus_verbs:махнуть{}, // махнуть на пляж rus_verbs:явиться{}, // явиться на допрос rus_verbs:оглянуться{}, // оглянуться на дорогу rus_verbs:уехать{}, // уехать на заработки rus_verbs:повести{}, // повести на штурм rus_verbs:опуститься{}, // опуститься на колени //rus_verbs:передать{}, // передать на проверку rus_verbs:побежать{}, // побежать на занятия rus_verbs:прибыть{}, // прибыть на место службы rus_verbs:кричать{}, // кричать на медведя rus_verbs:стечь{}, // стечь на землю rus_verbs:обратить{}, // обратить на себя внимание rus_verbs:подать{}, // подать на пропитание rus_verbs:привести{}, // привести на съемки rus_verbs:испытывать{}, // испытывать на животных rus_verbs:перевести{}, // перевести на жену rus_verbs:купить{}, // купить на заемные деньги rus_verbs:собраться{}, // собраться на встречу rus_verbs:заглянуть{}, // заглянуть на огонёк rus_verbs:нажать{}, // нажать на рычаг rus_verbs:поспешить{}, // поспешить на праздник rus_verbs:перейти{}, // перейти на русский язык rus_verbs:поверить{}, // поверить на честное слово rus_verbs:глянуть{}, // глянуть на обложку rus_verbs:зайти{}, // зайти на огонёк rus_verbs:проходить{}, // проходить на сцену rus_verbs:глядеть{}, // глядеть на актрису //rus_verbs:решиться{}, // решиться на прыжок rus_verbs:пригласить{}, // пригласить на танец rus_verbs:позвать{}, // позвать на экзамен rus_verbs:усесться{}, // усесться на стул rus_verbs:поступить{}, // поступить на математический факультет rus_verbs:лечь{}, // лечь на живот rus_verbs:потянуться{}, // потянуться на юг rus_verbs:присесть{}, // присесть на корточки rus_verbs:наступить{}, // наступить на змею rus_verbs:заорать{}, // заорать на попрошаек rus_verbs:надеть{}, // надеть на голову rus_verbs:поглядеть{}, // поглядеть на девчонок rus_verbs:принимать{}, // принимать на гарантийное обслуживание rus_verbs:привезти{}, // привезти на испытания rus_verbs:рухнуть{}, // рухнуть на асфальт rus_verbs:пускать{}, // пускать на корм rus_verbs:отвести{}, // отвести на приём rus_verbs:отправить{}, // отправить на утилизацию rus_verbs:двигаться{}, // двигаться на восток rus_verbs:нести{}, // нести на пляж rus_verbs:падать{}, // падать на руки rus_verbs:откинуться{}, // откинуться на спинку кресла rus_verbs:рявкнуть{}, // рявкнуть на детей rus_verbs:получать{}, // получать на проживание rus_verbs:полезть{}, // полезть на рожон rus_verbs:направить{}, // направить на дообследование rus_verbs:приводить{}, // приводить на проверку rus_verbs:потребоваться{}, // потребоваться на замену rus_verbs:кинуться{}, // кинуться на нападавшего rus_verbs:учиться{}, // учиться на токаря rus_verbs:приподнять{}, // приподнять на один метр rus_verbs:налить{}, // налить на стол rus_verbs:играть{}, // играть на деньги rus_verbs:рассчитывать{}, // рассчитывать на подмогу rus_verbs:шепнуть{}, // шепнуть на ухо rus_verbs:швырнуть{}, // швырнуть на землю rus_verbs:прыгнуть{}, // прыгнуть на оленя rus_verbs:предлагать{}, // предлагать на выбор rus_verbs:садиться{}, // садиться на стул rus_verbs:лить{}, // лить на землю rus_verbs:испытать{}, // испытать на животных rus_verbs:фыркнуть{}, // фыркнуть на детеныша rus_verbs:годиться{}, // мясо годится на фарш rus_verbs:проверить{}, // проверить высказывание на истинность rus_verbs:откликнуться{}, // откликнуться на призывы rus_verbs:полагаться{}, // полагаться на интуицию rus_verbs:покоситься{}, // покоситься на соседа rus_verbs:повесить{}, // повесить на гвоздь инфинитив:походить{вид:соверш}, // походить на занятия глагол:походить{вид:соверш}, деепричастие:походив{}, прилагательное:походивший{}, rus_verbs:помчаться{}, // помчаться на экзамен rus_verbs:ставить{}, // ставить на контроль rus_verbs:свалиться{}, // свалиться на землю rus_verbs:валиться{}, // валиться на землю rus_verbs:подарить{}, // подарить на день рожденья rus_verbs:сбежать{}, // сбежать на необитаемый остров rus_verbs:стрелять{}, // стрелять на поражение rus_verbs:обращать{}, // обращать на себя внимание rus_verbs:наступать{}, // наступать на те же грабли rus_verbs:сбросить{}, // сбросить на землю rus_verbs:обидеться{}, // обидеться на друга rus_verbs:устроиться{}, // устроиться на стажировку rus_verbs:погрузиться{}, // погрузиться на большую глубину rus_verbs:течь{}, // течь на землю rus_verbs:отбросить{}, // отбросить на землю rus_verbs:метать{}, // метать на дно rus_verbs:пустить{}, // пустить на переплавку rus_verbs:прожить{}, // прожить на пособие rus_verbs:полететь{}, // полететь на континент rus_verbs:пропустить{}, // пропустить на сцену rus_verbs:указывать{}, // указывать на ошибку rus_verbs:наткнуться{}, // наткнуться на клад rus_verbs:рвануть{}, // рвануть на юг rus_verbs:ступать{}, // ступать на землю rus_verbs:спрыгнуть{}, // спрыгнуть на берег rus_verbs:заходить{}, // заходить на огонёк rus_verbs:нырнуть{}, // нырнуть на глубину rus_verbs:рвануться{}, // рвануться на свободу rus_verbs:натянуть{}, // натянуть на голову rus_verbs:забраться{}, // забраться на стол rus_verbs:помахать{}, // помахать на прощание rus_verbs:содержать{}, // содержать на спонсорскую помощь rus_verbs:приезжать{}, // приезжать на праздники rus_verbs:проникнуть{}, // проникнуть на территорию rus_verbs:подъехать{}, // подъехать на митинг rus_verbs:устремиться{}, // устремиться на волю rus_verbs:посадить{}, // посадить на стул rus_verbs:ринуться{}, // ринуться на голкипера rus_verbs:подвигнуть{}, // подвигнуть на подвиг rus_verbs:отдавать{}, // отдавать на перевоспитание rus_verbs:отложить{}, // отложить на черный день rus_verbs:убежать{}, // убежать на танцы rus_verbs:поднимать{}, // поднимать на верхний этаж rus_verbs:переходить{}, // переходить на цифровой сигнал rus_verbs:отослать{}, // отослать на переаттестацию rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола rus_verbs:назначить{}, // назначить на должность rus_verbs:осесть{}, // осесть на дно rus_verbs:торопиться{}, // торопиться на экзамен rus_verbs:менять{}, // менять на еду rus_verbs:доставить{}, // доставить на шестой этаж rus_verbs:заслать{}, // заслать на проверку rus_verbs:дуть{}, // дуть на воду rus_verbs:сослать{}, // сослать на каторгу rus_verbs:останавливаться{}, // останавливаться на отдых rus_verbs:сдаваться{}, // сдаваться на милость победителя rus_verbs:сослаться{}, // сослаться на презумпцию невиновности rus_verbs:рассердиться{}, // рассердиться на дочь rus_verbs:кинуть{}, // кинуть на землю rus_verbs:расположиться{}, // расположиться на ночлег rus_verbs:осмелиться{}, // осмелиться на подлог rus_verbs:шептать{}, // шептать на ушко rus_verbs:уронить{}, // уронить на землю rus_verbs:откинуть{}, // откинуть на спинку кресла rus_verbs:перенести{}, // перенести на рабочий стол rus_verbs:сдаться{}, // сдаться на милость победителя rus_verbs:светить{}, // светить на дорогу rus_verbs:мчаться{}, // мчаться на бал rus_verbs:нестись{}, // нестись на свидание rus_verbs:поглядывать{}, // поглядывать на экран rus_verbs:орать{}, // орать на детей rus_verbs:уложить{}, // уложить на лопатки rus_verbs:решаться{}, // решаться на поступок rus_verbs:попадать{}, // попадать на карандаш rus_verbs:сплюнуть{}, // сплюнуть на землю rus_verbs:снимать{}, // снимать на телефон rus_verbs:опоздать{}, // опоздать на работу rus_verbs:посылать{}, // посылать на проверку rus_verbs:погнать{}, // погнать на пастбище rus_verbs:поступать{}, // поступать на кибернетический факультет rus_verbs:спускаться{}, // спускаться на уровень моря rus_verbs:усадить{}, // усадить на диван rus_verbs:проиграть{}, // проиграть на спор rus_verbs:прилететь{}, // прилететь на фестиваль rus_verbs:повалиться{}, // повалиться на спину rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина rus_verbs:задавать{}, // задавать на выходные rus_verbs:запасть{}, // запасть на девочку rus_verbs:лезть{}, // лезть на забор rus_verbs:потащить{}, // потащить на выборы rus_verbs:направляться{}, // направляться на экзамен rus_verbs:определять{}, // определять на вкус rus_verbs:поползти{}, // поползти на стену rus_verbs:поплыть{}, // поплыть на берег rus_verbs:залезть{}, // залезть на яблоню rus_verbs:сдать{}, // сдать на мясокомбинат rus_verbs:приземлиться{}, // приземлиться на дорогу rus_verbs:лаять{}, // лаять на прохожих rus_verbs:перевернуть{}, // перевернуть на бок rus_verbs:ловить{}, // ловить на живца rus_verbs:отнести{}, // отнести животное на хирургический стол rus_verbs:плюнуть{}, // плюнуть на условности rus_verbs:передавать{}, // передавать на проверку rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали инфинитив:рассыпаться{вид:соверш}, глагол:рассыпаться{вид:несоверш}, глагол:рассыпаться{вид:соверш}, деепричастие:рассыпавшись{}, деепричастие:рассыпаясь{}, прилагательное:рассыпавшийся{вид:несоверш}, прилагательное:рассыпавшийся{вид:соверш}, прилагательное:рассыпающийся{}, rus_verbs:зарычать{}, // Медведица зарычала на медвежонка rus_verbs:призвать{}, // призвать на сборы rus_verbs:увезти{}, // увезти на дачу rus_verbs:содержаться{}, // содержаться на пожертвования rus_verbs:навести{}, // навести на скопление телескоп rus_verbs:отправляться{}, // отправляться на утилизацию rus_verbs:улечься{}, // улечься на животик rus_verbs:налететь{}, // налететь на препятствие rus_verbs:перевернуться{}, // перевернуться на спину rus_verbs:улететь{}, // улететь на родину rus_verbs:ложиться{}, // ложиться на бок rus_verbs:класть{}, // класть на место rus_verbs:отреагировать{}, // отреагировать на выступление rus_verbs:доставлять{}, // доставлять на дом rus_verbs:отнять{}, // отнять на благо правящей верхушки rus_verbs:ступить{}, // ступить на землю rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы rus_verbs:унести{}, // унести на работу rus_verbs:сходить{}, // сходить на концерт rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги rus_verbs:соскочить{}, // соскочить на землю rus_verbs:пожаловаться{}, // пожаловаться на соседей rus_verbs:тащить{}, // тащить на замену rus_verbs:замахать{}, // замахать руками на паренька rus_verbs:заглядывать{}, // заглядывать на обед rus_verbs:соглашаться{}, // соглашаться на равный обмен rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик rus_verbs:увести{}, // увести на осмотр rus_verbs:успевать{}, // успевать на контрольную работу rus_verbs:опрокинуть{}, // опрокинуть на себя rus_verbs:подавать{}, // подавать на апелляцию rus_verbs:прибежать{}, // прибежать на вокзал rus_verbs:отшвырнуть{}, // отшвырнуть на замлю rus_verbs:привлекать{}, // привлекать на свою сторону rus_verbs:опереться{}, // опереться на палку rus_verbs:перебраться{}, // перебраться на маленький островок rus_verbs:уговорить{}, // уговорить на новые траты rus_verbs:гулять{}, // гулять на спонсорские деньги rus_verbs:переводить{}, // переводить на другой путь rus_verbs:заколебаться{}, // заколебаться на один миг rus_verbs:зашептать{}, // зашептать на ушко rus_verbs:привстать{}, // привстать на цыпочки rus_verbs:хлынуть{}, // хлынуть на берег rus_verbs:наброситься{}, // наброситься на еду rus_verbs:напасть{}, // повстанцы, напавшие на конвой rus_verbs:убрать{}, // книга, убранная на полку rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию rus_verbs:засматриваться{}, // засматриваться на девчонок rus_verbs:застегнуться{}, // застегнуться на все пуговицы rus_verbs:провериться{}, // провериться на заболевания rus_verbs:проверяться{}, // проверяться на заболевания rus_verbs:тестировать{}, // тестировать на профпригодность rus_verbs:протестировать{}, // протестировать на профпригодность rus_verbs:уходить{}, // отец, уходящий на работу rus_verbs:налипнуть{}, // снег, налипший на провода rus_verbs:налипать{}, // снег, налипающий на провода rus_verbs:улетать{}, // Многие птицы улетают осенью на юг. rus_verbs:поехать{}, // она поехала на встречу с заказчиком rus_verbs:переключать{}, // переключать на резервную линию rus_verbs:переключаться{}, // переключаться на резервную линию rus_verbs:подписаться{}, // подписаться на обновление rus_verbs:нанести{}, // нанести на кожу rus_verbs:нарываться{}, // нарываться на неприятности rus_verbs:выводить{}, // выводить на орбиту rus_verbs:вернуться{}, // вернуться на родину rus_verbs:возвращаться{}, // возвращаться на родину прилагательное:падкий{}, // Он падок на деньги. прилагательное:обиженный{}, // Он обижен на отца. rus_verbs:косить{}, // Он косит на оба глаза. rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок. прилагательное:готовый{}, // Он готов на всякие жертвы. rus_verbs:говорить{}, // Он говорит на скользкую тему. прилагательное:глухой{}, // Он глух на одно ухо. rus_verbs:взять{}, // Он взял ребёнка себе на колени. rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия. rus_verbs:вести{}, // Лестница ведёт на третий этаж. rus_verbs:уполномочивать{}, // уполномочивать на что-либо глагол:спешить{ вид:несоверш }, // Я спешу на поезд. rus_verbs:брать{}, // Я беру всю ответственность на себя. rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление. rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики. rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку. rus_verbs:разбираться{}, // Эта машина разбирается на части. rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние. rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп. rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье. rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно. rus_verbs:делиться{}, // Тридцать делится на пять без остатка. rus_verbs:удаляться{}, // Суд удаляется на совещание. rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север. rus_verbs:сохранить{}, // Сохраните это на память обо мне. rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию. rus_verbs:лететь{}, // Самолёт летит на север. rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров. // rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи. rus_verbs:смотреть{}, // Она смотрит на нас из окна. rus_verbs:отдать{}, // Она отдала мне деньги на сохранение. rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину. rus_verbs:любоваться{}, // гости любовались на картину rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь. прилагательное:действительный{}, // Прививка оспы действительна только на три года. rus_verbs:спуститься{}, // На город спустился смог прилагательное:нечистый{}, // Он нечист на руку. прилагательное:неспособный{}, // Он неспособен на такую низость. прилагательное:злой{}, // кот очень зол на хозяина rus_verbs:пойти{}, // Девочка не пошла на урок физультуры rus_verbs:прибывать{}, // мой поезд прибывает на первый путь rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу rus_verbs:идти{}, // Дело идёт на лад. rus_verbs:лазить{}, // Он лазил на чердак. rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры. // rus_verbs:действовать{}, // действующий на нервы rus_verbs:выходить{}, // Балкон выходит на площадь. rus_verbs:работать{}, // Время работает на нас. глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина. rus_verbs:бросить{}, // Они бросили все силы на строительство. // глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков. rus_verbs:броситься{}, // Она радостно бросилась мне на шею. rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью. rus_verbs:ответить{}, // Она не ответила на мой поклон. rus_verbs:нашивать{}, // Она нашивала заплату на локоть. rus_verbs:молиться{}, // Она молится на свою мать. rus_verbs:запереть{}, // Она заперла дверь на замок. rus_verbs:заявить{}, // Она заявила свои права на наследство. rus_verbs:уйти{}, // Все деньги ушли на путешествие. rus_verbs:вступить{}, // Водолаз вступил на берег. rus_verbs:сойти{}, // Ночь сошла на землю. rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано. rus_verbs:рыдать{}, // Не рыдай так безумно над ним. rus_verbs:подписать{}, // Не забудьте подписать меня на газету. rus_verbs:держать{}, // Наш пароход держал курс прямо на север. rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира. rus_verbs:ехать{}, // Мы сейчас едем на завод. rus_verbs:выбросить{}, // Волнами лодку выбросило на берег. ГЛ_ИНФ(сесть), // сесть на снег ГЛ_ИНФ(записаться), ГЛ_ИНФ(положить) // положи книгу на стол } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: залить на youtube fact гл_предл { if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} } then return true } fact гл_предл { if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } } then return true } // смещаться на несколько миллиметров fact гл_предл { if context { Гл_НА_Вин предлог:на{} наречие:*{} } then return true } // партия взяла на себя нереалистичные обязательства fact гл_предл { if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} } then return true } #endregion ВИНИТЕЛЬНЫЙ // Все остальные варианты с предлогом 'НА' по умолчанию запрещаем. fact гл_предл { if context { * предлог:на{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:вин } } then return false,-4 } // Этот вариант нужен для обработки конструкций с числительными: // Президентские выборы разделили Венесуэлу на два непримиримых лагеря fact гл_предл { if context { * предлог:на{} *:*{ падеж:род } } then return false,-4 } // Продавать на eBay fact гл_предл { if context { * предлог:на{} * } then return false,-6 } #endregion Предлог_НА #region Предлог_С // ------------- ПРЕДЛОГ 'С' ----------------- // У этого предлога предпочтительная семантика привязывает его обычно к существительному. // Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим. #region ТВОРИТЕЛЬНЫЙ wordentry_set Гл_С_Твор={ rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться rus_verbs:забраться{}, rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ) rus_verbs:БИТЬСЯ{}, // rus_verbs:ПОДРАТЬСЯ{}, // прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ) rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ) rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ) rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ) rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ) прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом. rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ) rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ) rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ) rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ) rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ) rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ) rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ) rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ) rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ) rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ) rus_verbs:отправить{}, // вы можете отправить со мной человека rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор) rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С) rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С) прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С) rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С) rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С) rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С) rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С) rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С) rus_verbs:СВЫКАТЬСЯ{}, rus_verbs:стаскиваться{}, rus_verbs:спиливаться{}, rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С) rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор) rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С) rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С) rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С) rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С) rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С) rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С) rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С) rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С) rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С) rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор) rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С) rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С) rus_verbs:согласиться{}, // с этим согласились все (согласиться с) rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор) rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С) rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С) rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор) rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор) rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С) rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С) rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор) rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор) rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор) rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор) rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор) rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор) rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор) rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор) rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор) rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ) rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ) rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много) rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С) rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С) rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С) rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С) rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С) rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор) rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С) rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С) rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С) rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С) rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С) инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара. инфинитив:кристаллизоваться{ вид:несоверш }, глагол:кристаллизоваться{ вид:соверш }, глагол:кристаллизоваться{ вид:несоверш }, rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С) rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С) rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С) rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С) rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С) rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор) rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С) rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С) rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с) rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с) rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с) rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с) rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело. rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором rus_verbs:стирать{}, // стирать с мылом рубашку в тазу rus_verbs:прыгать{}, // парашютист прыгает с парашютом rus_verbs:выступить{}, // Он выступил с приветствием съезду. rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят. rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой. rus_verbs:вставать{}, // он встаёт с зарёй rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером. rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью. rus_verbs:договориться{}, // мы договоримся с вами rus_verbs:побыть{}, // он хотел побыть с тобой rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью rus_verbs:вязаться{}, // вязаться с фактами rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:относиться{}, // относиться с пониманием rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов. rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней rus_verbs:гулять{}, // бабушка гуляет с внуком rus_verbs:разбираться{}, // разбираться с задачей rus_verbs:сверить{}, // Данные были сверены с эталонными значениями rus_verbs:делать{}, // Что делать со старым телефоном rus_verbs:осматривать{}, // осматривать с удивлением rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре rus_verbs:попрощаться{}, // попрощаться с талантливым актером rus_verbs:задремать{}, // задремать с кружкой чая в руке rus_verbs:связать{}, // связать катастрофу с действиями конкурентов rus_verbs:носиться{}, // носиться с безумной идеей rus_verbs:кончать{}, // кончать с собой rus_verbs:обмениваться{}, // обмениваться с собеседниками rus_verbs:переговариваться{}, // переговариваться с маяком rus_verbs:общаться{}, // общаться с полицией rus_verbs:завершить{}, // завершить с ошибкой rus_verbs:обняться{}, // обняться с подругой rus_verbs:сливаться{}, // сливаться с фоном rus_verbs:смешаться{}, // смешаться с толпой rus_verbs:договариваться{}, // договариваться с потерпевшим rus_verbs:обедать{}, // обедать с гостями rus_verbs:сообщаться{}, // сообщаться с подземной рекой rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц rus_verbs:читаться{}, // читаться с трудом rus_verbs:смириться{}, // смириться с утратой rus_verbs:разделить{}, // разделить с другими ответственность rus_verbs:роднить{}, // роднить с медведем rus_verbs:медлить{}, // медлить с ответом rus_verbs:скрестить{}, // скрестить с ужом rus_verbs:покоиться{}, // покоиться с миром rus_verbs:делиться{}, // делиться с друзьями rus_verbs:познакомить{}, // познакомить с Олей rus_verbs:порвать{}, // порвать с Олей rus_verbs:завязать{}, // завязать с Олей знакомство rus_verbs:суетиться{}, // суетиться с изданием романа rus_verbs:соединиться{}, // соединиться с сервером rus_verbs:справляться{}, // справляться с нуждой rus_verbs:замешкаться{}, // замешкаться с ответом rus_verbs:поссориться{}, // поссориться с подругой rus_verbs:ссориться{}, // ссориться с друзьями rus_verbs:торопить{}, // торопить с решением rus_verbs:поздравить{}, // поздравить с победой rus_verbs:проститься{}, // проститься с человеком rus_verbs:поработать{}, // поработать с деревом rus_verbs:приключиться{}, // приключиться с Колей rus_verbs:сговориться{}, // сговориться с Ваней rus_verbs:отъехать{}, // отъехать с ревом rus_verbs:объединять{}, // объединять с другой кампанией rus_verbs:употребить{}, // употребить с молоком rus_verbs:перепутать{}, // перепутать с другой книгой rus_verbs:запоздать{}, // запоздать с ответом rus_verbs:подружиться{}, // подружиться с другими детьми rus_verbs:дружить{}, // дружить с Сережей rus_verbs:поравняться{}, // поравняться с финишной чертой rus_verbs:ужинать{}, // ужинать с гостями rus_verbs:расставаться{}, // расставаться с приятелями rus_verbs:завтракать{}, // завтракать с семьей rus_verbs:объединиться{}, // объединиться с соседями rus_verbs:сменяться{}, // сменяться с напарником rus_verbs:соединить{}, // соединить с сетью rus_verbs:разговориться{}, // разговориться с охранником rus_verbs:преподнести{}, // преподнести с помпой rus_verbs:напечатать{}, // напечатать с картинками rus_verbs:соединять{}, // соединять с сетью rus_verbs:расправиться{}, // расправиться с беззащитным человеком rus_verbs:распрощаться{}, // распрощаться с деньгами rus_verbs:сравнить{}, // сравнить с конкурентами rus_verbs:ознакомиться{}, // ознакомиться с выступлением инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{}, rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия rus_verbs:прощаться{}, // прощаться с боевым товарищем rus_verbs:сравнивать{}, // сравнивать с конкурентами rus_verbs:складывать{}, // складывать с весом упаковки rus_verbs:повестись{}, // повестись с ворами rus_verbs:столкнуть{}, // столкнуть с отбойником rus_verbs:переглядываться{}, // переглядываться с соседом rus_verbs:поторопить{}, // поторопить с откликом rus_verbs:развлекаться{}, // развлекаться с подружками rus_verbs:заговаривать{}, // заговаривать с незнакомцами rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим деепричастие:согласуясь{}, прилагательное:согласующийся{}, rus_verbs:совпасть{}, // совпасть с оригиналом rus_verbs:соединяться{}, // соединяться с куратором rus_verbs:повстречаться{}, // повстречаться с героями rus_verbs:поужинать{}, // поужинать с родителями rus_verbs:развестись{}, // развестись с первым мужем rus_verbs:переговорить{}, // переговорить с коллегами rus_verbs:сцепиться{}, // сцепиться с бродячей собакой rus_verbs:сожрать{}, // сожрать с потрохами rus_verbs:побеседовать{}, // побеседовать со шпаной rus_verbs:поиграть{}, // поиграть с котятами rus_verbs:сцепить{}, // сцепить с тягачом rus_verbs:помириться{}, // помириться с подружкой rus_verbs:связываться{}, // связываться с бандитами rus_verbs:совещаться{}, // совещаться с мастерами rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой rus_verbs:переплестись{}, // переплестись с кустами rus_verbs:мутить{}, // мутить с одногрупницами rus_verbs:приглядываться{}, // приглядываться с интересом rus_verbs:сблизиться{}, // сблизиться с врагами rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой rus_verbs:растереть{}, // растереть с солью rus_verbs:смешиваться{}, // смешиваться с известью rus_verbs:соприкоснуться{}, // соприкоснуться с тайной rus_verbs:ладить{}, // ладить с родственниками rus_verbs:сотрудничать{}, // сотрудничать с органами дознания rus_verbs:съехаться{}, // съехаться с родственниками rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов rus_verbs:советоваться{}, // советоваться с отчимом rus_verbs:сравниться{}, // сравниться с лучшими rus_verbs:знакомиться{}, // знакомиться с абитуриентами rus_verbs:нырять{}, // нырять с аквалангом rus_verbs:забавляться{}, // забавляться с куклой rus_verbs:перекликаться{}, // перекликаться с другой статьей rus_verbs:тренироваться{}, // тренироваться с партнершей rus_verbs:поспорить{}, // поспорить с казночеем инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш }, rus_verbs:примириться{}, // примириться с утратой rus_verbs:раскланяться{}, // раскланяться с фрейлинами rus_verbs:слечь{}, // слечь с ангиной rus_verbs:соприкасаться{}, // соприкасаться со стеной rus_verbs:смешать{}, // смешать с грязью rus_verbs:пересекаться{}, // пересекаться с трассой rus_verbs:путать{}, // путать с государственной шерстью rus_verbs:поболтать{}, // поболтать с ученицами rus_verbs:здороваться{}, // здороваться с профессором rus_verbs:просчитаться{}, // просчитаться с покупкой rus_verbs:сторожить{}, // сторожить с собакой rus_verbs:обыскивать{}, // обыскивать с собаками rus_verbs:переплетаться{}, // переплетаться с другой веткой rus_verbs:обниматься{}, // обниматься с Ксюшей rus_verbs:объединяться{}, // объединяться с конкурентами rus_verbs:погорячиться{}, // погорячиться с покупкой rus_verbs:мыться{}, // мыться с мылом rus_verbs:свериться{}, // свериться с эталоном rus_verbs:разделаться{}, // разделаться с кем-то rus_verbs:чередоваться{}, // чередоваться с партнером rus_verbs:налететь{}, // налететь с соратниками rus_verbs:поспать{}, // поспать с включенным светом rus_verbs:управиться{}, // управиться с собакой rus_verbs:согрешить{}, // согрешить с замужней rus_verbs:определиться{}, // определиться с победителем rus_verbs:перемешаться{}, // перемешаться с гранулами rus_verbs:затрудняться{}, // затрудняться с ответом rus_verbs:обождать{}, // обождать со стартом rus_verbs:фыркать{}, // фыркать с презрением rus_verbs:засидеться{}, // засидеться с приятелем rus_verbs:крепнуть{}, // крепнуть с годами rus_verbs:пировать{}, // пировать с дружиной rus_verbs:щебетать{}, // щебетать с сестричками rus_verbs:маяться{}, // маяться с кашлем rus_verbs:сближать{}, // сближать с центральным светилом rus_verbs:меркнуть{}, // меркнуть с возрастом rus_verbs:заспорить{}, // заспорить с оппонентами rus_verbs:граничить{}, // граничить с Ливаном rus_verbs:перестараться{}, // перестараться со стимуляторами rus_verbs:объединить{}, // объединить с филиалом rus_verbs:свыкнуться{}, // свыкнуться с утратой rus_verbs:посоветоваться{}, // посоветоваться с адвокатами rus_verbs:напутать{}, // напутать с ведомостями rus_verbs:нагрянуть{}, // нагрянуть с обыском rus_verbs:посовещаться{}, // посовещаться с судьей rus_verbs:провернуть{}, // провернуть с друганом rus_verbs:разделяться{}, // разделяться с сотрапезниками rus_verbs:пересечься{}, // пересечься с второй колонной rus_verbs:опережать{}, // опережать с большим запасом rus_verbs:перепутаться{}, // перепутаться с другой линией rus_verbs:соотноситься{}, // соотноситься с затратами rus_verbs:смешивать{}, // смешивать с золой rus_verbs:свидеться{}, // свидеться с тобой rus_verbs:переспать{}, // переспать с графиней rus_verbs:поладить{}, // поладить с соседями rus_verbs:протащить{}, // протащить с собой rus_verbs:разминуться{}, // разминуться с встречным потоком rus_verbs:перемежаться{}, // перемежаться с успехами rus_verbs:рассчитаться{}, // рассчитаться с кредиторами rus_verbs:срастись{}, // срастись с телом rus_verbs:знакомить{}, // знакомить с родителями rus_verbs:поругаться{}, // поругаться с родителями rus_verbs:совладать{}, // совладать с чувствами rus_verbs:обручить{}, // обручить с богатой невестой rus_verbs:сближаться{}, // сближаться с вражеским эсминцем rus_verbs:замутить{}, // замутить с Ксюшей rus_verbs:повозиться{}, // повозиться с настройкой rus_verbs:торговаться{}, // торговаться с продавцами rus_verbs:уединиться{}, // уединиться с девчонкой rus_verbs:переборщить{}, // переборщить с добавкой rus_verbs:ознакомить{}, // ознакомить с пожеланиями rus_verbs:прочесывать{}, // прочесывать с собаками rus_verbs:переписываться{}, // переписываться с корреспондентами rus_verbs:повздорить{}, // повздорить с сержантом rus_verbs:разлучить{}, // разлучить с семьей rus_verbs:соседствовать{}, // соседствовать с цыганами rus_verbs:застукать{}, // застукать с проститутками rus_verbs:напуститься{}, // напуститься с кулаками rus_verbs:сдружиться{}, // сдружиться с ребятами rus_verbs:соперничать{}, // соперничать с параллельным классом rus_verbs:прочесать{}, // прочесать с собаками rus_verbs:кокетничать{}, // кокетничать с гимназистками rus_verbs:мириться{}, // мириться с убытками rus_verbs:оплошать{}, // оплошать с билетами rus_verbs:отождествлять{}, // отождествлять с литературным героем rus_verbs:хитрить{}, // хитрить с зарплатой rus_verbs:провозиться{}, // провозиться с задачкой rus_verbs:коротать{}, // коротать с друзьями rus_verbs:соревноваться{}, // соревноваться с машиной rus_verbs:уживаться{}, // уживаться с местными жителями rus_verbs:отождествляться{}, // отождествляться с литературным героем rus_verbs:сопоставить{}, // сопоставить с эталоном rus_verbs:пьянствовать{}, // пьянствовать с друзьями rus_verbs:залетать{}, // залетать с паленой водкой rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой rus_verbs:запаздывать{}, // запаздывать с кормлением rus_verbs:таскаться{}, // таскаться с сумками rus_verbs:контрастировать{}, // контрастировать с туфлями rus_verbs:сшибиться{}, // сшибиться с форвардом rus_verbs:состязаться{}, // состязаться с лучшей командой rus_verbs:затрудниться{}, // затрудниться с объяснением rus_verbs:объясниться{}, // объясниться с пострадавшими rus_verbs:разводиться{}, // разводиться со сварливой женой rus_verbs:препираться{}, // препираться с адвокатами rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками rus_verbs:свестись{}, // свестись с нулевым счетом rus_verbs:обговорить{}, // обговорить с директором rus_verbs:обвенчаться{}, // обвенчаться с ведьмой rus_verbs:экспериментировать{}, // экспериментировать с генами rus_verbs:сверять{}, // сверять с таблицей rus_verbs:сверяться{}, // свериться с таблицей rus_verbs:сблизить{}, // сблизить с точкой rus_verbs:гармонировать{}, // гармонировать с обоями rus_verbs:перемешивать{}, // перемешивать с молоком rus_verbs:трепаться{}, // трепаться с сослуживцами rus_verbs:перемигиваться{}, // перемигиваться с соседкой rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем rus_verbs:распить{}, // распить с собутыльниками rus_verbs:скрестись{}, // скрестись с дикой лошадью rus_verbs:передраться{}, // передраться с дворовыми собаками rus_verbs:умыть{}, // умыть с мылом rus_verbs:грызться{}, // грызться с соседями rus_verbs:переругиваться{}, // переругиваться с соседями rus_verbs:доиграться{}, // доиграться со спичками rus_verbs:заладиться{}, // заладиться с подругой rus_verbs:скрещиваться{}, // скрещиваться с дикими видами rus_verbs:повидаться{}, // повидаться с дедушкой rus_verbs:повоевать{}, // повоевать с орками rus_verbs:сразиться{}, // сразиться с лучшим рыцарем rus_verbs:кипятить{}, // кипятить с отбеливателем rus_verbs:усердствовать{}, // усердствовать с наказанием rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером rus_verbs:пошептаться{}, // пошептаться с судьями rus_verbs:сравняться{}, // сравняться с лучшими экземплярами rus_verbs:церемониться{}, // церемониться с пьяницами rus_verbs:консультироваться{}, // консультироваться со специалистами rus_verbs:переусердствовать{}, // переусердствовать с наказанием rus_verbs:проноситься{}, // проноситься с собой rus_verbs:перемешать{}, // перемешать с гипсом rus_verbs:темнить{}, // темнить с долгами rus_verbs:сталкивать{}, // сталкивать с черной дырой rus_verbs:увольнять{}, // увольнять с волчьим билетом rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт rus_verbs:созвониться{}, // созвониться с мамой rus_verbs:спеться{}, // спеться с отъявленными хулиганами rus_verbs:интриговать{}, // интриговать с придворными rus_verbs:приобрести{}, // приобрести со скидкой rus_verbs:задержаться{}, // задержаться со сдачей работы rus_verbs:плавать{}, // плавать со спасательным кругом rus_verbs:якшаться{}, // Не якшайся с врагами инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги инфинитив:ассоциировать{вид:несоверш}, глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги глагол:ассоциировать{вид:несоверш}, //+прилагательное:ассоциировавший{вид:несоверш}, прилагательное:ассоциировавший{вид:соверш}, прилагательное:ассоциирующий{}, деепричастие:ассоциируя{}, деепричастие:ассоциировав{}, rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов //+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом //+глагол:аффилировать{вид:соверш}, прилагательное:аффилированный{}, rus_verbs:баловаться{}, // мальчик баловался с молотком rus_verbs:балясничать{}, // женщина балясничала с товарками rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями rus_verbs:бодаться{}, // теленок бодается с деревом rus_verbs:боксировать{}, // Майкл дважды боксировал с ним rus_verbs:брататься{}, // Солдаты братались с бойцами союзников rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:происходить{}, // Что происходит с мировой экономикой? rus_verbs:произойти{}, // Что произошло с экономикой? rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:водиться{}, // Няня водится с детьми rus_verbs:воевать{}, // Фермеры воевали с волками rus_verbs:возиться{}, // Няня возится с детьми rus_verbs:ворковать{}, // Голубь воркует с голубкой rus_verbs:воссоединиться{}, // Дети воссоединились с семьей rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой rus_verbs:враждовать{}, // враждовать с соседями rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:расстаться{}, // я не могу расстаться с тобой rus_verbs:выдирать{}, // выдирать с мясом rus_verbs:выдираться{}, // выдираться с мясом rus_verbs:вытворить{}, // вытворить что-либо с чем-либо rus_verbs:вытворять{}, // вытворять что-либо с чем-либо rus_verbs:сделать{}, // сделать с чем-то rus_verbs:домыть{}, // домыть с мылом rus_verbs:случиться{}, // случиться с кем-то rus_verbs:остаться{}, // остаться с кем-то rus_verbs:случать{}, // случать с породистым кобельком rus_verbs:послать{}, // послать с весточкой rus_verbs:работать{}, // работать с роботами rus_verbs:провести{}, // провести с девчонками время rus_verbs:заговорить{}, // заговорить с незнакомкой rus_verbs:прошептать{}, // прошептать с придыханием rus_verbs:читать{}, // читать с выражением rus_verbs:слушать{}, // слушать с повышенным вниманием rus_verbs:принести{}, // принести с собой rus_verbs:спать{}, // спать с женщинами rus_verbs:закончить{}, // закончить с приготовлениями rus_verbs:помочь{}, // помочь с перестановкой rus_verbs:уехать{}, // уехать с семьей rus_verbs:случаться{}, // случаться с кем-то rus_verbs:кутить{}, // кутить с проститутками rus_verbs:разговаривать{}, // разговаривать с ребенком rus_verbs:погодить{}, // погодить с ликвидацией rus_verbs:считаться{}, // считаться с чужим мнением rus_verbs:носить{}, // носить с собой rus_verbs:хорошеть{}, // хорошеть с каждым днем rus_verbs:приводить{}, // приводить с собой rus_verbs:прыгнуть{}, // прыгнуть с парашютом rus_verbs:петь{}, // петь с чувством rus_verbs:сложить{}, // сложить с результатом rus_verbs:познакомиться{}, // познакомиться с другими студентами rus_verbs:обращаться{}, // обращаться с животными rus_verbs:съесть{}, // съесть с хлебом rus_verbs:ошибаться{}, // ошибаться с дозировкой rus_verbs:столкнуться{}, // столкнуться с медведем rus_verbs:справиться{}, // справиться с нуждой rus_verbs:торопиться{}, // торопиться с ответом rus_verbs:поздравлять{}, // поздравлять с победой rus_verbs:объясняться{}, // объясняться с начальством rus_verbs:пошутить{}, // пошутить с подругой rus_verbs:поздороваться{}, // поздороваться с коллегами rus_verbs:поступать{}, // Как поступать с таким поведением? rus_verbs:определяться{}, // определяться с кандидатами rus_verbs:связаться{}, // связаться с поставщиком rus_verbs:спорить{}, // спорить с собеседником rus_verbs:разобраться{}, // разобраться с делами rus_verbs:ловить{}, // ловить с удочкой rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос rus_verbs:шутить{}, // шутить с диким зверем rus_verbs:разорвать{}, // разорвать с поставщиком контракт rus_verbs:увезти{}, // увезти с собой rus_verbs:унести{}, // унести с собой rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее rus_verbs:складываться{}, // складываться с первым импульсом rus_verbs:соглашаться{}, // соглашаться с предложенным договором //rus_verbs:покончить{}, // покончить с развратом rus_verbs:прихватить{}, // прихватить с собой rus_verbs:похоронить{}, // похоронить с почестями rus_verbs:связывать{}, // связывать с компанией свою судьбу rus_verbs:совпадать{}, // совпадать с предсказанием rus_verbs:танцевать{}, // танцевать с девушками rus_verbs:поделиться{}, // поделиться с выжившими rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате. rus_verbs:беседовать{}, // преподаватель, беседующий со студентами rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками rus_verbs:поговорить{}, // поговорить с виновниками rus_verbs:сказать{}, // сказать с трудом rus_verbs:произнести{}, // произнести с трудом rus_verbs:говорить{}, // говорить с акцентом rus_verbs:произносить{}, // произносить с трудом rus_verbs:встречаться{}, // кто с Антонио встречался? rus_verbs:посидеть{}, // посидеть с друзьями rus_verbs:расквитаться{}, // расквитаться с обидчиком rus_verbs:поквитаться{}, // поквитаться с обидчиком rus_verbs:ругаться{}, // ругаться с женой rus_verbs:поскандалить{}, // поскандалить с женой rus_verbs:потанцевать{}, // потанцевать с подругой rus_verbs:скандалить{}, // скандалить с соседями rus_verbs:разругаться{}, // разругаться с другом rus_verbs:болтать{}, // болтать с подругами rus_verbs:потрепаться{}, // потрепаться с соседкой rus_verbs:войти{}, // войти с регистрацией rus_verbs:входить{}, // входить с регистрацией rus_verbs:возвращаться{}, // возвращаться с триумфом rus_verbs:опоздать{}, // Он опоздал с подачей сочинения. rus_verbs:молчать{}, // Он молчал с ледяным спокойствием. rus_verbs:сражаться{}, // Он героически сражался с врагами. rus_verbs:выходить{}, // Он всегда выходит с зонтиком. rus_verbs:сличать{}, // сличать перевод с оригиналом rus_verbs:начать{}, // я начал с товарищем спор о религии rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки rus_verbs:приходить{}, // Приходите с нею. rus_verbs:жить{}, // кто с тобой жил? rus_verbs:расходиться{}, // Маша расходится с Петей rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой rus_verbs:торговать{}, // мы торгуем с ними нефтью rus_verbs:уединяться{}, // уединяться с подругой в доме rus_verbs:уладить{}, // уладить конфликт с соседями rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем. rus_verbs:разделять{}, // Я разделяю с вами горе и радость. rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи. rus_verbs:захватить{}, // Я не захватил с собой денег. прилагательное:знакомый{}, // Я знаком с ними обоими. rus_verbs:вести{}, // Я веду с ней переписку. прилагательное:сопряженный{}, // Это сопряжено с большими трудностями. прилагательное:связанный{причастие}, // Это дело связано с риском. rus_verbs:поехать{}, // Хотите поехать со мной в театр? rus_verbs:проснуться{}, // Утром я проснулся с ясной головой. rus_verbs:лететь{}, // Самолёт летел со скоростью звука. rus_verbs:играть{}, // С огнём играть опасно! rus_verbs:поделать{}, // С ним ничего не поделаешь. rus_verbs:стрястись{}, // С ней стряслось несчастье. rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием. rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием. rus_verbs:разойтись{}, // Она разошлась с мужем. rus_verbs:пристать{}, // Она пристала ко мне с расспросами. rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением. rus_verbs:поступить{}, // Она плохо поступила с ним. rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом. rus_verbs:взять{}, // Возьмите с собой только самое необходимое. rus_verbs:наплакаться{}, // Наплачется она с ним. rus_verbs:лежать{}, // Он лежит с воспалением лёгких. rus_verbs:дышать{}, // дышащий с трудом rus_verbs:брать{}, // брать с собой rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой. rus_verbs:упасть{}, // Ваза упала со звоном. rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком rus_verbs:сидеть{}, // Она сидит дома с ребенком rus_verbs:встретиться{}, // встречаться с кем-либо ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{}, rus_verbs:мыть{} } fact гл_предл { if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} } then return true } #endregion ТВОРИТЕЛЬНЫЙ #region РОДИТЕЛЬНЫЙ wordentry_set Гл_С_Род= { rus_verbs:УХОДИТЬ{}, // Но с базы не уходить. rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ) rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ) rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ) rus_verbs:РАЗГЛЯДЕТЬ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ) rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ) rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ) rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ) rus_verbs:ЗАРЕВЕТЬ{}, // rus_verbs:ПРОРЕВЕТЬ{}, // rus_verbs:ЗАОРАТЬ{}, // rus_verbs:ПРООРАТЬ{}, // rus_verbs:ОРАТЬ{}, // rus_verbs:ЗАКРИЧАТЬ{}, rus_verbs:ВОПИТЬ{}, // rus_verbs:ЗАВОПИТЬ{}, // rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ) rus_verbs:СТАСКИВАТЬ{}, // rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ) rus_verbs:ЗАВЫТЬ{}, // rus_verbs:ВЫТЬ{}, // rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ) rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:собирать{}, // мальчики начали собирать со столов посуду rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ) rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ) rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ) rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ) rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ) rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род) rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род) rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С) rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С) rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род) rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С) rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С) rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С) rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С) rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род) rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род) rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род) rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род) rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род) rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С) rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род) rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род) rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род) rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род) rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род) rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род) rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С) rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род) rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род) rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род) rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С) rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С) rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С) прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С) rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С) rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род) rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С) rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с) rus_verbs:спасть{}, // тяжесть спала с души. (спасть с) rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С) rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С) rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С) rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то) rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С) rus_verbs:приближаться{}, // со стороны острова приближалась лодка. rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С) rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с) rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с) rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С) rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С) rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С) rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С) rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С) rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С) rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.) rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С) rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С) rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С) rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С) rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с) rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С) rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с) rus_verbs:вставать{}, // Он не встает с кровати. (вставать с) rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с) rus_verbs:причитаться{}, // С вас причитается 50 рублей. rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки. rus_verbs:сократить{}, // Его сократили со службы. rus_verbs:поднять{}, // рука подняла с пола rus_verbs:поднимать{}, rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни. rus_verbs:полететь{}, // Мальчик полетел с лестницы. rus_verbs:литься{}, // вода льется с неба rus_verbs:натечь{}, // натечь с сапог rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая rus_verbs:съезжать{}, // съезжать с заявленной темы rus_verbs:покатываться{}, // покатываться со смеху rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:сдирать{}, // сдирать с тела кожу rus_verbs:соскальзывать{}, // соскальзывать с крючка rus_verbs:сметать{}, // сметать с прилавков rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки rus_verbs:прокаркать{}, // прокаркать с ветки rus_verbs:стряхивать{}, // стряхивать с одежды rus_verbs:сваливаться{}, // сваливаться с лестницы rus_verbs:слизнуть{}, // слизнуть с лица rus_verbs:доставляться{}, // доставляться с фермы rus_verbs:обступать{}, // обступать с двух сторон rus_verbs:повскакивать{}, // повскакивать с мест rus_verbs:обозревать{}, // обозревать с вершины rus_verbs:слинять{}, // слинять с урока rus_verbs:смывать{}, // смывать с лица rus_verbs:спихнуть{}, // спихнуть со стола rus_verbs:обозреть{}, // обозреть с вершины rus_verbs:накупить{}, // накупить с рук rus_verbs:схлынуть{}, // схлынуть с берега rus_verbs:спикировать{}, // спикировать с километровой высоты rus_verbs:уползти{}, // уползти с поля боя rus_verbs:сбиваться{}, // сбиваться с пути rus_verbs:отлучиться{}, // отлучиться с поста rus_verbs:сигануть{}, // сигануть с крыши rus_verbs:сместить{}, // сместить с поста rus_verbs:списать{}, // списать с оригинального устройства инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы деепричастие:слетая{}, rus_verbs:напиваться{}, // напиваться с горя rus_verbs:свесить{}, // свесить с крыши rus_verbs:заполучить{}, // заполучить со склада rus_verbs:спадать{}, // спадать с глаз rus_verbs:стартовать{}, // стартовать с мыса rus_verbs:спереть{}, // спереть со склада rus_verbs:согнать{}, // согнать с живота rus_verbs:скатываться{}, // скатываться со стога rus_verbs:сняться{}, // сняться с выборов rus_verbs:слезать{}, // слезать со стола rus_verbs:деваться{}, // деваться с подводной лодки rus_verbs:огласить{}, // огласить с трибуны rus_verbs:красть{}, // красть со склада rus_verbs:расширить{}, // расширить с торца rus_verbs:угадывать{}, // угадывать с полуслова rus_verbs:оскорбить{}, // оскорбить со сцены rus_verbs:срывать{}, // срывать с головы rus_verbs:сшибить{}, // сшибить с коня rus_verbs:сбивать{}, // сбивать с одежды rus_verbs:содрать{}, // содрать с посетителей rus_verbs:столкнуть{}, // столкнуть с горы rus_verbs:отряхнуть{}, // отряхнуть с одежды rus_verbs:сбрасывать{}, // сбрасывать с борта rus_verbs:расстреливать{}, // расстреливать с борта вертолета rus_verbs:придти{}, // мать скоро придет с работы rus_verbs:съехать{}, // Миша съехал с горки rus_verbs:свисать{}, // свисать с веток rus_verbs:стянуть{}, // стянуть с кровати rus_verbs:скинуть{}, // скинуть снег с плеча rus_verbs:загреметь{}, // загреметь со стула rus_verbs:сыпаться{}, // сыпаться с неба rus_verbs:стряхнуть{}, // стряхнуть с головы rus_verbs:сползти{}, // сползти со стула rus_verbs:стереть{}, // стереть с экрана rus_verbs:прогнать{}, // прогнать с фермы rus_verbs:смахнуть{}, // смахнуть со стола rus_verbs:спускать{}, // спускать с поводка rus_verbs:деться{}, // деться с подводной лодки rus_verbs:сдернуть{}, // сдернуть с себя rus_verbs:сдвинуться{}, // сдвинуться с места rus_verbs:слететь{}, // слететь с катушек rus_verbs:обступить{}, // обступить со всех сторон rus_verbs:снести{}, // снести с плеч инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков деепричастие:сбегая{}, прилагательное:сбегающий{}, // прилагательное:сбегавший{ вид:несоверш }, rus_verbs:запить{}, // запить с горя rus_verbs:рубануть{}, // рубануть с плеча rus_verbs:чертыхнуться{}, // чертыхнуться с досады rus_verbs:срываться{}, // срываться с цепи rus_verbs:смыться{}, // смыться с уроков rus_verbs:похитить{}, // похитить со склада rus_verbs:смести{}, // смести со своего пути rus_verbs:отгружать{}, // отгружать со склада rus_verbs:отгрузить{}, // отгрузить со склада rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя rus_verbs:взиматься{}, // Плата взимается с любого посетителя rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков rus_verbs:вспархивать{}, // вспархивать с цветка rus_verbs:вспорхнуть{}, // вспорхнуть с ветки rus_verbs:выбросить{}, // выбросить что-то с балкона rus_verbs:выводить{}, // выводить с одежды пятна rus_verbs:снять{}, // снять с головы rus_verbs:начинать{}, // начинать с эскиза rus_verbs:двинуться{}, // двинуться с места rus_verbs:начинаться{}, // начинаться с гардероба rus_verbs:стечь{}, // стечь с крыши rus_verbs:слезть{}, // слезть с кучи rus_verbs:спуститься{}, // спуститься с крыши rus_verbs:сойти{}, // сойти с пьедестала rus_verbs:свернуть{}, // свернуть с пути rus_verbs:сорвать{}, // сорвать с цепи rus_verbs:сорваться{}, // сорваться с поводка rus_verbs:тронуться{}, // тронуться с места rus_verbs:угадать{}, // угадать с первой попытки rus_verbs:спустить{}, // спустить с лестницы rus_verbs:соскочить{}, // соскочить с крючка rus_verbs:сдвинуть{}, // сдвинуть с места rus_verbs:подниматься{}, // туман, поднимающийся с болота rus_verbs:подняться{}, // туман, поднявшийся с болота rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног. rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног. rus_verbs:донестись{}, // С улицы донесся шум дождя. rus_verbs:опасть{}, // Опавшие с дерева листья. rus_verbs:махнуть{}, // Он махнул с берега в воду. rus_verbs:исчезнуть{}, // исчезнуть с экрана rus_verbs:свалиться{}, // свалиться со сцены rus_verbs:упасть{}, // упасть с дерева rus_verbs:вернуться{}, // Он ещё не вернулся с работы. rus_verbs:сдувать{}, // сдувать пух с одуванчиков rus_verbs:свергать{}, // свергать царя с трона rus_verbs:сбиться{}, // сбиться с пути rus_verbs:стирать{}, // стирать тряпкой надпись с доски rus_verbs:убирать{}, // убирать мусор c пола rus_verbs:удалять{}, // удалять игрока с поля rus_verbs:окружить{}, // Япония окружена со всех сторон морями. rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение. глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы. прилагательное:спокойный{}, // С этой стороны я спокоен. rus_verbs:спросить{}, // С тебя за всё спросят. rus_verbs:течь{}, // С него течёт пот. rus_verbs:дуть{}, // С моря дует ветер. rus_verbs:капать{}, // С его лица капали крупные капли пота. rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол. rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня. rus_verbs:встать{}, // Все встали со стульев. rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто. rus_verbs:взять{}, // Возьми книгу с полки. rus_verbs:спускаться{}, // Мы спускались с горы. rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы. rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок. rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы. rus_verbs:двигаться{}, // Он не двигался с места. rus_verbs:отходить{}, // мой поезд отходит с первого пути rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции rus_verbs:падать{}, // снег падает с ветвей rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия. } fact гл_предл { if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:род} } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:парт} } then return true } #endregion РОДИТЕЛЬНЫЙ fact гл_предл { if context { * предлог:с{} *:*{ падеж:твор } } then return false,-3 } fact гл_предл { if context { * предлог:с{} *:*{ падеж:род } } then return false,-4 } fact гл_предл { if context { * предлог:с{} * } then return false,-5 } #endregion Предлог_С /* #region Предлог_ПОД // -------------- ПРЕДЛОГ 'ПОД' ----------------------- fact гл_предл { if context { * предлог:под{} @regex("[a-z]+[0-9]*") } then return true } // ПОД+вин.п. не может присоединяться к существительным, поэтому // он присоединяется к любым глаголам. fact гл_предл { if context { * предлог:под{} *:*{ падеж:вин } } then return true } wordentry_set Гл_ПОД_твор= { rus_verbs:извиваться{}, // извивалась под его длинными усами rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ) rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ) rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ) rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ) rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ) rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ) rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть) rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ) rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ) rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ) rus_verbs:ПРОПОЛЗТИ{}, // rus_verbs:ПРОПОЛЗАТЬ{}, // rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ) rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ) rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ) rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ) rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ) rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом rus_verbs:иметься{}, // у каждого под рукой имелся арбалет rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ) rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ) rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ) rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ) rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ) rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ) rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ) rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ) rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ) rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ) rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ) rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ) rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ) rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор) rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ) rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ) rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ) rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ) rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ) rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ) rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ) rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ) rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ) rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ) rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ) rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ) rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ) rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ) rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ) rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ) rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ) rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ) rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ) rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ) rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ) rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД) rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ) rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД) rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ) rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ) rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ) rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ) rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ) rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ) rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ) rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ) rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ) rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ) rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ) rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ) rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ) rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ) rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ) rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ) rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ) rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ) rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ) rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ) rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ) rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ) rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ) rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ) rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ) rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ) rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ) rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ) rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ) rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ) rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД) rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД) rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД) rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД) rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД) rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД) rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД) rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД) rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор) rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД) rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД) rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД) rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД) rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД) rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД) rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД) rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД) rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД) rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД) rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД) rus_verbs:уснуть{}, // Миша уснет под одеялом rus_verbs:пошевелиться{}, // пошевелиться под одеялом rus_verbs:задохнуться{}, // задохнуться под слоем снега rus_verbs:потечь{}, // потечь под избыточным давлением rus_verbs:уцелеть{}, // уцелеть под завалами rus_verbs:мерцать{}, // мерцать под лучами софитов rus_verbs:поискать{}, // поискать под кроватью rus_verbs:гудеть{}, // гудеть под нагрузкой rus_verbs:посидеть{}, // посидеть под навесом rus_verbs:укрыться{}, // укрыться под навесом rus_verbs:утихнуть{}, // утихнуть под одеялом rus_verbs:заскрипеть{}, // заскрипеть под тяжестью rus_verbs:шелохнуться{}, // шелохнуться под одеялом инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш }, инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш }, деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш }, rus_verbs:пониматься{}, // пониматься под успехом rus_verbs:подразумеваться{}, // подразумеваться под правильным решением rus_verbs:промокнуть{}, // промокнуть под проливным дождем rus_verbs:засосать{}, // засосать под ложечкой rus_verbs:подписаться{}, // подписаться под воззванием rus_verbs:укрываться{}, // укрываться под навесом rus_verbs:запыхтеть{}, // запыхтеть под одеялом rus_verbs:мокнуть{}, // мокнуть под лождем rus_verbs:сгибаться{}, // сгибаться под тяжестью снега rus_verbs:намокнуть{}, // намокнуть под дождем rus_verbs:подписываться{}, // подписываться под обращением rus_verbs:тарахтеть{}, // тарахтеть под окнами инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача. деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{}, rus_verbs:лежать{}, // лежать под капельницей rus_verbs:вымокать{}, // вымокать под дождём rus_verbs:вымокнуть{}, // вымокнуть под дождём rus_verbs:проворчать{}, // проворчать под нос rus_verbs:хмыкнуть{}, // хмыкнуть под нос rus_verbs:отыскать{}, // отыскать под кроватью rus_verbs:дрогнуть{}, // дрогнуть под ударами rus_verbs:проявляться{}, // проявляться под нагрузкой rus_verbs:сдержать{}, // сдержать под контролем rus_verbs:ложиться{}, // ложиться под клиента rus_verbs:таять{}, // таять под весенним солнцем rus_verbs:покатиться{}, // покатиться под откос rus_verbs:лечь{}, // он лег под навесом rus_verbs:идти{}, // идти под дождем прилагательное:известный{}, // Он известен под этим именем. rus_verbs:стоять{}, // Ящик стоит под столом. rus_verbs:отступить{}, // Враг отступил под ударами наших войск. rus_verbs:царапаться{}, // Мышь царапается под полом. rus_verbs:спать{}, // заяц спокойно спал у себя под кустом rus_verbs:загорать{}, // мы загораем под солнцем ГЛ_ИНФ(мыть), // мыть руки под струёй воды ГЛ_ИНФ(закопать), ГЛ_ИНФ(спрятать), ГЛ_ИНФ(прятать), ГЛ_ИНФ(перепрятать) } fact гл_предл { if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } } then return true } // для глаголов вне списка - запрещаем. fact гл_предл { if context { * предлог:под{} *:*{ падеж:твор } } then return false,-10 } fact гл_предл { if context { * предлог:под{} *:*{} } then return false,-11 } #endregion Предлог_ПОД */ #region Предлог_ОБ // -------------- ПРЕДЛОГ 'ОБ' ----------------------- wordentry_set Гл_ОБ_предл= { rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ) rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ) rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ) rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом? rus_verbs:забывать{}, // Мы не можем забывать об их участи. rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ) rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ) rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ) rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ) rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ) rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ) rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ) rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ) rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ) rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ) rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об) rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об) rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ) rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ) rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ) rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе. rus_verbs:кричать{}, // Все газеты кричат об этом событии. rus_verbs:советоваться{}, // Она обо всём советуется с матерью. rus_verbs:говориться{}, // об остальном говорилось легко. rus_verbs:подумать{}, // нужно крепко обо всем подумать. rus_verbs:напомнить{}, // черный дым напомнил об опасности. rus_verbs:забыть{}, // забудь об этой роскоши. rus_verbs:думать{}, // приходится обо всем думать самой. rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:информировать{}, // информировать об изменениях rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:заговорить{}, // заговорить об оплате rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:попросить{}, // попросить об услуге rus_verbs:объявить{}, // объявить об отставке rus_verbs:предупредить{}, // предупредить об аварии rus_verbs:предупреждать{}, // предупреждать об опасности rus_verbs:твердить{}, // твердить об обязанностях rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:прочитать{}, // он читал об этом в учебнике rus_verbs:узнать{}, // он узнал об этом из фильмов rus_verbs:рассказать{}, // рассказать об экзаменах rus_verbs:рассказывать{}, rus_verbs:договориться{}, // договориться об оплате rus_verbs:договариваться{}, // договариваться об обмене rus_verbs:болтать{}, // Не болтай об этом! rus_verbs:проболтаться{}, // Не проболтайся об этом! rus_verbs:заботиться{}, // кто заботится об урегулировании rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне rus_verbs:помнить{}, // всем советую об этом помнить rus_verbs:мечтать{} // Мечтать об успехе } fact гл_предл { if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } } then return true } fact гл_предл { if context { * предлог:о{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { * предлог:об{} @regex("[a-z]+[0-9]*") } then return true } // остальные глаголы не могут связываться fact гл_предл { if context { * предлог:об{} *:*{ падеж:предл } } then return false, -4 } wordentry_set Гл_ОБ_вин= { rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ) rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ) rus_verbs:опереться{}, // Он опёрся об стену. rus_verbs:опираться{}, rus_verbs:постучать{}, // постучал лбом об пол. rus_verbs:удариться{}, // бутылка глухо ударилась об землю. rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:царапаться{} // Днище лодки царапалось обо что-то. } fact гл_предл { if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:об{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:об{} *:*{} } then return false,-5 } #endregion Предлог_ОБ #region Предлог_О // ------------------- С ПРЕДЛОГОМ 'О' ---------------------- wordentry_set Гл_О_Вин={ rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену. rus_verbs:болтать{}, // Болтали чаще всего о пустяках. rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг. rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол. rus_verbs:бахнуться{}, // Бахнуться головой о стол. rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ) rus_verbs:ВЫТИРАТЬ{}, // rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ) rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ) rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ) rus_verbs:ЛЯЗГАТЬ{}, // rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ) rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ) rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ) rus_verbs:колотиться{}, // сердце его колотилось о ребра rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей. rus_verbs:биться{}, // биться головой о стену? (биться о) rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о) rus_verbs:разбиваться{}, // волны разбивались о скалу rus_verbs:разбивать{}, // Разбивает голову о прутья клетки. rus_verbs:облокотиться{}, // облокотиться о стену rus_verbs:точить{}, // точить о точильный камень rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень rus_verbs:потереться{}, // потереться о дерево rus_verbs:ушибиться{}, // ушибиться о дерево rus_verbs:тереться{}, // тереться о ствол rus_verbs:шмякнуться{}, // шмякнуться о землю rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:тереть{}, // тереть о камень rus_verbs:потереть{}, // потереть о колено rus_verbs:удариться{}, // удариться о край rus_verbs:споткнуться{}, // споткнуться о камень rus_verbs:запнуться{}, // запнуться о камень rus_verbs:запинаться{}, // запинаться о камни rus_verbs:ударяться{}, // ударяться о бортик rus_verbs:стукнуться{}, // стукнуться о бортик rus_verbs:стукаться{}, // стукаться о бортик rus_verbs:опереться{}, // Он опёрся локтями о стол. rus_verbs:плескаться{} // Вода плещется о берег. } fact гл_предл { if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:о{} *:*{ падеж:вин } } then return false,-5 } wordentry_set Гл_О_предл={ rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ) rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ) rus_verbs:РАССПРАШИВАТЬ{}, // rus_verbs:слушать{}, // ты будешь слушать о них? rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ) rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ) rus_verbs:сложить{}, // о вас сложены легенды rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О) rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О) rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О) rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О) rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О) rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О) rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О) rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О) rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О) rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О) rus_verbs:осведомиться{}, // офицер осведомился о цели визита rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о) rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О) rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о) rus_verbs:зайти{}, // Разговор зашёл о политике. rus_verbs:порассказать{}, // порассказать о своих путешествиях инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви деепричастие:спев{}, прилагательное:спевший{ вид:соверш }, прилагательное:спетый{}, rus_verbs:напеть{}, rus_verbs:разговаривать{}, // разговаривать с другом о жизни rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях //rus_verbs:заботиться{}, // заботиться о престарелых родителях rus_verbs:раздумывать{}, // раздумывать о новой работе rus_verbs:договариваться{}, // договариваться о сумме компенсации rus_verbs:молить{}, // молить о пощаде rus_verbs:отзываться{}, // отзываться о книге rus_verbs:подумывать{}, // подумывать о новом подходе rus_verbs:поговаривать{}, // поговаривать о загадочном звере rus_verbs:обмолвиться{}, // обмолвиться о проклятии rus_verbs:условиться{}, // условиться о поддержке rus_verbs:призадуматься{}, // призадуматься о последствиях rus_verbs:известить{}, // известить о поступлении rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:напевать{}, // напевать о любви rus_verbs:помышлять{}, // помышлять о новом деле rus_verbs:переговорить{}, // переговорить о правилах rus_verbs:повествовать{}, // повествовать о событиях rus_verbs:слыхивать{}, // слыхивать о чудище rus_verbs:потолковать{}, // потолковать о планах rus_verbs:проговориться{}, // проговориться о планах rus_verbs:умолчать{}, // умолчать о штрафах rus_verbs:хлопотать{}, // хлопотать о премии rus_verbs:уведомить{}, // уведомить о поступлении rus_verbs:горевать{}, // горевать о потере rus_verbs:запамятовать{}, // запамятовать о важном мероприятии rus_verbs:заикнуться{}, // заикнуться о прибавке rus_verbs:информировать{}, // информировать о событиях rus_verbs:проболтаться{}, // проболтаться о кладе rus_verbs:поразмыслить{}, // поразмыслить о судьбе rus_verbs:заикаться{}, // заикаться о деньгах rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:печься{}, // печься о всеобщем благе rus_verbs:разглагольствовать{}, // разглагольствовать о правах rus_verbs:размечтаться{}, // размечтаться о будущем rus_verbs:лепетать{}, // лепетать о невиновности rus_verbs:грезить{}, // грезить о большой и чистой любви rus_verbs:залепетать{}, // залепетать о сокровищах rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде rus_verbs:протрубить{}, // протрубить о победе rus_verbs:извещать{}, // извещать о поступлении rus_verbs:трубить{}, // трубить о поимке разбойников rus_verbs:осведомляться{}, // осведомляться о судьбе rus_verbs:поразмышлять{}, // поразмышлять о неизбежном rus_verbs:слагать{}, // слагать о подвигах викингов rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании rus_verbs:закидывать{}, // закидывать сообщениями об ошибках rus_verbs:базарить{}, // пацаны базарили о телках rus_verbs:балагурить{}, // мужики балагурили о новом председателе rus_verbs:балакать{}, // мужики балакали о новом председателе rus_verbs:беспокоиться{}, // Она беспокоится о детях rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве rus_verbs:возмечтать{}, // возмечтать о счастливом мире rus_verbs:вопить{}, // Кто-то вопил о несправедливости rus_verbs:сказать{}, // сказать что-то новое о ком-то rus_verbs:знать{}, // знать о ком-то что-то пикантное rus_verbs:подумать{}, // подумать о чём-то rus_verbs:думать{}, // думать о чём-то rus_verbs:узнать{}, // узнать о происшествии rus_verbs:помнить{}, // помнить о задании rus_verbs:просить{}, // просить о коде доступа rus_verbs:забыть{}, // забыть о своих обязанностях rus_verbs:сообщить{}, // сообщить о заложенной мине rus_verbs:заявить{}, // заявить о пропаже rus_verbs:задуматься{}, // задуматься о смерти rus_verbs:спрашивать{}, // спрашивать о поступлении товара rus_verbs:догадаться{}, // догадаться о причинах rus_verbs:договориться{}, // договориться о собеседовании rus_verbs:мечтать{}, // мечтать о сцене rus_verbs:поговорить{}, // поговорить о наболевшем rus_verbs:размышлять{}, // размышлять о насущном rus_verbs:напоминать{}, // напоминать о себе rus_verbs:пожалеть{}, // пожалеть о содеянном rus_verbs:ныть{}, // ныть о прибавке rus_verbs:сообщать{}, // сообщать о победе rus_verbs:догадываться{}, // догадываться о первопричине rus_verbs:поведать{}, // поведать о тайнах rus_verbs:умолять{}, // умолять о пощаде rus_verbs:сожалеть{}, // сожалеть о случившемся rus_verbs:жалеть{}, // жалеть о случившемся rus_verbs:забывать{}, // забывать о случившемся rus_verbs:упоминать{}, // упоминать о предках rus_verbs:позабыть{}, // позабыть о своем обещании rus_verbs:запеть{}, // запеть о любви rus_verbs:скорбеть{}, // скорбеть о усопшем rus_verbs:задумываться{}, // задумываться о смене работы rus_verbs:позаботиться{}, // позаботиться о престарелых родителях rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината rus_verbs:попросить{}, // попросить о замене rus_verbs:предупредить{}, // предупредить о замене rus_verbs:предупреждать{}, // предупреждать о замене rus_verbs:твердить{}, // твердить о замене rus_verbs:заявлять{}, // заявлять о подлоге rus_verbs:петь{}, // певица, поющая о лете rus_verbs:проинформировать{}, // проинформировать о переговорах rus_verbs:порассказывать{}, // порассказывать о событиях rus_verbs:послушать{}, // послушать о новинках rus_verbs:заговорить{}, // заговорить о плате rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой. rus_verbs:оставить{}, // Он оставил о себе печальную память. rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях rus_verbs:спорить{}, // они спорили о законе глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия. глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия. rus_verbs:прочитать{}, // Я прочитал о тебе rus_verbs:услышать{}, // Я услышал о нем rus_verbs:помечтать{}, // Девочки помечтали о принце rus_verbs:слышать{}, // Мальчик слышал о приведениях rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке rus_verbs:грустить{}, // Я грущу о тебе rus_verbs:осведомить{}, // о последних достижениях науки rus_verbs:рассказывать{}, // Антонио рассказывает о работе rus_verbs:говорить{}, // говорим о трех больших псах rus_verbs:идти{} // Вопрос идёт о войне. } fact гл_предл { if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } } then return true } // Мы поделились впечатлениями о выставке. // ^^^^^^^^^^ ^^^^^^^^^^ fact гл_предл { if context { * предлог:о{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:о{} *:*{} } then return false,-5 } #endregion Предлог_О #region Предлог_ПО // ------------------- С ПРЕДЛОГОМ 'ПО' ---------------------- // для этих глаголов - запрещаем связывание с ПО+дат.п. wordentry_set Глаг_ПО_Дат_Запр= { rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:закончить{}, rus_verbs:мочь{}, rus_verbs:хотеть{} } fact гл_предл { if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } } then return false,-10 } // По умолчанию разрешаем связывание в паттернах типа // Я иду по шоссе fact гл_предл { if context { * предлог:по{} *:*{ падеж:дат } } then return true } wordentry_set Глаг_ПО_Вин= { rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ) rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО) rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера rus_verbs:засадить{}, // засадить по рукоятку rus_verbs:увязнуть{} // увязнуть по колено } fact гл_предл { if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:по{} *:*{ падеж:вин } } then return false,-5 } #endregion Предлог_ПО #region Предлог_К // ------------------- С ПРЕДЛОГОМ 'К' ---------------------- wordentry_set Гл_К_Дат={ rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна. rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску. прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ) rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ) rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ) rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ) rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ) rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ) rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ) rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ) rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ) rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, // rus_verbs:ПРИНОРОВИТЬСЯ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ) rus_verbs:СПИКИРОВАТЬ{}, // rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С) rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ) rus_verbs:ПРОТЯНУТЬ{}, // rus_verbs:ТЯНУТЬ{}, // rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ) rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,, rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, // rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, // rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ) rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке. rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ) rus_verbs:хотеть{}, rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ) rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ) rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ) rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ) rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ) rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ) rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ) rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ) rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ) rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ) rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ) rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К) rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К) rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К) rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К) rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К) прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К) безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К) rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К) rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К) rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К) rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К) rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К) rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К) rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К) rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К) rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К) rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К) rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К) rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К) rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К) rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К) rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К) rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К) rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К) rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К) rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К) rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К) rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К) rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К) rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К) глагол:быть{}, // к тебе есть вопросы. прилагательное:равнодушный{}, // Он равнодушен к музыке. rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К) rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К) инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К) rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К) rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к) rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К) rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К) rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К) rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К) rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К) rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К) rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К) rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к) rus_verbs:просить{}, // Директор просит вас к себе. (просить к) rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к) rus_verbs:присесть{}, // старик присел к огню. (присесть к) rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К) rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к) rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к) rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К) rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К) rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К) rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К) rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к) rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К) rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К) rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К) rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К) rus_verbs:подходить{}, // цвет подходил ей к лицу. rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К) rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К) rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К) rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К) rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К) rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К) rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к) rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К) rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К) rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к) rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к) rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К) rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К) rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К) rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К) rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к) rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к) rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к) rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К) rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к) rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к) rus_verbs:требовать{}, // вас требует к себе император. (требовать к) rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к) rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к) rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К) rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К) rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к) rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К) rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К) rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к) rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к) rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к) rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К) rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к) rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к) rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к) rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К) rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К) rus_verbs:выехать{}, // почти сразу мы выехали к реке. rus_verbs:пододвигаться{}, // пододвигайся к окну rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам. rus_verbs:представить{}, // Его представили к ордену. rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу. rus_verbs:выскочить{}, // тем временем они выскочили к реке. rus_verbs:выйти{}, // тем временем они вышли к лестнице. rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе. rus_verbs:приложить{}, // приложить к детали повышенное усилие rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку) rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю rus_verbs:прыгать{}, // прыгать к хозяину на стол rus_verbs:приглашать{}, // приглашать к доктору rus_verbs:рваться{}, // Чужие люди рвутся к власти rus_verbs:понестись{}, // понестись к обрыву rus_verbs:питать{}, // питать привязанность к алкоголю rus_verbs:заехать{}, // Коля заехал к Оле rus_verbs:переехать{}, // переехать к родителям rus_verbs:ползти{}, // ползти к дороге rus_verbs:сводиться{}, // сводиться к элементарному действию rus_verbs:добавлять{}, // добавлять к общей сумме rus_verbs:подбросить{}, // подбросить к потолку rus_verbs:призывать{}, // призывать к спокойствию rus_verbs:пробираться{}, // пробираться к партизанам rus_verbs:отвезти{}, // отвезти к родителям rus_verbs:применяться{}, // применяться к уравнению rus_verbs:сходиться{}, // сходиться к точному решению rus_verbs:допускать{}, // допускать к сдаче зачета rus_verbs:свести{}, // свести к нулю rus_verbs:придвинуть{}, // придвинуть к мальчику rus_verbs:подготовить{}, // подготовить к печати rus_verbs:подобраться{}, // подобраться к оленю rus_verbs:заторопиться{}, // заторопиться к выходу rus_verbs:пристать{}, // пристать к берегу rus_verbs:поманить{}, // поманить к себе rus_verbs:припасть{}, // припасть к алтарю rus_verbs:притащить{}, // притащить к себе домой rus_verbs:прижимать{}, // прижимать к груди rus_verbs:подсесть{}, // подсесть к симпатичной девочке rus_verbs:придвинуться{}, // придвинуться к окну rus_verbs:отпускать{}, // отпускать к другу rus_verbs:пригнуться{}, // пригнуться к земле rus_verbs:пристроиться{}, // пристроиться к колонне rus_verbs:сгрести{}, // сгрести к себе rus_verbs:удрать{}, // удрать к цыганам rus_verbs:прибавиться{}, // прибавиться к общей сумме rus_verbs:присмотреться{}, // присмотреться к покупке rus_verbs:подкатить{}, // подкатить к трюму rus_verbs:клонить{}, // клонить ко сну rus_verbs:проследовать{}, // проследовать к выходу rus_verbs:пододвинуть{}, // пододвинуть к себе rus_verbs:применять{}, // применять к сотрудникам rus_verbs:прильнуть{}, // прильнуть к экранам rus_verbs:подвинуть{}, // подвинуть к себе rus_verbs:примчаться{}, // примчаться к папе rus_verbs:подкрасться{}, // подкрасться к жертве rus_verbs:привязаться{}, // привязаться к собаке rus_verbs:забирать{}, // забирать к себе rus_verbs:прорваться{}, // прорваться к кассе rus_verbs:прикасаться{}, // прикасаться к коже rus_verbs:уносить{}, // уносить к себе rus_verbs:подтянуться{}, // подтянуться к месту rus_verbs:привозить{}, // привозить к ветеринару rus_verbs:подползти{}, // подползти к зайцу rus_verbs:приблизить{}, // приблизить к глазам rus_verbs:применить{}, // применить к уравнению простое преобразование rus_verbs:приглядеться{}, // приглядеться к изображению rus_verbs:приложиться{}, // приложиться к ручке rus_verbs:приставать{}, // приставать к девчонкам rus_verbs:запрещаться{}, // запрещаться к показу rus_verbs:прибегать{}, // прибегать к насилию rus_verbs:побудить{}, // побудить к действиям rus_verbs:притягивать{}, // притягивать к себе rus_verbs:пристроить{}, // пристроить к полезному делу rus_verbs:приговорить{}, // приговорить к смерти rus_verbs:склоняться{}, // склоняться к прекращению разработки rus_verbs:подъезжать{}, // подъезжать к вокзалу rus_verbs:привалиться{}, // привалиться к забору rus_verbs:наклоняться{}, // наклоняться к щенку rus_verbs:подоспеть{}, // подоспеть к обеду rus_verbs:прилипнуть{}, // прилипнуть к окну rus_verbs:приволочь{}, // приволочь к себе rus_verbs:устремляться{}, // устремляться к вершине rus_verbs:откатиться{}, // откатиться к исходным позициям rus_verbs:побуждать{}, // побуждать к действиям rus_verbs:прискакать{}, // прискакать к кормежке rus_verbs:присматриваться{}, // присматриваться к новичку rus_verbs:прижиматься{}, // прижиматься к борту rus_verbs:жаться{}, // жаться к огню rus_verbs:передвинуть{}, // передвинуть к окну rus_verbs:допускаться{}, // допускаться к экзаменам rus_verbs:прикрепить{}, // прикрепить к корпусу rus_verbs:отправлять{}, // отправлять к специалистам rus_verbs:перебежать{}, // перебежать к врагам rus_verbs:притронуться{}, // притронуться к реликвии rus_verbs:заспешить{}, // заспешить к семье rus_verbs:ревновать{}, // ревновать к сопернице rus_verbs:подступить{}, // подступить к горлу rus_verbs:уводить{}, // уводить к ветеринару rus_verbs:побросать{}, // побросать к ногам rus_verbs:подаваться{}, // подаваться к ужину rus_verbs:приписывать{}, // приписывать к достижениям rus_verbs:относить{}, // относить к растениям rus_verbs:принюхаться{}, // принюхаться к ароматам rus_verbs:подтащить{}, // подтащить к себе rus_verbs:прислонить{}, // прислонить к стене rus_verbs:подплыть{}, // подплыть к бую rus_verbs:опаздывать{}, // опаздывать к стилисту rus_verbs:примкнуть{}, // примкнуть к деомнстрантам rus_verbs:стекаться{}, // стекаются к стенам тюрьмы rus_verbs:подготовиться{}, // подготовиться к марафону rus_verbs:приглядываться{}, // приглядываться к новичку rus_verbs:присоединяться{}, // присоединяться к сообществу rus_verbs:клониться{}, // клониться ко сну rus_verbs:привыкать{}, // привыкать к хорошему rus_verbs:принудить{}, // принудить к миру rus_verbs:уплыть{}, // уплыть к далекому берегу rus_verbs:утащить{}, // утащить к детенышам rus_verbs:приплыть{}, // приплыть к финишу rus_verbs:подбегать{}, // подбегать к хозяину rus_verbs:лишаться{}, // лишаться средств к существованию rus_verbs:приступать{}, // приступать к операции rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике rus_verbs:подключить{}, // подключить к трубе rus_verbs:подключиться{}, // подключиться к сети rus_verbs:прилить{}, // прилить к лицу rus_verbs:стучаться{}, // стучаться к соседям rus_verbs:пристегнуть{}, // пристегнуть к креслу rus_verbs:присоединить{}, // присоединить к сети rus_verbs:отбежать{}, // отбежать к противоположной стене rus_verbs:подвезти{}, // подвезти к набережной rus_verbs:прибегнуть{}, // прибегнуть к хитрости rus_verbs:приучить{}, // приучить к туалету rus_verbs:подталкивать{}, // подталкивать к выходу rus_verbs:прорываться{}, // прорываться к выходу rus_verbs:увозить{}, // увозить к ветеринару rus_verbs:засеменить{}, // засеменить к выходу rus_verbs:крепиться{}, // крепиться к потолку rus_verbs:прибрать{}, // прибрать к рукам rus_verbs:пристраститься{}, // пристраститься к наркотикам rus_verbs:поспеть{}, // поспеть к обеду rus_verbs:привязывать{}, // привязывать к дереву rus_verbs:прилагать{}, // прилагать к документам rus_verbs:переправить{}, // переправить к дедушке rus_verbs:подогнать{}, // подогнать к воротам rus_verbs:тяготеть{}, // тяготеть к социализму rus_verbs:подбираться{}, // подбираться к оленю rus_verbs:подступать{}, // подступать к горлу rus_verbs:примыкать{}, // примыкать к первому элементу rus_verbs:приладить{}, // приладить к велосипеду rus_verbs:подбрасывать{}, // подбрасывать к потолку rus_verbs:перевозить{}, // перевозить к новому месту дислокации rus_verbs:усаживаться{}, // усаживаться к окну rus_verbs:приближать{}, // приближать к глазам rus_verbs:попроситься{}, // попроситься к бабушке rus_verbs:прибить{}, // прибить к доске rus_verbs:перетащить{}, // перетащить к себе rus_verbs:прицепить{}, // прицепить к паровозу rus_verbs:прикладывать{}, // прикладывать к ране rus_verbs:устареть{}, // устареть к началу войны rus_verbs:причалить{}, // причалить к пристани rus_verbs:приспособиться{}, // приспособиться к опозданиям rus_verbs:принуждать{}, // принуждать к миру rus_verbs:соваться{}, // соваться к директору rus_verbs:протолкаться{}, // протолкаться к прилавку rus_verbs:приковать{}, // приковать к батарее rus_verbs:подкрадываться{}, // подкрадываться к суслику rus_verbs:подсадить{}, // подсадить к арестонту rus_verbs:прикатить{}, // прикатить к финишу rus_verbs:протащить{}, // протащить к владыке rus_verbs:сужаться{}, // сужаться к основанию rus_verbs:присовокупить{}, // присовокупить к пожеланиям rus_verbs:пригвоздить{}, // пригвоздить к доске rus_verbs:отсылать{}, // отсылать к первоисточнику rus_verbs:изготовиться{}, // изготовиться к прыжку rus_verbs:прилагаться{}, // прилагаться к покупке rus_verbs:прицепиться{}, // прицепиться к вагону rus_verbs:примешиваться{}, // примешиваться к вину rus_verbs:переселить{}, // переселить к старшекурсникам rus_verbs:затрусить{}, // затрусить к выходе rus_verbs:приспособить{}, // приспособить к обогреву rus_verbs:примериться{}, // примериться к аппарату rus_verbs:прибавляться{}, // прибавляться к пенсии rus_verbs:подкатиться{}, // подкатиться к воротам rus_verbs:стягивать{}, // стягивать к границе rus_verbs:дописать{}, // дописать к роману rus_verbs:подпустить{}, // подпустить к корове rus_verbs:склонять{}, // склонять к сотрудничеству rus_verbs:припечатать{}, // припечатать к стене rus_verbs:охладеть{}, // охладеть к музыке rus_verbs:пришить{}, // пришить к шинели rus_verbs:принюхиваться{}, // принюхиваться к ветру rus_verbs:подрулить{}, // подрулить к барышне rus_verbs:наведаться{}, // наведаться к оракулу rus_verbs:клеиться{}, // клеиться к конверту rus_verbs:перетянуть{}, // перетянуть к себе rus_verbs:переметнуться{}, // переметнуться к конкурентам rus_verbs:липнуть{}, // липнуть к сокурсницам rus_verbs:поковырять{}, // поковырять к выходу rus_verbs:подпускать{}, // подпускать к пульту управления rus_verbs:присосаться{}, // присосаться к источнику rus_verbs:приклеить{}, // приклеить к стеклу rus_verbs:подтягивать{}, // подтягивать к себе rus_verbs:подкатывать{}, // подкатывать к даме rus_verbs:притрагиваться{}, // притрагиваться к опухоли rus_verbs:слетаться{}, // слетаться к водопою rus_verbs:хаживать{}, // хаживать к батюшке rus_verbs:привлекаться{}, // привлекаться к административной ответственности rus_verbs:подзывать{}, // подзывать к себе rus_verbs:прикладываться{}, // прикладываться к иконе rus_verbs:подтягиваться{}, // подтягиваться к парламенту rus_verbs:прилепить{}, // прилепить к стенке холодильника rus_verbs:пододвинуться{}, // пододвинуться к экрану rus_verbs:приползти{}, // приползти к дереву rus_verbs:запаздывать{}, // запаздывать к обеду rus_verbs:припереть{}, // припереть к стене rus_verbs:нагибаться{}, // нагибаться к цветку инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам деепричастие:сгоняв{}, rus_verbs:поковылять{}, // поковылять к выходу rus_verbs:привалить{}, // привалить к столбу rus_verbs:отпроситься{}, // отпроситься к родителям rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям rus_verbs:прилипать{}, // прилипать к рукам rus_verbs:подсоединить{}, // подсоединить к приборам rus_verbs:приливать{}, // приливать к голове rus_verbs:подселить{}, // подселить к другим новичкам rus_verbs:прилепиться{}, // прилепиться к шкуре rus_verbs:подлетать{}, // подлетать к пункту назначения rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг rus_verbs:льнуть{}, // льнуть к заботливому хозяину rus_verbs:привязываться{}, // привязываться к любящему хозяину rus_verbs:приклеиться{}, // приклеиться к спине rus_verbs:стягиваться{}, // стягиваться к сенату rus_verbs:подготавливать{}, // подготавливать к выходу на арену rus_verbs:приглашаться{}, // приглашаться к доктору rus_verbs:причислять{}, // причислять к отличникам rus_verbs:приколоть{}, // приколоть к лацкану rus_verbs:наклонять{}, // наклонять к горизонту rus_verbs:припадать{}, // припадать к первоисточнику rus_verbs:приобщиться{}, // приобщиться к культурному наследию rus_verbs:придираться{}, // придираться к мелким ошибкам rus_verbs:приучать{}, // приучать к лотку rus_verbs:промотать{}, // промотать к началу rus_verbs:прихлынуть{}, // прихлынуть к голове rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу rus_verbs:прикрутить{}, // прикрутить к велосипеду rus_verbs:подплывать{}, // подплывать к лодке rus_verbs:приравниваться{}, // приравниваться к побегу rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы rus_verbs:приткнуться{}, // приткнуться к первой группе туристов rus_verbs:приручить{}, // приручить котика к лотку rus_verbs:приковывать{}, // приковывать к себе все внимание прессы rus_verbs:приготовляться{}, // приготовляться к первому экзамену rus_verbs:остыть{}, // Вода остынет к утру. rus_verbs:приехать{}, // Он приедет к концу будущей недели. rus_verbs:подсаживаться{}, rus_verbs:успевать{}, // успевать к стилисту rus_verbs:привлекать{}, // привлекать к себе внимание прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму rus_verbs:прийтись{}, // прийтись ко двору инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы инфинитив:адаптироваться{вид:несоверш}, глагол:адаптироваться{вид:соверш}, глагол:адаптироваться{вид:несоверш}, деепричастие:адаптировавшись{}, деепричастие:адаптируясь{}, прилагательное:адаптировавшийся{вид:соверш}, //+прилагательное:адаптировавшийся{вид:несоверш}, прилагательное:адаптирующийся{}, rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей rus_verbs:близиться{}, // Шторм близится к побережью rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки rus_verbs:причислить{}, // Мы причислили его к числу экспертов rus_verbs:вести{}, // Наша партия ведет народ к процветанию rus_verbs:взывать{}, // Учителя взывают к совести хулигана rus_verbs:воззвать{}, // воззвать соплеменников к оружию rus_verbs:возревновать{}, // возревновать к поклонникам rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью rus_verbs:восходить{}, // восходить к вершине rus_verbs:восшествовать{}, // восшествовать к вершине rus_verbs:успеть{}, // успеть к обеду rus_verbs:повернуться{}, // повернуться к кому-то rus_verbs:обратиться{}, // обратиться к охраннику rus_verbs:звать{}, // звать к столу rus_verbs:отправиться{}, // отправиться к парикмахеру rus_verbs:обернуться{}, // обернуться к зовущему rus_verbs:явиться{}, // явиться к следователю rus_verbs:уехать{}, // уехать к родне rus_verbs:прибыть{}, // прибыть к перекличке rus_verbs:привыкнуть{}, // привыкнуть к голоду rus_verbs:уходить{}, // уходить к цыганам rus_verbs:привести{}, // привести к себе rus_verbs:шагнуть{}, // шагнуть к славе rus_verbs:относиться{}, // относиться к прежним периодам rus_verbs:подослать{}, // подослать к врагам rus_verbs:поспешить{}, // поспешить к обеду rus_verbs:зайти{}, // зайти к подруге rus_verbs:позвать{}, // позвать к себе rus_verbs:потянуться{}, // потянуться к рычагам rus_verbs:пускать{}, // пускать к себе rus_verbs:отвести{}, // отвести к врачу rus_verbs:приблизиться{}, // приблизиться к решению задачи rus_verbs:прижать{}, // прижать к стене rus_verbs:отправить{}, // отправить к доктору rus_verbs:падать{}, // падать к многолетним минимумам rus_verbs:полезть{}, // полезть к дерущимся rus_verbs:лезть{}, // Ты сама ко мне лезла! rus_verbs:направить{}, // направить к майору rus_verbs:приводить{}, // приводить к дантисту rus_verbs:кинуться{}, // кинуться к двери rus_verbs:поднести{}, // поднести к глазам rus_verbs:подниматься{}, // подниматься к себе rus_verbs:прибавить{}, // прибавить к результату rus_verbs:зашагать{}, // зашагать к выходу rus_verbs:склониться{}, // склониться к земле rus_verbs:стремиться{}, // стремиться к вершине rus_verbs:лететь{}, // лететь к родственникам rus_verbs:ездить{}, // ездить к любовнице rus_verbs:приближаться{}, // приближаться к финише rus_verbs:помчаться{}, // помчаться к стоматологу rus_verbs:прислушаться{}, // прислушаться к происходящему rus_verbs:изменить{}, // изменить к лучшему собственную жизнь rus_verbs:проявить{}, // проявить к погибшим сострадание rus_verbs:подбежать{}, // подбежать к упавшему rus_verbs:терять{}, // терять к партнерам доверие rus_verbs:пропустить{}, // пропустить к певцу rus_verbs:подвести{}, // подвести к глазам rus_verbs:меняться{}, // меняться к лучшему rus_verbs:заходить{}, // заходить к другу rus_verbs:рвануться{}, // рвануться к воде rus_verbs:привлечь{}, // привлечь к себе внимание rus_verbs:присоединиться{}, // присоединиться к сети rus_verbs:приезжать{}, // приезжать к дедушке rus_verbs:дернуться{}, // дернуться к борту rus_verbs:подъехать{}, // подъехать к воротам rus_verbs:готовиться{}, // готовиться к дождю rus_verbs:убежать{}, // убежать к маме rus_verbs:поднимать{}, // поднимать к источнику сигнала rus_verbs:отослать{}, // отослать к руководителю rus_verbs:приготовиться{}, // приготовиться к худшему rus_verbs:приступить{}, // приступить к выполнению обязанностей rus_verbs:метнуться{}, // метнуться к фонтану rus_verbs:прислушиваться{}, // прислушиваться к голосу разума rus_verbs:побрести{}, // побрести к выходу rus_verbs:мчаться{}, // мчаться к успеху rus_verbs:нестись{}, // нестись к обрыву rus_verbs:попадать{}, // попадать к хорошему костоправу rus_verbs:опоздать{}, // опоздать к психотерапевту rus_verbs:посылать{}, // посылать к доктору rus_verbs:поплыть{}, // поплыть к берегу rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе rus_verbs:отнести{}, // отнести животное к ветеринару rus_verbs:прислониться{}, // прислониться к стволу rus_verbs:наклонить{}, // наклонить к миске с молоком rus_verbs:прикоснуться{}, // прикоснуться к поверхности rus_verbs:увезти{}, // увезти к бабушке rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия rus_verbs:подозвать{}, // подозвать к себе rus_verbs:улететь{}, // улететь к теплым берегам rus_verbs:ложиться{}, // ложиться к мужу rus_verbs:убираться{}, // убираться к чертовой бабушке rus_verbs:класть{}, // класть к другим документам rus_verbs:доставлять{}, // доставлять к подъезду rus_verbs:поворачиваться{}, // поворачиваться к источнику шума rus_verbs:заглядывать{}, // заглядывать к любовнице rus_verbs:занести{}, // занести к заказчикам rus_verbs:прибежать{}, // прибежать к папе rus_verbs:притянуть{}, // притянуть к причалу rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:подать{}, // он подал лимузин к подъезду rus_verbs:подавать{}, // она подавала соус к мясу rus_verbs:приобщаться{}, // приобщаться к культуре прилагательное:неспособный{}, // Наша дочка неспособна к учению. прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару прилагательное:предназначенный{}, // Старый дом предназначен к сносу. прилагательное:внимательный{}, // Она всегда внимательна к гостям. прилагательное:назначенный{}, // Дело назначено к докладу. прилагательное:разрешенный{}, // Эта книга разрешена к печати. прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам. прилагательное:готовый{}, // Я готов к экзаменам. прилагательное:требовательный{}, // Он очень требователен к себе. прилагательное:жадный{}, // Он жаден к деньгам. прилагательное:глухой{}, // Он глух к моей просьбе. прилагательное:добрый{}, // Он добр к детям. rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам. rus_verbs:плыть{}, // Пароход плыл к берегу. rus_verbs:пойти{}, // я пошел к доктору rus_verbs:придти{}, // придти к выводу rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом. rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений. rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам. rus_verbs:спускаться{}, // Улица круто спускается к реке. rus_verbs:спуститься{}, // Мы спустились к реке. rus_verbs:пустить{}, // пускать ко дну rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью! rus_verbs:отойти{}, // Дом отошёл к племяннику. rus_verbs:отходить{}, // Коля отходил ко сну. rus_verbs:приходить{}, // местные жители к нему приходили лечиться rus_verbs:кидаться{}, // не кидайся к столу rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу. rus_verbs:закончиться{}, // Собрание закончилось к вечеру. rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему. rus_verbs:направиться{}, // Мы сошли на берег и направились к городу. rus_verbs:направляться{}, rus_verbs:свестись{}, // Всё свелось к нулю. rus_verbs:прислать{}, // Пришлите кого-нибудь к ней. rus_verbs:присылать{}, // Он присылал к должнику своих головорезов rus_verbs:подлететь{}, // Самолёт подлетел к лесу. rus_verbs:возвращаться{}, // он возвращается к старой работе глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая. rus_verbs:возвращать{}, // возвращать к жизни rus_verbs:располагать{}, // Атмосфера располагает к работе. rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому. rus_verbs:поступить{}, // К нам поступила жалоба. rus_verbs:поступать{}, // К нам поступают жалобы. rus_verbs:прыгнуть{}, // Белка прыгнула к дереву rus_verbs:торопиться{}, // пассажиры торопятся к выходу rus_verbs:поторопиться{}, // поторопитесь к выходу rus_verbs:вернуть{}, // вернуть к активной жизни rus_verbs:припирать{}, // припирать к стенке rus_verbs:проваливать{}, // Проваливай ко всем чертям! rus_verbs:вбежать{}, // Коля вбежал ко мне rus_verbs:вбегать{}, // Коля вбегал ко мне глагол:забегать{ вид:несоверш }, // Коля забегал ко мне rus_verbs:постучаться{}, // Коля постучался ко мне. rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому rus_verbs:понести{}, // Мы понесли кота к ветеринару rus_verbs:принести{}, // Я принес кота к ветеринару rus_verbs:устремиться{}, // Мы устремились к ручью. rus_verbs:подводить{}, // Учитель подводил детей к аквариуму rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения. rus_verbs:пригласить{}, // Я пригласил к себе товарищей. rus_verbs:собираться{}, // Я собираюсь к тебе в гости. rus_verbs:собраться{}, // Маша собралась к дантисту rus_verbs:сходить{}, // Я схожу к врачу. rus_verbs:идти{}, // Маша уверенно шла к Пете rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию. rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию. rus_verbs:заканчивать{}, // Заканчивайте к обеду rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:окончить{}, // rus_verbs:дозвониться{}, // Я не мог к вам дозвониться. глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор rus_verbs:уйти{}, // Антонио ушел к Элеонор rus_verbs:бежать{}, // Антонио бежит к Элеонор rus_verbs:спешить{}, // Антонио спешит к Элеонор rus_verbs:скакать{}, // Антонио скачет к Элеонор rus_verbs:красться{}, // Антонио крадётся к Элеонор rus_verbs:поскакать{}, // беглецы поскакали к холмам rus_verbs:перейти{} // Антонио перешел к Элеонор } fact гл_предл { if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } } then return true } fact гл_предл { if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:к{} *:*{} } then return false,-5 } #endregion Предлог_К #region Предлог_ДЛЯ // ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ---------------------- wordentry_set Гл_ДЛЯ_Род={ частица:нет{}, // для меня нет других путей. частица:нету{}, rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ) rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ) rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться) rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ) rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ) rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ) rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ) rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ) rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ) rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ) rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ) rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ) rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ) rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ) rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ) rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ) rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ) rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ) rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ) rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ) rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ) rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ) rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ) rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ) rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ) rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ) rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ) rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ) прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ) rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ) rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ) rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ) rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ) rus_verbs:оставить{}, // или вообще решили оставить планету для себя rus_verbs:оставлять{}, rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ) rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ) rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ) rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ) rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ) rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ) rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ) rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ) rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для) rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ) rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ) rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ) rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ) rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ) прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ) прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ) прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ) rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ) rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ) rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ) rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ) rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ) rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ) rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ) rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ) rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ) rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ) rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ) rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ) прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ) rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ) rus_verbs:вывести{}, // мы специально вывели этих животных для мяса. rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для) rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ) rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ) rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ) rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ) rus_verbs:найтись{}, // у вас найдется для него работа? rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для) rus_verbs:заехать{}, // Коля заехал для обсуждения проекта rus_verbs:созреть{}, // созреть для побега rus_verbs:наметить{}, // наметить для проверки rus_verbs:уяснить{}, // уяснить для себя rus_verbs:нанимать{}, // нанимать для разовой работы rus_verbs:приспособить{}, // приспособить для удовольствия rus_verbs:облюбовать{}, // облюбовать для посиделок rus_verbs:прояснить{}, // прояснить для себя rus_verbs:задействовать{}, // задействовать для патрулирования rus_verbs:приготовлять{}, // приготовлять для проверки инфинитив:использовать{ вид:соверш }, // использовать для достижения цели инфинитив:использовать{ вид:несоверш }, глагол:использовать{ вид:соверш }, глагол:использовать{ вид:несоверш }, прилагательное:использованный{}, деепричастие:используя{}, деепричастие:использовав{}, rus_verbs:напрячься{}, // напрячься для решительного рывка rus_verbs:одобрить{}, // одобрить для использования rus_verbs:одобрять{}, // одобрять для использования rus_verbs:пригодиться{}, // пригодиться для тестирования rus_verbs:готовить{}, // готовить для выхода в свет rus_verbs:отобрать{}, // отобрать для участия в конкурсе rus_verbs:потребоваться{}, // потребоваться для подтверждения rus_verbs:пояснить{}, // пояснить для слушателей rus_verbs:пояснять{}, // пояснить для экзаменаторов rus_verbs:понадобиться{}, // понадобиться для обоснования инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, rus_verbs:найти{}, // Папа нашел для детей няню прилагательное:вредный{}, // Это вредно для здоровья. прилагательное:полезный{}, // Прогулки полезны для здоровья. прилагательное:обязательный{}, // Этот пункт обязателен для исполнения прилагательное:бесполезный{}, // Это лекарство бесполезно для него прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления rus_verbs:создать{}, // Он не создан для этого дела. прилагательное:сложный{}, // задача сложна для младших школьников прилагательное:несложный{}, прилагательное:лёгкий{}, прилагательное:сложноватый{}, rus_verbs:становиться{}, rus_verbs:представлять{}, // Это не представляет для меня интереса. rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка rus_verbs:пройти{}, // День прошёл спокойно для него. rus_verbs:проходить{}, rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ rus_verbs:высаживаться{}, rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца. rus_verbs:прибавить{}, rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов. rus_verbs:составлять{}, rus_verbs:стараться{}, // Я старался для вас rus_verbs:постараться{}, // Я постарался для вас rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста. rus_verbs:собраться{}, // собраться для обсуждения rus_verbs:собираться{}, // собираться для обсуждения rus_verbs:уполномочивать{}, rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров rus_verbs:принести{}, // Я принёс эту книгу для вас. rus_verbs:делать{}, // Я это делаю для удовольствия. rus_verbs:сделать{}, // Я сделаю это для удовольствия. rus_verbs:подготовить{}, // я подготовил для друзей сюрприз rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села rus_verbs:прибыть{} // они прибыли для участия } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } } then return true } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:для{} *:*{} } then return false,-4 } #endregion Предлог_ДЛЯ #region Предлог_ОТ // попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_ОТ_Род_Запр= { rus_verbs:наслаждаться{}, // свободой от обязательств rus_verbs:насладиться{}, rus_verbs:мочь{}, // Он не мог удержаться от смеха. // rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:чувствовать{}, // все время от времени чувствуют его. rus_verbs:планировать{}, rus_verbs:приняться{} // мы принялись обниматься от радости. } fact гл_предл { if context { Глаг_ОТ_Род_Запр предлог:от{} * } then return false } #endregion Предлог_ОТ #region Предлог_БЕЗ /* // запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_БЕЗ_Род_Запр= { rus_verbs:мочь{}, // Он мог читать часами без отдыха. rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:планировать{}, rus_verbs:приняться{} } fact гл_предл { if context { Глаг_БЕЗ_Род_Запр предлог:без{} * } then return false } */ #endregion Предлог_БЕЗ #region Предлог_КРОМЕ fact гл_предл { if context { * ПредлогДляВсе * } then return false,-5 } #endregion Предлог_КРОМЕ // ------------------------------------ // По умолчанию разрешаем все остальные сочетания. fact гл_предл { if context { * * * } then return true }
Охранник вгляделся в темный коридор
rus_verbs:вглядеться{},
5,483,447
[ 1, 145, 257, 146, 232, 146, 227, 145, 113, 145, 126, 145, 126, 145, 121, 145, 123, 225, 145, 115, 145, 116, 145, 124, 146, 242, 145, 117, 145, 118, 145, 124, 146, 228, 146, 242, 225, 145, 115, 225, 146, 229, 145, 118, 145, 125, 145, 126, 146, 238, 145, 122, 225, 145, 123, 145, 127, 146, 227, 145, 121, 145, 117, 145, 127, 146, 227, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 436, 407, 67, 502, 2038, 30, 145, 115, 145, 116, 145, 124, 146, 242, 145, 117, 145, 118, 146, 229, 146, 239, 146, 228, 146, 242, 2916, 16, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-07-19 */ /// // GasBack Technology // https://gasback.tech/ // // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Implementation of the {IBEP20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {BEP20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of BEP20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IBEP20-approve}. */ pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity >=0.6.4; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract BEP20 is Context, IBEP20, Ownable { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the name of the token. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom (address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'BEP20: transfer amount exceeds allowance') ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero')); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer (address sender, address recipient, uint256 amount) internal { require(sender != address(0), 'BEP20: transfer from the zero address'); require(recipient != address(0), 'BEP20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), 'BEP20: mint to the zero address'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve (address owner, address spender, uint256 amount) internal { require(owner != address(0), 'BEP20: approve from the zero address'); require(spender != address(0), 'BEP20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance')); } } // GasFuel contract GasBackFuel is BEP20('GasFuel', 'GASF') { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title SafeBEP20 * @dev Wrappers around BEP20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeBEP20 for IBEP20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer(IBEP20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IBEP20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IBEP20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IBEP20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeBEP20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IBEP20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IBEP20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeBEP20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IBEP20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeBEP20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeBEP20: BEP20 operation did not succeed"); } } } // MasterChef is the Owner of GasBackFuel and has super powers. // He keeps track of rewards and the most recent TX Gas Price. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once governance is sufficiently // distributed and the community can be shown to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Most recent GasPrice, used for tracking on Web dApp uint256 public latestGasPrice = 0; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of Gas // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accGasPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accGasPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Gas to distribute per block. uint256 lastRewardBlock; // Last block number that Gas distribution occurs. uint256 accGasPerShare; // Accumulated Gas per share, times 1e12. See below. uint16 depositFeeBP; // Deposit fee in basis points } // The GasBackFuel Token GasBackFuel public gasback; // Dev address. address public devaddr; // Gas tokens created per block. uint256 public gasbackPerBlock; // Bonus muliplier for early gasback makers. uint256 public constant BONUS_MULTIPLIER = 1; // Treasury address address public treasuryAddress; // Ensure we can't add same pool twice mapping (address => bool) private poolIsAdded; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( GasBackFuel _gasback, address _devaddr, address _treasuryAddress, uint256 _gasbackPerBlock, uint256 _startBlock ) public { gasback = _gasback; devaddr = _devaddr; treasuryAddress = _treasuryAddress; gasbackPerBlock = _gasbackPerBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } // EDIT: Don't add same pool twice, fixed in code with check require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added'); poolIsAdded[address(_lpToken)] = true; uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accGasPerShare: 0, depositFeeBP: _depositFeeBP })); } // Update the given pool's Gas allocation point and deposit fee. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending Gass on frontend. function pendingGas(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accGasPerShare = pool.accGasPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gasbackReward = multiplier.mul(gasbackPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accGasPerShare = accGasPerShare.add(gasbackReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accGasPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { // Added to set recent latestGasPrice latestGasPrice = tx.gasprice; PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gasbackReward = multiplier.mul(gasbackPerBlock).mul(pool.allocPoint).div(totalAllocPoint); gasback.mint(devaddr, gasbackReward.div(10)); gasback.mint(address(this), gasbackReward); pool.accGasPerShare = pool.accGasPerShare.add(gasbackReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Gas allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accGasPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeGasTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if(pool.depositFeeBP > 0){ uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(treasuryAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); }else{ user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accGasPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accGasPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeGasTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accGasPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Safe gasback transfer function, just in case if rounding error causes pool to not have enough Gas. function safeGasTransfer(address _to, uint256 _amount) internal { uint256 gasbackBal = gasback.balanceOf(address(this)); if (_amount > gasbackBal) { gasback.transfer(_to, gasbackBal); } else { gasback.transfer(_to, _amount); } } function dev(address _devaddr) public onlyOwner { devaddr = _devaddr; } function setTreasuryAddress(address _treasuryAddress) public onlyOwner { treasuryAddress = _treasuryAddress; } function updateEmissionRate(uint256 _gasbackPerBlock) public onlyOwner { massUpdatePools(); gasbackPerBlock = _gasbackPerBlock; } }
View function to see pending Gass on frontend.
function pendingGas(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accGasPerShare = pool.accGasPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gasbackReward = multiplier.mul(gasbackPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accGasPerShare = accGasPerShare.add(gasbackReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accGasPerShare).div(1e12).sub(user.rewardDebt); }
2,179,018
[ 1, 1767, 445, 358, 2621, 4634, 611, 428, 603, 15442, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4634, 27998, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 67, 1355, 15533, 203, 3639, 2254, 5034, 4078, 27998, 2173, 9535, 273, 2845, 18, 8981, 27998, 2173, 9535, 31, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 2629, 18, 2696, 405, 2845, 18, 2722, 17631, 1060, 1768, 597, 12423, 3088, 1283, 480, 374, 13, 288, 203, 5411, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 5411, 2254, 5034, 16189, 823, 17631, 1060, 273, 15027, 18, 16411, 12, 31604, 823, 2173, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 8763, 2148, 1769, 203, 5411, 4078, 27998, 2173, 9535, 273, 4078, 27998, 2173, 9535, 18, 1289, 12, 31604, 823, 17631, 1060, 18, 16411, 12, 21, 73, 2138, 2934, 2892, 12, 9953, 3088, 1283, 10019, 203, 3639, 289, 203, 3639, 327, 729, 18, 8949, 18, 16411, 12, 8981, 27998, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x8557Cc2Fc11ebA44FFE690c96e0fC594eF648D84/sources/contracts/mferRaincheck.sol
* @dev Extension of {ERC20} that allows token holders to destroy both their own tokens and those that they have an allowance for, in a way that can be recognized off-chain (via event analysis)./
abstract contract ERC20Burnable is Context, ERC20 { function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } }
4,722,684
[ 1, 3625, 434, 288, 654, 39, 3462, 97, 716, 5360, 1147, 366, 4665, 358, 5546, 3937, 3675, 4953, 2430, 471, 5348, 716, 2898, 1240, 392, 1699, 1359, 364, 16, 316, 279, 4031, 716, 848, 506, 16332, 3397, 17, 5639, 261, 21985, 871, 6285, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 3462, 38, 321, 429, 353, 1772, 16, 4232, 39, 3462, 288, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 203, 565, 445, 18305, 12, 11890, 5034, 3844, 13, 1071, 5024, 288, 203, 3639, 389, 70, 321, 24899, 3576, 12021, 9334, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 18305, 1265, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 1071, 5024, 288, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 1699, 1359, 12, 4631, 16, 389, 3576, 12021, 10663, 203, 3639, 2583, 12, 2972, 7009, 1359, 1545, 3844, 16, 315, 654, 39, 3462, 30, 18305, 3844, 14399, 1699, 1359, 8863, 203, 3639, 22893, 288, 203, 5411, 389, 12908, 537, 12, 4631, 16, 389, 3576, 12021, 9334, 783, 7009, 1359, 300, 3844, 1769, 203, 3639, 289, 203, 3639, 389, 70, 321, 12, 4631, 16, 3844, 1769, 203, 565, 289, 203, 565, 445, 18305, 1265, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 1071, 5024, 288, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 1699, 1359, 12, 4631, 16, 389, 3576, 12021, 10663, 203, 3639, 2583, 12, 2972, 7009, 1359, 1545, 3844, 16, 315, 654, 39, 3462, 30, 18305, 3844, 14399, 1699, 1359, 8863, 203, 3639, 22893, 288, 203, 5411, 389, 12908, 537, 12, 4631, 16, 389, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-03-12 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; library Address { function isContract(address account) internal view returns (bool) { uint size; assembly { size := extcodesize(account) } return size > 0; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } pragma solidity ^0.8.7; abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; // Mapping from token ID to owner address address[] internal _owners; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint) { require(owner != address(0), "ERC721: balance query for the zero address"); uint count; for( uint i; i < _owners.length; ++i ){ if( owner == _owners[i] ) ++count; } return count; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId < _owners.length && _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners.push(to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } pragma solidity ^0.8.7; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account but rips out the core of the gas-wasting processing that comes from OpenZeppelin. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _owners.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < _owners.length, "ERC721Enumerable: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); uint count; for(uint i; i < _owners.length; i++){ if(owner == _owners[i]){ if(count == index) return i; else count++; } } revert("ERC721Enumerable: owner index out of bounds"); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity ^0.8.7; /** * Hiya * This smart contract we have taken every measure possible to * keep the costs of gas managable every step along the way. * * In this contract we've used several different methods to keep costs down. * If you came here worried because gas is so low or you don't have to pay that pesky * OpenSea approval fee; rejoice! * Contract by: _granto * Based on the work of solidity geniuses: nftchance & masonnft & squeebo_nft ____ ! ! ! ! `- _ _ _ | ``` ! _____! ! \, Made in Texas \ l _ ; \ _/ \. / \ .’ . ./’ `. , \ ; ``’ */ contract CoolMisfit is ERC721Enumerable, Ownable { string public baseURI; address public proxyRegistryAddress; address public treasuryAccount; uint256 public MAX_SUPPLY = 500; uint256 public MAX_PER_TX = 1; uint256 public constant RESERVES = 25; uint256 public priceInWei = 0 ether; bool public publicSaleActive = false; mapping(address => bool) public projectProxy; mapping(address => uint256) public addressToMinted; // baseURI: metadata endpoint for this collection // treasuryAccount: address the funds should be widthdrawn to constructor(string memory _baseURI, address _treasuryAccount) ERC721("Cool Misfit", "CoolMisfit") { baseURI = _baseURI; treasuryAccount = _treasuryAccount; // Opensea proxy registry address: this preapproves Opensea for transactions, saving users gas fees proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; } function setBaseURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } function setMaxSupply(uint256 _maxSupply) public onlyOwner { MAX_SUPPLY = _maxSupply; } function setPriceInWei(uint256 _priceInWei) public onlyOwner { priceInWei = _priceInWei; } function setTxnMax(uint256 _txnMax) public onlyOwner { MAX_PER_TX = _txnMax; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "Token does not exist."); return string(abi.encodePacked(baseURI, Strings.toString(_tokenId))); } function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwner { proxyRegistryAddress = _proxyRegistryAddress; } function flipProxyState(address proxyAddress) public onlyOwner { projectProxy[proxyAddress] = !projectProxy[proxyAddress]; } function togglePublicSaleActive() external onlyOwner { publicSaleActive = !publicSaleActive; } function collectReserves() external onlyOwner { require(_owners.length == 0, "Reserves already taken."); for (uint256 i; i < RESERVES; i++) _mint(_msgSender(), i); } function mint(uint256 count) public payable { uint256 totalSupply = _owners.length; require(publicSaleActive, "Public sale is not active."); require(totalSupply + count < MAX_SUPPLY + 1, "Excedes max supply."); require(count < MAX_PER_TX + 1, "Exceeds max per transaction."); require(count * priceInWei == msg.value, "Invalid funds provided."); for (uint256 i; i < count; i++) { _mint(_msgSender(), totalSupply + i); } } function burn(uint256 tokenId) public { require( _isApprovedOrOwner(_msgSender(), tokenId), "Not approved to burn." ); _burn(tokenId); } function withdraw() public { (bool success, ) = treasuryAccount.call{value: address(this).balance}( "" ); require(success, "Failed to send to treasury."); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) return new uint256[](0); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function batchTransferFrom( address _from, address _to, uint256[] memory _tokenIds ) public { for (uint256 i = 0; i < _tokenIds.length; i++) { transferFrom(_from, _to, _tokenIds[i]); } } function batchSafeTransferFrom( address _from, address _to, uint256[] memory _tokenIds, bytes memory data_ ) public { for (uint256 i = 0; i < _tokenIds.length; i++) { safeTransferFrom(_from, _to, _tokenIds[i], data_); } } function isOwnerOf(address account, uint256[] calldata _tokenIds) external view returns (bool) { for (uint256 i; i < _tokenIds.length; ++i) { if (_owners[_tokenIds[i]] != account) return false; } return true; } function isApprovedForAll(address _owner, address operator) public view override returns (bool) { OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry( proxyRegistryAddress ); if ( address(proxyRegistry.proxies(_owner)) == operator || projectProxy[operator] ) return true; return super.isApprovedForAll(_owner, operator); } function _mint(address to, uint256 tokenId) internal virtual override { _owners.push(to); emit Transfer(address(0), to, tokenId); } } contract OwnableDelegateProxy {} contract OpenSeaProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; }
baseURI: metadata endpoint for this collection treasuryAccount: address the funds should be widthdrawn to
contract CoolMisfit is ERC721Enumerable, Ownable { string public baseURI; address public proxyRegistryAddress; address public treasuryAccount; uint256 public MAX_SUPPLY = 500; uint256 public MAX_PER_TX = 1; uint256 public constant RESERVES = 25; uint256 public priceInWei = 0 ether; bool public publicSaleActive = false; mapping(address => bool) public projectProxy; mapping(address => uint256) public addressToMinted; constructor(string memory _baseURI, address _treasuryAccount) ERC721("Cool Misfit", "CoolMisfit") { baseURI = _baseURI; treasuryAccount = _treasuryAccount; proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; } function setBaseURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } function setMaxSupply(uint256 _maxSupply) public onlyOwner { MAX_SUPPLY = _maxSupply; } function setPriceInWei(uint256 _priceInWei) public onlyOwner { priceInWei = _priceInWei; } function setTxnMax(uint256 _txnMax) public onlyOwner { MAX_PER_TX = _txnMax; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "Token does not exist."); return string(abi.encodePacked(baseURI, Strings.toString(_tokenId))); } function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwner { proxyRegistryAddress = _proxyRegistryAddress; } function flipProxyState(address proxyAddress) public onlyOwner { projectProxy[proxyAddress] = !projectProxy[proxyAddress]; } function togglePublicSaleActive() external onlyOwner { publicSaleActive = !publicSaleActive; } function collectReserves() external onlyOwner { require(_owners.length == 0, "Reserves already taken."); for (uint256 i; i < RESERVES; i++) _mint(_msgSender(), i); } function mint(uint256 count) public payable { uint256 totalSupply = _owners.length; require(publicSaleActive, "Public sale is not active."); require(totalSupply + count < MAX_SUPPLY + 1, "Excedes max supply."); require(count < MAX_PER_TX + 1, "Exceeds max per transaction."); require(count * priceInWei == msg.value, "Invalid funds provided."); for (uint256 i; i < count; i++) { _mint(_msgSender(), totalSupply + i); } } function mint(uint256 count) public payable { uint256 totalSupply = _owners.length; require(publicSaleActive, "Public sale is not active."); require(totalSupply + count < MAX_SUPPLY + 1, "Excedes max supply."); require(count < MAX_PER_TX + 1, "Exceeds max per transaction."); require(count * priceInWei == msg.value, "Invalid funds provided."); for (uint256 i; i < count; i++) { _mint(_msgSender(), totalSupply + i); } } function burn(uint256 tokenId) public { require( _isApprovedOrOwner(_msgSender(), tokenId), "Not approved to burn." ); _burn(tokenId); } function withdraw() public { "" ); require(success, "Failed to send to treasury."); } (bool success, ) = treasuryAccount.call{value: address(this).balance}( function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) return new uint256[](0); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) return new uint256[](0); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function batchTransferFrom( address _from, address _to, uint256[] memory _tokenIds ) public { for (uint256 i = 0; i < _tokenIds.length; i++) { transferFrom(_from, _to, _tokenIds[i]); } } function batchTransferFrom( address _from, address _to, uint256[] memory _tokenIds ) public { for (uint256 i = 0; i < _tokenIds.length; i++) { transferFrom(_from, _to, _tokenIds[i]); } } function batchSafeTransferFrom( address _from, address _to, uint256[] memory _tokenIds, bytes memory data_ ) public { for (uint256 i = 0; i < _tokenIds.length; i++) { safeTransferFrom(_from, _to, _tokenIds[i], data_); } } function batchSafeTransferFrom( address _from, address _to, uint256[] memory _tokenIds, bytes memory data_ ) public { for (uint256 i = 0; i < _tokenIds.length; i++) { safeTransferFrom(_from, _to, _tokenIds[i], data_); } } function isOwnerOf(address account, uint256[] calldata _tokenIds) external view returns (bool) { for (uint256 i; i < _tokenIds.length; ++i) { if (_owners[_tokenIds[i]] != account) return false; } return true; } function isOwnerOf(address account, uint256[] calldata _tokenIds) external view returns (bool) { for (uint256 i; i < _tokenIds.length; ++i) { if (_owners[_tokenIds[i]] != account) return false; } return true; } function isApprovedForAll(address _owner, address operator) public view override returns (bool) { OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry( proxyRegistryAddress ); if ( address(proxyRegistry.proxies(_owner)) == operator || projectProxy[operator] ) return true; return super.isApprovedForAll(_owner, operator); } function _mint(address to, uint256 tokenId) internal virtual override { _owners.push(to); emit Transfer(address(0), to, tokenId); } }
2,423,946
[ 1, 1969, 3098, 30, 1982, 2494, 364, 333, 1849, 9787, 345, 22498, 3032, 30, 1758, 326, 284, 19156, 1410, 506, 1835, 9446, 82, 358, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 385, 1371, 11729, 7216, 353, 4232, 39, 27, 5340, 3572, 25121, 16, 14223, 6914, 288, 203, 565, 533, 1071, 1026, 3098, 31, 203, 203, 565, 1758, 1071, 2889, 4243, 1887, 31, 203, 565, 1758, 1071, 9787, 345, 22498, 3032, 31, 203, 203, 565, 2254, 5034, 1071, 4552, 67, 13272, 23893, 273, 6604, 31, 203, 203, 565, 2254, 5034, 1071, 4552, 67, 3194, 67, 16556, 273, 404, 31, 203, 565, 2254, 5034, 1071, 5381, 2438, 2123, 3412, 55, 273, 6969, 31, 203, 565, 2254, 5034, 1071, 6205, 382, 3218, 77, 273, 374, 225, 2437, 31, 203, 565, 1426, 565, 1071, 1071, 30746, 3896, 273, 629, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 1984, 3886, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 1758, 774, 49, 474, 329, 31, 203, 203, 565, 3885, 12, 1080, 3778, 389, 1969, 3098, 16, 1758, 389, 27427, 345, 22498, 3032, 13, 203, 3639, 4232, 39, 27, 5340, 2932, 39, 1371, 16584, 7216, 3113, 315, 39, 1371, 11729, 7216, 7923, 203, 203, 7010, 203, 565, 288, 203, 3639, 1026, 3098, 273, 389, 1969, 3098, 31, 203, 3639, 9787, 345, 22498, 3032, 273, 389, 27427, 345, 22498, 3032, 31, 203, 3639, 2889, 4243, 1887, 273, 374, 6995, 6564, 5908, 557, 29, 8204, 39, 10261, 39, 23, 74, 5082, 29, 5292, 28, 70, 378, 2226, 37, 27, 71, 5292, 5528, 38, 20, 4700, 71, 21, 31, 203, 565, 289, 203, 203, 565, 445, 26435, 3098, 12, 1080, 3778, 389, 1969, 3098, 13, 1071, 1338, 5541, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./interfaces/IBorrowerOps.sol"; import "./interfaces/IVaultManager.sol"; import "./interfaces/IOSDToken.sol"; import "./interfaces/ICollSurplusPool.sol"; import "./interfaces/ISortedVaults.sol"; import "./Dependencies/OrumBase.sol"; import "./Dependencies/CheckContract.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract BorrowerOps is OrumBase, Ownable, CheckContract, IBorrowerOps { string constant public NAME = "BorrowerOps"; // --- Connected contract declarations --- IVaultManager public vaultManager; address stabilityPoolAddress; address gasPoolAddress; address orumFeeDistributionAddress; uint public lockupTime; ICollSurplusPool collSurplusPool; IOSDToken public osdToken; // A doubly linked list of Vaults, sorted by their collateral ratios ISortedVaults public sortedVaults; /* --- Variable container structs --- Used to hold, return and assign variables inside a function, in order to avoid the error: "CompilerError: Stack too deep". */ struct LocalVariables_adjustVault { uint price; uint collChange; uint netDebtChange; bool isCollIncrease; uint debt; uint coll; uint oldICR; uint newICR; uint newTCR; uint ROSEFee; uint newDebt; uint newColl; uint stake; } struct LocalVariables_openVault { uint price; uint ROSEFee; uint netColl; uint netDebt; uint compositeDebt; uint ICR; uint NICR; uint stake; uint arrayIndex; } struct ContractsCache { IVaultManager vaultManager; IActivePool activePool; IOSDToken osdToken; } enum BorrowerOperation { openVault, closeVault, adjustVault } // --- Dependency setters --- function setAddresses( address _vaultManagerAddress, address _activePoolAddress, address _defaultPoolAddress, address _stabilityPoolAddress, address _gasPoolAddress, address _collSurplusPoolAddress, address _priceFeedAddress, address _sortedVaultsAddress, address _osdTokenAddress, address _orumFeeDistributionAddress ) external onlyOwner { // This makes impossible to open a vault with zero withdrawn OSD assert(MIN_NET_DEBT > 0); checkContract(_vaultManagerAddress); checkContract(_activePoolAddress); checkContract(_defaultPoolAddress); checkContract(_stabilityPoolAddress); checkContract(_gasPoolAddress); checkContract(_collSurplusPoolAddress); checkContract(_priceFeedAddress); checkContract(_sortedVaultsAddress); checkContract(_osdTokenAddress); // checkContract(_orumFeeDistributionAddress); vaultManager = IVaultManager(_vaultManagerAddress); activePool = IActivePool(_activePoolAddress); defaultPool = IDefaultPool(_defaultPoolAddress); stabilityPoolAddress = _stabilityPoolAddress; gasPoolAddress = _gasPoolAddress; collSurplusPool = ICollSurplusPool(_collSurplusPoolAddress); priceFeed = IPriceFeed(_priceFeedAddress); sortedVaults = ISortedVaults(_sortedVaultsAddress); osdToken = IOSDToken(_osdTokenAddress); orumFeeDistributionAddress = _orumFeeDistributionAddress; emit VaultManagerAddressChanged(_vaultManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit DefaultPoolAddressChanged(_defaultPoolAddress); emit StabilityPoolAddressChanged(_stabilityPoolAddress); emit GasPoolAddressChanged(_gasPoolAddress); emit CollSurplusPoolAddressChanged(_collSurplusPoolAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit SortedVaultsAddressChanged(_sortedVaultsAddress); emit OSDTokenAddressChanged(_osdTokenAddress); emit OrumRevenueAddressChanged(_orumFeeDistributionAddress); } // --- Borrower Vault Ops --- function openVault(uint _maxFeePercentage, uint _OSDAmount, address _upperHint, address _lowerHint) external payable override { ContractsCache memory contractsCache = ContractsCache(vaultManager, activePool, osdToken); LocalVariables_openVault memory vars; vars.price = priceFeed.fetchPrice(); bool isRecoveryMode = _checkRecoveryMode(vars.price); _requireValidMaxFeePercentage(_maxFeePercentage, isRecoveryMode); _requireVaultisNotActive(contractsCache.vaultManager, msg.sender); vars.netDebt = _OSDAmount; vars.netColl = msg.value; if (!isRecoveryMode) { vars.ROSEFee = _triggerBorrowingFee(contractsCache.vaultManager, _OSDAmount, _maxFeePercentage, vars.price); // send the rose fee to the staking contract (bool success_staking,) = orumFeeDistributionAddress.call{value: vars.ROSEFee}(""); require(success_staking,"BorrowerOps: Borrow fee payment failed"); vars.netColl -= vars.ROSEFee; } _requireAtLeastMinNetDebt(vars.netDebt); // ICR is based on the composite debt, i.e. the requested OSD amount + OSD borrowing fee + OSD gas comp. vars.compositeDebt = _getCompositeDebt(vars.netDebt); assert(vars.compositeDebt > 0); vars.ICR = OrumMath._computeCR(vars.netColl, vars.compositeDebt, vars.price); vars.NICR = OrumMath._computeNominalCR(vars.netColl, vars.compositeDebt); if (isRecoveryMode) { _requireICRisAboveCCR(vars.ICR); } else { _requireICRisAboveMCR(vars.ICR); uint newTCR = _getNewTCRFromVaultChange(vars.netColl, true, vars.compositeDebt, true, vars.ROSEFee, vars.price); // bools: coll increase, debt increase _requireNewTCRisAboveCCR(newTCR); } // Set the vault struct's properties contractsCache.vaultManager.setVaultStatus(msg.sender, 1); contractsCache.vaultManager.increaseVaultColl(msg.sender, vars.netColl); contractsCache.vaultManager.increaseVaultDebt(msg.sender, vars.compositeDebt); contractsCache.vaultManager.updateVaultRewardSnapshots(msg.sender); vars.stake = contractsCache.vaultManager.updateStakeAndTotalStakes(msg.sender); sortedVaults.insert(msg.sender, vars.NICR, _upperHint, _lowerHint); vars.arrayIndex = contractsCache.vaultManager.addVaultOwnerToArray(msg.sender); emit VaultCreated(msg.sender, vars.arrayIndex); // Move the rose to the Active Pool, and mint the OSDAmount to the borrower _activePoolAddColl(contractsCache.activePool, vars.netColl); _withdrawOSD(contractsCache.activePool, contractsCache.osdToken, msg.sender, _OSDAmount, vars.netDebt); // Move the OSD gas compensation to the Gas Pool _withdrawOSD(contractsCache.activePool, contractsCache.osdToken, gasPoolAddress, OSD_GAS_COMPENSATION, OSD_GAS_COMPENSATION); emit VaultUpdated(msg.sender, vars.compositeDebt, vars.netColl, vars.stake, uint8(BorrowerOperation.openVault)); emit BorrowFeeInROSE(msg.sender, vars.ROSEFee); } // Send ROSE as collateral to a vault function addColl(address _upperHint, address _lowerHint) external payable override { _adjustVault(msg.sender, 0, 0, false, _upperHint, _lowerHint, 0); } // Send ROSE as collateral to a vault. Called by only the Stability Pool. function moveROSEGainToVault(address _borrower, address _upperHint, address _lowerHint) external payable override { _requireCallerIsStabilityPool(); _adjustVault(_borrower, 0, 0, false, _upperHint, _lowerHint, 0); } // Withdraw ROSE collateral from a vault function withdrawColl(uint _collWithdrawal, address _upperHint, address _lowerHint) external override { _adjustVault(msg.sender, _collWithdrawal, 0, false, _upperHint, _lowerHint, 0); } // Withdraw OSD tokens from a vault: mint new OSD tokens to the owner, and increase the vault's debt accordingly function withdrawOSD(uint _maxFeePercentage, uint _OSDAmount, address _upperHint, address _lowerHint) external override { _adjustVault(msg.sender, 0, _OSDAmount, true, _upperHint, _lowerHint, _maxFeePercentage); } // Repay OSD tokens to a Vault: Burn the repaid OSD tokens, and reduce the vault's debt accordingly function repayOSD(uint _OSDAmount, address _upperHint, address _lowerHint) external override { _adjustVault(msg.sender, 0, _OSDAmount, false, _upperHint, _lowerHint, 0); } /* * _adjustVault(): Alongside a debt change, this function can perform either a collateral top-up or a collateral withdrawal. * * It therefore expects either a positive msg.value, or a positive _collWithdrawal argument. * * If both are positive, it will revert. */ function _adjustVault(address _borrower, uint _collWithdrawal, uint _OSDChange, bool _isDebtIncrease, address _upperHint, address _lowerHint, uint _maxFeePercentage) internal { ContractsCache memory contractsCache = ContractsCache(vaultManager, activePool, osdToken); LocalVariables_adjustVault memory vars; vars.price = priceFeed.fetchPrice(); bool isRecoveryMode = _checkRecoveryMode(vars.price); if (_isDebtIncrease) { _requireValidMaxFeePercentage(_maxFeePercentage, isRecoveryMode); _requireNonZeroDebtChange(_OSDChange); } _requireSingularCollChange(_collWithdrawal); _requireNonZeroAdjustment(_collWithdrawal, _OSDChange); _requireVaultisActive(contractsCache.vaultManager, _borrower); // Confirm the operation is either a borrower adjusting their own vault, or a pure ROSE transfer from the Stability Pool to a vault assert(msg.sender == _borrower || (msg.sender == stabilityPoolAddress && msg.value > 0 && _OSDChange == 0)); contractsCache.vaultManager.applyPendingRewards(_borrower); // Get the collChange based on whether or not ROSE was sent in the transaction (vars.collChange, vars.isCollIncrease) = _getCollChange(msg.value, _collWithdrawal); vars.netDebtChange = _OSDChange; // If the adjustment incorporates a debt increase and system is in Normal Mode, then trigger a borrowing fee if (_isDebtIncrease && !isRecoveryMode) { vars.ROSEFee = _triggerBorrowingFee(contractsCache.vaultManager, _OSDChange, _maxFeePercentage, vars.price); } vars.debt = contractsCache.vaultManager.getVaultDebt(_borrower); vars.coll = contractsCache.vaultManager.getVaultColl(_borrower); // Get the vault's old ICR before the adjustment, and what its new ICR will be after the adjustment vars.oldICR = OrumMath._computeCR(vars.coll, vars.debt, vars.price); vars.newICR = _getNewICRFromVaultChange(vars.coll, vars.debt, vars.collChange, vars.isCollIncrease, vars.netDebtChange, _isDebtIncrease, vars.ROSEFee, vars.price); assert(_collWithdrawal <= vars.coll); // Check the adjustment satisfies all conditions for the current system mode _requireValidAdjustmentInCurrentMode(isRecoveryMode, _collWithdrawal, _isDebtIncrease, vars); // When the adjustment is a debt repayment, check it's a valid amount and that the caller has enough OSD if (!_isDebtIncrease && _OSDChange > 0) { _requireAtLeastMinNetDebt(_getNetDebt(vars.debt)- vars.netDebtChange); _requireValidOSDRepayment(vars.debt, vars.netDebtChange); _requireSufficientOSDBalance(contractsCache.osdToken, _borrower, vars.netDebtChange); } (vars.newColl, vars.newDebt) = _updateVaultFromAdjustment(contractsCache.vaultManager, _borrower, vars.collChange, vars.isCollIncrease, vars.netDebtChange, _isDebtIncrease, vars.ROSEFee); vars.stake = contractsCache.vaultManager.updateStakeAndTotalStakes(_borrower); // Re-insert vault in to the sorted list uint newNICR = _getNewNominalICRFromVaultChange(vars.coll, vars.debt, vars.collChange, vars.isCollIncrease, vars.netDebtChange, _isDebtIncrease, vars.ROSEFee); sortedVaults.reInsert(_borrower, newNICR, _upperHint, _lowerHint); emit VaultUpdated(_borrower, vars.newDebt, vars.newColl, vars.stake, uint8(BorrowerOperation.adjustVault)); emit BorrowFeeInROSE(msg.sender, vars.ROSEFee); // Use the unmodified _OSDChange here, as we don't send the fee to the user _moveTokensAndROSEFromAdjustment( contractsCache.activePool, contractsCache.osdToken, msg.sender, vars.collChange, vars.isCollIncrease, _OSDChange, _isDebtIncrease, vars.netDebtChange, vars.ROSEFee ); } function closeVault() external override { IVaultManager vaultManagerCached = vaultManager; IActivePool activePoolCached = activePool; IOSDToken osdTokenCached = osdToken; _requireVaultisActive(vaultManagerCached, msg.sender); uint price = priceFeed.fetchPrice(); _requireNotInRecoveryMode(price); vaultManagerCached.applyPendingRewards(msg.sender); uint coll = vaultManagerCached.getVaultColl(msg.sender); uint debt = vaultManagerCached.getVaultDebt(msg.sender); _requireSufficientOSDBalance(osdTokenCached, msg.sender, debt - OSD_GAS_COMPENSATION); uint newTCR = _getNewTCRFromVaultChange(coll, false, debt, false, 0, price); _requireNewTCRisAboveCCR(newTCR); vaultManagerCached.removeStake(msg.sender); vaultManagerCached.closeVault(msg.sender); emit VaultUpdated(msg.sender, 0, 0, 0, uint8(BorrowerOperation.closeVault)); // Burn the repaid OSD from the user's balance and the gas compensation from the Gas Pool _repayOSD(activePoolCached, osdTokenCached, msg.sender, debt - OSD_GAS_COMPENSATION); _repayOSD(activePoolCached, osdTokenCached, gasPoolAddress, OSD_GAS_COMPENSATION); // Send the collateral back to the user activePoolCached.sendROSE(msg.sender, coll); } /** * Claim remaining collateral from a redemption or from a liquidation with ICR > MCR in Recovery Mode */ function claimCollateral() external override { // send ROSE from CollSurplus Pool to owner collSurplusPool.claimColl(msg.sender); } // --- Helper functions --- function _triggerBorrowingFee(IVaultManager _vaultManager, uint _OSDAmount, uint _maxFeePercentage, uint _price) internal returns (uint) { _vaultManager.decayBaseRateFromBorrowing(); // decay the baseRate state variable uint OSDFee = _vaultManager.getBorrowingFee(_OSDAmount); _requireUserAcceptsFee(OSDFee, _OSDAmount, _maxFeePercentage); // Send fee to LQTY staking contract uint ROSEFee = (OSDFee * DECIMAL_PRECISION)/ _price; return ROSEFee; } function _getUSDValue(uint _coll, uint _price) internal pure returns (uint) { uint usdValue = (_price * _coll) / DECIMAL_PRECISION; return usdValue; } function _getCollChange( uint _collReceived, uint _requestedCollWithdrawal ) internal pure returns(uint collChange, bool isCollIncrease) { if (_collReceived != 0) { collChange = _collReceived; isCollIncrease = true; } else { collChange = _requestedCollWithdrawal; } } // Update vault's coll and debt based on whether they increase or decrease function _updateVaultFromAdjustment ( IVaultManager _vaultManager, address _borrower, uint _collChange, bool _isCollIncrease, uint _debtChange, bool _isDebtIncrease, uint _borrowFee ) internal returns (uint, uint) { uint newColl = (_isCollIncrease) ? _vaultManager.increaseVaultColl(_borrower, _collChange) : _vaultManager.decreaseVaultColl(_borrower, _collChange); newColl = (_isDebtIncrease) ? _vaultManager.decreaseVaultColl(_borrower, _borrowFee): newColl; uint newDebt = (_isDebtIncrease) ? _vaultManager.increaseVaultDebt(_borrower, _debtChange) : _vaultManager.decreaseVaultDebt(_borrower, _debtChange); return (newColl, newDebt); } function _moveTokensAndROSEFromAdjustment ( IActivePool _activePool, IOSDToken _osdToken, address _borrower, uint _collChange, bool _isCollIncrease, uint _OSDChange, bool _isDebtIncrease, uint _netDebtChange, uint _borrowFee ) internal { if (_isDebtIncrease) { _withdrawOSD(_activePool, _osdToken, _borrower, _OSDChange, _netDebtChange); _activePool.sendROSE(orumFeeDistributionAddress, _borrowFee); } else { _repayOSD(_activePool, _osdToken, _borrower, _OSDChange); } if (_isCollIncrease) { _activePoolAddColl(_activePool, _collChange); } else { _activePool.sendROSE(_borrower, _collChange); } } // Send ROSE to Active Pool and increase its recorded ROSE balance function _activePoolAddColl(IActivePool _activePool, uint _amount) internal { (bool success, ) = address(_activePool).call{value: _amount}(""); require(success, "BorrowerOps: Sending ROSE to ActivePool failed"); } // Issue the specified amount of OSD to _account and increases the total active debt (_netDebtIncrease potentially includes a OSDFee) function _withdrawOSD(IActivePool _activePool, IOSDToken _osdToken, address _account, uint _OSDAmount, uint _netDebtIncrease) internal { _activePool.increaseOSDDebt(_netDebtIncrease); _osdToken.mint(_account, _OSDAmount); } // Burn the specified amount of OSD from _account and decreases the total active debt function _repayOSD(IActivePool _activePool, IOSDToken _osdToken, address _account, uint _OSD) internal { _activePool.decreaseOSDDebt(_OSD); _osdToken.burn(_account, _OSD); } // --- 'Require' wrapper functions --- function _requireSingularCollChange(uint _collWithdrawal) internal view { require(msg.value == 0 || _collWithdrawal == 0, "BorrowerOps: Cannot withdraw and add coll"); } function _requireCallerIsBorrower(address _borrower) internal view { require(msg.sender == _borrower, "BorrowerOps: Caller must be the borrower for a withdrawal"); } function _requireNonZeroAdjustment(uint _collWithdrawal, uint _OSDChange) internal view { require(msg.value != 0 || _collWithdrawal != 0 || _OSDChange != 0, "BorrowerOps: There must be either a collateral change or a debt change"); } function _requireVaultisActive(IVaultManager _vaultManager, address _borrower) internal view { uint status = _vaultManager.getVaultStatus(_borrower); require(status == 1, "BorrowerOps: Vault does not exist or is closed"); } function _requireVaultisNotActive(IVaultManager _vaultManager, address _borrower) internal view { uint status = _vaultManager.getVaultStatus(_borrower); require(status != 1, "BorrowerOps: Vault is active"); } function _requireNonZeroDebtChange(uint _OSDChange) internal pure { require(_OSDChange > 0, "BorrowerOps: Debt increase requires non-zero debtChange"); } function _requireNotInRecoveryMode(uint _price) internal view { require(!_checkRecoveryMode(_price), "BorrowerOps: Operation not permitted during Recovery Mode"); } function _requireNoCollWithdrawal(uint _collWithdrawal) internal pure { require(_collWithdrawal == 0, "BorrowerOps: Collateral withdrawal not permitted Recovery Mode"); } function _requireValidAdjustmentInCurrentMode ( bool _isRecoveryMode, uint _collWithdrawal, bool _isDebtIncrease, LocalVariables_adjustVault memory _vars ) internal view { /* *In Recovery Mode, only allow: * * - Pure collateral top-up * - Pure debt repayment * - Collateral top-up with debt repayment * - A debt increase combined with a collateral top-up which makes the ICR >= 150% and improves the ICR (and by extension improves the TCR). * * In Normal Mode, ensure: * * - The new ICR is above MCR * - The adjustment won't pull the TCR below CCR */ if (_isRecoveryMode) { _requireNoCollWithdrawal(_collWithdrawal); if (_isDebtIncrease) { _requireICRisAboveCCR(_vars.newICR); _requireNewICRisAboveOldICR(_vars.newICR, _vars.oldICR); } } else { // if Normal Mode _requireICRisAboveMCR(_vars.newICR); _vars.newTCR = _getNewTCRFromVaultChange(_vars.collChange, _vars.isCollIncrease, _vars.netDebtChange, _isDebtIncrease, _vars.ROSEFee, _vars.price); _requireNewTCRisAboveCCR(_vars.newTCR); } } function _requireICRisAboveMCR(uint _newICR) internal view { require(_newICR >= MCR, "BorrowerOps: An operation that would result in ICR < MCR is not permitted"); } function _requireICRisAboveCCR(uint _newICR) internal view { require(_newICR >= CCR, "BorrowerOps: Operation must leave vault with ICR >= CCR"); } function _requireNewICRisAboveOldICR(uint _newICR, uint _oldICR) internal pure { require(_newICR >= _oldICR, "BorrowerOps: Cannot decrease your Vault's ICR in Recovery Mode"); } function _requireNewTCRisAboveCCR(uint _newTCR) internal view { require(_newTCR >= CCR, "BorrowerOps: An operation that would result in TCR < CCR is not permitted"); } function _requireAtLeastMinNetDebt(uint _netDebt) internal view { require (_netDebt >= MIN_NET_DEBT, "BorrowerOps: Vault's net debt must be greater than minimum"); } function _requireValidOSDRepayment(uint _currentDebt, uint _debtRepayment) internal view { require(_debtRepayment <= _currentDebt - OSD_GAS_COMPENSATION, "BorrowerOps: Amount repaid must not be larger than the Vault's debt"); } function _requireCallerIsStabilityPool() internal view { require(msg.sender == stabilityPoolAddress, "BorrowerOps: Caller is not Stability Pool"); } function _requireSufficientOSDBalance(IOSDToken _osdToken, address _borrower, uint _debtRepayment) internal view { require(_osdToken.balanceOf(_borrower) >= _debtRepayment, "BorrowerOps: Caller doesnt have enough OSD to make repayment"); } function _requireValidMaxFeePercentage(uint _maxFeePercentage, bool _isRecoveryMode) internal view { if (_isRecoveryMode) { require(_maxFeePercentage <= DECIMAL_PRECISION, "Max fee percentage must less than or equal to 100%"); } else { require(_maxFeePercentage >= BORROWING_FEE_FLOOR && _maxFeePercentage <= DECIMAL_PRECISION, "Max fee percentage must be between 0.5% and 100%"); } } // --- ICR and TCR getters --- // Compute the new collateral ratio, considering the change in coll and debt. Assumes 0 pending rewards. function _getNewNominalICRFromVaultChange ( uint _coll, uint _debt, uint _collChange, bool _isCollIncrease, uint _debtChange, bool _isDebtIncrease, uint _borrowFee ) pure internal returns (uint) { (uint newColl, uint newDebt) = _getNewVaultAmounts(_coll, _debt, _collChange, _isCollIncrease, _debtChange, _isDebtIncrease, _borrowFee); uint newNICR = OrumMath._computeNominalCR(newColl, newDebt); return newNICR; } // Compute the new collateral ratio, considering the change in coll and debt. Assumes 0 pending rewards. function _getNewICRFromVaultChange ( uint _coll, uint _debt, uint _collChange, bool _isCollIncrease, uint _debtChange, bool _isDebtIncrease, uint _borrowFee, uint _price ) pure internal returns (uint) { (uint newColl, uint newDebt) = _getNewVaultAmounts(_coll, _debt, _collChange, _isCollIncrease, _debtChange, _isDebtIncrease, _borrowFee); uint newICR = OrumMath._computeCR(newColl, newDebt, _price); return newICR; } function _getNewVaultAmounts( uint _coll, uint _debt, uint _collChange, bool _isCollIncrease, uint _debtChange, bool _isDebtIncrease, uint _borrowFee ) internal pure returns (uint, uint) { uint newColl = _coll; uint newDebt = _debt; newColl = _isCollIncrease ? _coll +_collChange: _coll - _collChange; newDebt = _isDebtIncrease ? _debt + _debtChange : _debt - _debtChange; newColl = _isDebtIncrease ? newColl - _borrowFee: newColl; return (newColl, newDebt); } function _getNewTCRFromVaultChange ( uint _collChange, bool _isCollIncrease, uint _debtChange, bool _isDebtIncrease, uint _borrowFee, uint _price ) internal view returns (uint) { uint totalColl = getEntireSystemColl(); uint totalDebt = getEntireSystemDebt(); totalColl = _isCollIncrease ? totalColl + _collChange : totalColl - _collChange; totalDebt = _isDebtIncrease ? totalDebt + _debtChange: totalDebt - _debtChange; totalColl = _isDebtIncrease ? totalColl - _borrowFee: totalColl; uint newTCR = OrumMath._computeCR(totalColl, totalDebt, _price); return newTCR; } function getCompositeDebt(uint _debt) external view override returns (uint) { return _getCompositeDebt(_debt); } function changeTreasuryAddress(address _orumFeeDistributionAddress) external onlyOwner{ // checkContract(_orumFeeDistributionAddress); orumFeeDistributionAddress = _orumFeeDistributionAddress; emit OrumRevenueAddressChanged(_orumFeeDistributionAddress); } function changeBorrowFeeFloor(uint _newBorrowFeeFloor) external onlyOwner{ BORROWING_FEE_FLOOR = DECIMAL_PRECISION / 1000 * _newBorrowFeeFloor; } function changeMCR(uint _newMCR) external onlyOwner{ MCR = _newMCR; } function changeCCR(uint _newCCR) external onlyOwner{ CCR = _newCCR; } function changeMinNetDebt(uint _newMinDebt) external onlyOwner{ MIN_NET_DEBT = _newMinDebt; } function changeGasCompensation(uint _OSDGasCompensation) external onlyOwner{ OSD_GAS_COMPENSATION = _OSDGasCompensation; } }
In Recovery Mode, only allow: - Pure collateral top-up - Pure debt repayment - Collateral top-up with debt repayment - A debt increase combined with a collateral top-up which makes the ICR >= 150% and improves the ICR (and by extension improves the TCR). In Normal Mode, ensure: - The new ICR is above MCR - The adjustment won't pull the TCR below CCR/
function _requireValidAdjustmentInCurrentMode ( bool _isRecoveryMode, uint _collWithdrawal, bool _isDebtIncrease, LocalVariables_adjustVault memory _vars ) internal view { if (_isRecoveryMode) { _requireNoCollWithdrawal(_collWithdrawal); if (_isDebtIncrease) { _requireICRisAboveCCR(_vars.newICR); _requireNewICRisAboveOldICR(_vars.newICR, _vars.oldICR); } _requireICRisAboveMCR(_vars.newICR); _vars.newTCR = _getNewTCRFromVaultChange(_vars.collChange, _vars.isCollIncrease, _vars.netDebtChange, _isDebtIncrease, _vars.ROSEFee, _vars.price); _requireNewTCRisAboveCCR(_vars.newTCR); } }
5,400,216
[ 1, 382, 23675, 8126, 16, 1338, 1699, 30, 300, 16616, 4508, 2045, 287, 1760, 17, 416, 300, 16616, 18202, 88, 2071, 2955, 300, 17596, 2045, 287, 1760, 17, 416, 598, 18202, 88, 2071, 2955, 300, 432, 18202, 88, 10929, 8224, 598, 279, 4508, 2045, 287, 1760, 17, 416, 1492, 7297, 326, 467, 5093, 1545, 18478, 9, 471, 13069, 3324, 326, 467, 5093, 261, 464, 635, 2710, 13069, 3324, 326, 399, 5093, 2934, 657, 8769, 8126, 16, 3387, 30, 300, 1021, 394, 467, 5093, 353, 5721, 490, 5093, 300, 1021, 18335, 8462, 1404, 6892, 326, 399, 5093, 5712, 385, 5093, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 6528, 1556, 19985, 382, 3935, 2309, 7010, 565, 261, 203, 3639, 1426, 389, 291, 11548, 2309, 16, 203, 3639, 2254, 389, 12910, 1190, 9446, 287, 16, 203, 3639, 1426, 389, 291, 758, 23602, 382, 11908, 16, 7010, 3639, 3566, 6158, 67, 13362, 12003, 3778, 389, 4699, 203, 565, 262, 7010, 3639, 2713, 7010, 3639, 1476, 7010, 565, 288, 203, 3639, 309, 261, 67, 291, 11548, 2309, 13, 288, 203, 5411, 389, 6528, 2279, 13535, 1190, 9446, 287, 24899, 12910, 1190, 9446, 287, 1769, 203, 5411, 309, 261, 67, 291, 758, 23602, 382, 11908, 13, 288, 203, 7734, 389, 6528, 2871, 54, 291, 25477, 39, 5093, 24899, 4699, 18, 2704, 2871, 54, 1769, 203, 7734, 389, 6528, 1908, 2871, 54, 291, 25477, 7617, 2871, 54, 24899, 4699, 18, 2704, 2871, 54, 16, 389, 4699, 18, 1673, 2871, 54, 1769, 203, 5411, 289, 3639, 203, 5411, 389, 6528, 2871, 54, 291, 25477, 49, 5093, 24899, 4699, 18, 2704, 2871, 54, 1769, 203, 5411, 389, 4699, 18, 2704, 56, 5093, 273, 389, 588, 1908, 56, 5093, 1265, 12003, 3043, 24899, 4699, 18, 12910, 3043, 16, 389, 4699, 18, 291, 13535, 382, 11908, 16, 389, 4699, 18, 2758, 758, 23602, 3043, 16, 389, 291, 758, 23602, 382, 11908, 16, 389, 4699, 18, 1457, 1090, 14667, 16, 389, 4699, 18, 8694, 1769, 203, 5411, 389, 6528, 1908, 56, 5093, 291, 25477, 39, 5093, 24899, 4699, 18, 2704, 56, 5093, 1769, 21281, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.25; // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/MultiOwnable.sol /** * @title MultiOwnable.sol * @dev Provide multi-ownable functionality to a smart contract. * @dev Note this contract preserves the idea of a master owner where this owner * cannot be removed or deleted. Master owner's are the only owner's who can add * and remove other owner's. Transfer of master ownership is supported and can * also only be transferred by the current master owner * @dev When master ownership is transferred the original master owner is not * removed from the additional owners list */ pragma solidity 0.4.25; /** * @dev OpenZeppelin Solidity v2.0.0 imports (Using: npm [email protected]) */ contract MultiOwnable is Ownable { /** * @dev Mapping of additional addresses that are considered owners */ mapping (address => bool) additionalOwners; /** * @dev Modifier that overrides 'Ownable' to support multiple owners */ modifier onlyOwner() { // Ensure that msg.sender is an owner or revert require(isOwner(msg.sender), "Permission denied [owner]."); _; } /** * @dev Modifier that provides additional testing to ensure msg.sender * is master owner, or first address to deploy contract */ modifier onlyMaster() { // Ensure that msg.sender is the master user require(super.isOwner(), "Permission denied [master]."); _; } /** * @dev Ownership added event for Dapps interested in this event */ event OwnershipAdded ( address indexed addedOwner ); /** * @dev Ownership removed event for Dapps interested in this event */ event OwnershipRemoved ( address indexed removedOwner ); /** * @dev MultiOwnable .cTor responsible for initialising the masterOwner * or contract super-user * @dev The super user cannot be deleted from the ownership mapping and * can only be transferred */ constructor() Ownable() public { // Obtain owner of the contract (msg.sender) address masterOwner = owner(); // Add the master owner to the additional owners list additionalOwners[masterOwner] = true; } /** * @dev Returns the owner status of the specified address */ function isOwner(address _ownerAddressToLookup) public view returns (bool) { // Return the ownership state of the specified owner address return additionalOwners[_ownerAddressToLookup]; } /** * @dev Returns the master status of the specfied address */ function isMaster(address _masterAddressToLookup) public view returns (bool) { return (super.owner() == _masterAddressToLookup); } /** * @dev Add a new owner address to additional owners mapping * @dev Only the master owner can add additional owner addresses */ function addOwner(address _ownerToAdd) onlyMaster public returns (bool) { // Ensure the new owner address is not address(0) require(_ownerToAdd != address(0), "Invalid address specified (0x0)"); // Ensure that new owner address is not already in the owners list require(!isOwner(_ownerToAdd), "Address specified already in owners list."); // Add new owner to additional owners mapping additionalOwners[_ownerToAdd] = true; emit OwnershipAdded(_ownerToAdd); return true; } /** * @dev Add a new owner address to additional owners mapping * @dev Only the master owner can add additional owner addresses */ function removeOwner(address _ownerToRemove) onlyMaster public returns (bool) { // Ensure that the address to remove is not the master owner require(_ownerToRemove != super.owner(), "Permission denied [master]."); // Ensure that owner address to remove is actually an owner require(isOwner(_ownerToRemove), "Address specified not found in owners list."); // Add remove ownership from address in the additional owners mapping additionalOwners[_ownerToRemove] = false; emit OwnershipRemoved(_ownerToRemove); return true; } /** * @dev Transfer ownership of this contract to another address * @dev Only the master owner can transfer ownership to another address * @dev Only existing owners can have ownership transferred to them */ function transferOwnership(address _newOwnership) onlyMaster public { // Ensure the new ownership is not address(0) require(_newOwnership != address(0), "Invalid address specified (0x0)"); // Ensure the new ownership address is not the current ownership addressess require(_newOwnership != owner(), "Address specified must not match current owner address."); // Ensure that the new ownership is promoted from existing owners require(isOwner(_newOwnership), "Master ownership can only be transferred to an existing owner address."); // Call into the parent class and transfer ownership super.transferOwnership(_newOwnership); // If we get here, then add the new ownership address to the additional owners mapping // Note that the original master owner address was not removed and is still an owner until removed additionalOwners[_newOwnership] = true; } } // File: openzeppelin-solidity/contracts/access/Roles.sol /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private pausers; constructor() internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { pausers.remove(account); emit PauserRemoved(account); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns(bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } // File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor() internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor(uint256 rate, address wallet, IERC20 token) internal { require(rate > 0); require(wallet != address(0)); require(token != address(0)); _rate = rate; _wallet = wallet; _token = token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer fund with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(msg.sender); } /** * @return the token being sold. */ function token() public view returns(IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns(address) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns(uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { require(beneficiary != address(0)); require(weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address beneficiary, uint256 weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isOpen()); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor(uint256 openingTime, uint256 closingTime) internal { // solium-disable-next-line security/no-block-members require(openingTime >= block.timestamp); require(closingTime > openingTime); _openingTime = openingTime; _closingTime = closingTime; } /** * @return the crowdsale opening time. */ function openingTime() public view returns(uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns(uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > _closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal onlyWhileOpen view { super._preValidatePurchase(beneficiary, weiAmount); } } // File: contracts/SparkleBaseCrowdsale.sol /** * @dev SparkelBaseCrowdsale: Core crowdsale functionality */ contract SparkleBaseCrowdsale is MultiOwnable, Pausable, TimedCrowdsale { using SafeMath for uint256; /** * @dev CrowdsaleStage enumeration indicating which operational stage this contract is running */ enum CrowdsaleStage { preICO, bonusICO, mainICO } /** * @dev Internal contract variable stored */ ERC20 public tokenAddress; uint256 public tokenRate; uint256 public tokenCap; uint256 public startTime; uint256 public endTime; address public depositWallet; bool public kycRequired; bool public refundRemainingOk; uint256 public tokensSold; /** * @dev Contribution structure representing a token purchase */ struct OrderBook { uint256 weiAmount; // Amount of Wei that has been contributed towards tokens by this address uint256 pendingTokens; // Total pending tokens held by this address waiting for KYC verification, and user to claim their tokens(pending restrictions) bool kycVerified; // Has this address been kyc validated } // Contributions mapping to user addresses mapping(address => OrderBook) private orders; // Initialize the crowdsale stage to preICO (this stage will change) CrowdsaleStage public crowdsaleStage = CrowdsaleStage.preICO; /** * @dev Event signaling that a number of addresses have been approved for KYC */ event ApprovedKYCAddresses (address indexed _appovedByAddress, uint256 _numberOfApprovals); /** * @dev Event signaling that a number of addresses have been revoked from KYC */ event RevokedKYCAddresses (address indexed _revokedByAddress, uint256 _numberOfRevokals); /** * @dev Event signalling that tokens have been claimed from the crowdsale */ event TokensClaimed (address indexed _claimingAddress, uint256 _tokensClaimed); /** * @dev Event signaling that tokens were sold and how many were sold */ event TokensSold(address indexed _beneficiary, uint256 _tokensSold); /** * @dev Event signaling that toke burn approval has been changed */ event TokenRefundApprovalChanged(address indexed _approvingAddress, bool tokenBurnApproved); /** * @dev Event signaling that token burn approval has been changed */ event CrowdsaleStageChanged(address indexed _changingAddress, uint _newStageValue); /** * @dev Event signaling that crowdsale tokens have been burned */ event CrowdsaleTokensRefunded(address indexed _refundingToAddress, uint256 _numberOfTokensBurned); /** * @dev SparkleTokenCrowdsale Contract contructor */ constructor(ERC20 _tokenAddress, uint256 _tokenRate, uint256 _tokenCap, uint256 _startTime, uint256 _endTime, address _depositWallet, bool _kycRequired) public Crowdsale(_tokenRate, _depositWallet, _tokenAddress) TimedCrowdsale(_startTime, _endTime) MultiOwnable() Pausable() { tokenAddress = _tokenAddress; tokenRate = _tokenRate; tokenCap = _tokenCap; startTime = _startTime; endTime = _endTime; depositWallet = _depositWallet; kycRequired = _kycRequired; refundRemainingOk = false; } /** * @dev claimPendingTokens() provides users with a function to receive their purchase tokens * after their KYC Verification */ function claimTokens() whenNotPaused onlyWhileOpen public { // Ensure calling address is not address(0) require(msg.sender != address(0), "Invalid address specified: address(0)"); // Obtain a copy of the caller's order record OrderBook storage order = orders[msg.sender]; // Ensure caller has been KYC Verified require(order.kycVerified, "Address attempting to claim tokens is not KYC Verified."); // Ensure caller has pending tokens to claim require(order.pendingTokens > 0, "Address does not have any pending tokens to claim."); // For security sake grab the pending token value uint256 localPendingTokens = order.pendingTokens; // zero out pendingTokens to prevent potential re-entrancy vulnverability order.pendingTokens = 0; // Deliver the callers tokens _deliverTokens(msg.sender, localPendingTokens); // Emit event emit TokensClaimed(msg.sender, localPendingTokens); } /** * @dev getExchangeRate() provides a public facing manner in which to * determine the current rate of exchange in the crowdsale * @param _weiAmount is the amount of wei to purchase tokens with * @return number of tokens the specified wei amount would purchase */ function getExchangeRate(uint256 _weiAmount) whenNotPaused onlyWhileOpen public view returns (uint256) { if (crowdsaleStage == CrowdsaleStage.preICO) { // Ensure _weiAmount is > than current stage minimum require(_weiAmount >= 1 ether, "PreICO minimum ether required: 1 ETH."); } else if (crowdsaleStage == CrowdsaleStage.bonusICO || crowdsaleStage == CrowdsaleStage.mainICO) { // Ensure _weiAmount is > than current stage minimum require(_weiAmount >= 500 finney, "bonusICO/mainICO minimum ether required: 0.5 ETH."); } // Calculate the number of tokens this amount of wei is worth uint256 tokenAmount = _getTokenAmount(_weiAmount); // Ensure the number of tokens requests will not exceed available tokens require(getRemainingTokens() >= tokenAmount, "Specified wei value woudld exceed amount of tokens remaining."); // Calculate and return the token amount this amount of wei is worth (includes bonus factor) return tokenAmount; } /** * @dev getRemainingTokens() provides function to return the current remaining token count * @return number of tokens remaining in the crowdsale to be sold */ function getRemainingTokens() whenNotPaused public view returns (uint256) { // Return the balance of the contract (IE: tokenCap - tokensSold) return tokenCap.sub(tokensSold); } /** * @dev refundRemainingTokens provides functionn to refund remaining tokens to the specified address * @param _addressToRefund is the address in which the remaining tokens will be refunded to */ function refundRemainingTokens(address _addressToRefund) onlyOwner whenNotPaused public { // Ensure the specified address is not address(0) require(_addressToRefund != address(0), "Specified address is invalid [0x0]"); // Ensure the crowdsale has closed before burning tokens require(hasClosed(), "Crowdsale must be finished to burn tokens."); // Ensure that step-1 of the burning process is satisfied (owner set to true) require(refundRemainingOk, "Crowdsale remaining token refund is disabled."); uint256 tempBalance = token().balanceOf(this); // Transfer the remaining tokens to specified address _deliverTokens(_addressToRefund, tempBalance); // Emit event emit CrowdsaleTokensRefunded(_addressToRefund, tempBalance); } /** * @dev approveRemainingTokenRefund approves the function to withdraw any remaining tokens * after the crowdsale ends * @dev This was put in place as a two-step process to burn tokens so burning was secure */ function approveRemainingTokenRefund() onlyOwner whenNotPaused public { // Ensure calling address is not address(0) require(msg.sender != address(0), "Calling address invalid [0x0]"); // Ensure the crowdsale has closed before approving token burning require(hasClosed(), "Token burn approval can only be set after crowdsale closes"); refundRemainingOk = true; emit TokenRefundApprovalChanged(msg.sender, refundRemainingOk); } /** * @dev setStage() sets the current crowdsale stage to the specified value * @param _newStageValue is the new stage to be changed to */ function changeCrowdsaleStage(uint _newStageValue) onlyOwner whenNotPaused onlyWhileOpen public { // Create temporary stage variable CrowdsaleStage _stage; // Determine if caller is trying to set: preICO if (uint(CrowdsaleStage.preICO) == _newStageValue) { // Set the internal stage to the new value _stage = CrowdsaleStage.preICO; } // Determine if caller is trying to set: bonusICO else if (uint(CrowdsaleStage.bonusICO) == _newStageValue) { // Set the internal stage to the new value _stage = CrowdsaleStage.bonusICO; } // Determine if caller is trying to set: mainICO else if (uint(CrowdsaleStage.mainICO) == _newStageValue) { // Set the internal stage to the new value _stage = CrowdsaleStage.mainICO; } else { revert("Invalid stage selected"); } // Update the internal crowdsale stage to the new stage crowdsaleStage = _stage; // Emit event emit CrowdsaleStageChanged(msg.sender, uint(_stage)); } /** * @dev isAddressKYCVerified() checks the KYV Verification status of the specified address * @param _addressToLookuo address to check status of KYC Verification * @return kyc status of the specified address */ function isKYCVerified(address _addressToLookuo) whenNotPaused onlyWhileOpen public view returns (bool) { // Ensure _addressToLookuo is not address(0) require(_addressToLookuo != address(0), "Invalid address specified: address(0)"); // Obtain the addresses order record OrderBook storage order = orders[_addressToLookuo]; // Return the JYC Verification status for the specified address return order.kycVerified; } /** * @dev Approve in bulk the specified addfresses indicating they were KYC Verified * @param _addressesForApproval is a list of addresses that are to be KYC Verified */ function bulkApproveKYCAddresses(address[] _addressesForApproval) onlyOwner whenNotPaused onlyWhileOpen public { // Ensure that there are any address(es) in the provided array require(_addressesForApproval.length > 0, "Specified address array is empty"); // Interate through all addresses provided for (uint i = 0; i <_addressesForApproval.length; i++) { // Approve this address using the internal function _approveKYCAddress(_addressesForApproval[i]); } // Emit event indicating address(es) have been approved for KYC Verification emit ApprovedKYCAddresses(msg.sender, _addressesForApproval.length); } /** * @dev Revoke in bulk the specified addfresses indicating they were denied KYC Verified * @param _addressesToRevoke is a list of addresses that are to be KYC Verified */ function bulkRevokeKYCAddresses(address[] _addressesToRevoke) onlyOwner whenNotPaused onlyWhileOpen public { // Ensure that there are any address(es) in the provided array require(_addressesToRevoke.length > 0, "Specified address array is empty"); // Interate through all addresses provided for (uint i = 0; i <_addressesToRevoke.length; i++) { // Approve this address using the internal function _revokeKYCAddress(_addressesToRevoke[i]); } // Emit event indicating address(es) have been revoked for KYC Verification emit RevokedKYCAddresses(msg.sender, _addressesToRevoke.length); } /** * @dev tokensPending() provides owners the function to retrieve an addresses pending * token amount * @param _addressToLookup is the address to return the pending token value for * @return the number of pending tokens waiting to be claimed from specified address */ function tokensPending(address _addressToLookup) onlyOwner whenNotPaused onlyWhileOpen public view returns (uint256) { // Ensure specified address is not address(0) require(_addressToLookup != address(0), "Specified address is invalid [0x0]"); // Obtain the order for specified address OrderBook storage order = orders[_addressToLookup]; // Return the pendingTokens amount return order.pendingTokens; } /** * @dev contributionAmount() provides owners the function to retrieve an addresses total * contribution amount in eth * @param _addressToLookup is the address to return the contribution amount value for * @return the number of ether contribured to the crowdsale by specified address */ function contributionAmount(address _addressToLookup) onlyOwner whenNotPaused onlyWhileOpen public view returns (uint256) { // Ensure specified address is not address(0) require(_addressToLookup != address(0), "Specified address is Invalid [0x0]"); // Obtain the order for specified address OrderBook storage order = orders[_addressToLookup]; // Return the contribution amount in wei return order.weiAmount; } /** * @dev _approveKYCAddress provides the function to approve the specified address * indicating KYC Verified * @param _addressToApprove of the user that is being verified */ function _approveKYCAddress(address _addressToApprove) onlyOwner internal { // Ensure that _addressToApprove is not address(0) require(_addressToApprove != address(0), "Invalid address specified: address(0)"); // Get this addesses contribution record OrderBook storage order = orders[_addressToApprove]; // Set the contribution record to indicate address has been kyc verified order.kycVerified = true; } /** * @dev _revokeKYCAddress() provides the function to revoke previously * granted KYC verification in cases of fraud or false/invalid KYC data * @param _addressToRevoke is the address to remove KYC verification from */ function _revokeKYCAddress(address _addressToRevoke) onlyOwner internal { // Ensure address is not address(0) require(_addressToRevoke != address(0), "Invalid address specified: address(0)"); // Obtain a copy of this addresses contribution record OrderBook storage order = orders[_addressToRevoke]; // Revoke this addresses KYC verification order.kycVerified = false; } /** * @dev _rate() provides the function of calcualting the rate based on crowdsale stage * @param _weiAmount indicated the amount of ether intended to use for purchase * @return number of tokens worth based on specified Wei value */ function _rate(uint _weiAmount) internal view returns (uint256) { require(_weiAmount > 0, "Specified wei amoount must be > 0"); // Determine if the current operation stage of the crowdsale is preICO if (crowdsaleStage == CrowdsaleStage.preICO) { // Determine if the purchase is >= 21 ether if (_weiAmount >= 21 ether) { // 20% bonus return 480e8; } // Determine if the purchase is >= 11 ether if (_weiAmount >= 11 ether) { // 15% bonus return 460e8; } // Determine if the purchase is >= 5 ether if (_weiAmount >= 5 ether) { // 10% bonus return 440e8; } } else // Determine if the current operation stage of the crowdsale is bonusICO if (crowdsaleStage == CrowdsaleStage.bonusICO) { // Determine if the purchase is >= 21 ether if (_weiAmount >= 21 ether) { // 10% bonus return 440e8; } else if (_weiAmount >= 11 ether) { // 7% bonus return 428e8; } else if (_weiAmount >= 5 ether) { // 5% bonus return 420e8; } } // Rate is either < bounus or is main sale so return base rate only return rate(); } /** * @dev Performs token to wei converstion calculations based on crowdsale specification * @param _weiAmount to spend * @return number of tokens purchasable for the specified _weiAmount at crowdsale stage rates */ function _getTokenAmount(uint256 _weiAmount) whenNotPaused internal view returns (uint256) { // Get the current rate set in the constructor and calculate token units per wei uint256 currentRate = _rate(_weiAmount); // Calculate the total number of tokens buyable at based rate (before adding bonus) uint256 sparkleToBuy = currentRate.mul(_weiAmount).div(10e17); // Return proposed token amount return sparkleToBuy; } /** * @dev _preValidatePurchase provides the functionality of pre validating a potential purchase * @param _beneficiary is the address that is currently purchasing tokens * @param _weiAmount is the number of tokens this address is attempting to purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) whenNotPaused internal view { // Call into the parent validation to ensure _beneficiary and _weiAmount are valid super._preValidatePurchase(_beneficiary, _weiAmount); // Calculate amount of tokens for the specified _weiAmount uint256 requestedTokens = getExchangeRate(_weiAmount); // Calculate the currently sold tokens uint256 tempTotalTokensSold = tokensSold; // Incrememt total tokens tempTotalTokensSold.add(requestedTokens); // Ensure total max token cap is > tempTotalTokensSold require(tempTotalTokensSold <= tokenCap, "Requested wei amount will exceed the max token cap and was not accepted."); // Ensure that requested tokens will not go over the remaining token balance require(requestedTokens <= getRemainingTokens(), "Requested tokens would exceed tokens available and was not accepted."); // Obtain the order record for _beneficiary if one exists OrderBook storage order = orders[_beneficiary]; // Ensure this address has been kyc validated require(order.kycVerified, "Address attempting to purchase is not KYC Verified."); // Update this addresses order to reflect the purchase and ether spent order.weiAmount = order.weiAmount.add(_weiAmount); order.pendingTokens = order.pendingTokens.add(requestedTokens); // increment totalTokens sold tokensSold = tokensSold.add(requestedTokens); // Emit event emit TokensSold(_beneficiary, requestedTokens); } /** * @dev _processPurchase() is overridden and will be called by OpenZep v2.0 internally * @param _beneficiary is the address that is currently purchasing tokens * @param _tokenAmount is the number of tokens this address is attempting to purchase */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) whenNotPaused internal { // We do not call the base class _processPurchase() functions. This is needed here or the base // classes function will be called. } } // File: contracts/SparkleCrowdsale.sol contract SparkleCrowdsale is SparkleBaseCrowdsale { // Token contract address address public initTokenAddress = 0x4b7aD3a56810032782Afce12d7d27122bDb96efF; // Crowdsale specification uint256 public initTokenRate = 400e8; uint256 public initTokenCap = 19698000e8; uint256 public initStartTime = now; uint256 public initEndTime = now + 12 weeks; // Set this accordingly as it cannot be changed address public initDepositWallet = 0x0926a84C83d7B88338588Dca2729b590D787FA34; bool public initKYCRequired = true; constructor() SparkleBaseCrowdsale(ERC20(initTokenAddress), initTokenRate, initTokenCap, initStartTime, initEndTime, initDepositWallet, initKYCRequired) public { } }
* @dev Transfer ownership of this contract to another address @dev Only the master owner can transfer ownership to another address @dev Only existing owners can have ownership transferred to them/ Ensure the new ownership is not address(0) Ensure the new ownership address is not the current ownership addressess Ensure that the new ownership is promoted from existing owners Call into the parent class and transfer ownership If we get here, then add the new ownership address to the additional owners mapping Note that the original master owner address was not removed and is still an owner until removed
function transferOwnership(address _newOwnership) onlyMaster public { require(_newOwnership != address(0), "Invalid address specified (0x0)"); require(_newOwnership != owner(), "Address specified must not match current owner address."); require(isOwner(_newOwnership), "Master ownership can only be transferred to an existing owner address."); super.transferOwnership(_newOwnership); additionalOwners[_newOwnership] = true; }
14,059,033
[ 1, 5912, 23178, 434, 333, 6835, 358, 4042, 1758, 225, 5098, 326, 4171, 3410, 848, 7412, 23178, 358, 4042, 1758, 225, 5098, 2062, 25937, 848, 1240, 23178, 906, 4193, 358, 2182, 19, 7693, 326, 394, 23178, 353, 486, 1758, 12, 20, 13, 7693, 326, 394, 23178, 1758, 353, 486, 326, 783, 23178, 1758, 403, 7693, 716, 326, 394, 23178, 353, 3012, 16474, 628, 2062, 25937, 3049, 1368, 326, 982, 667, 471, 7412, 23178, 971, 732, 336, 2674, 16, 1508, 527, 326, 394, 23178, 1758, 358, 326, 3312, 25937, 2874, 3609, 716, 326, 2282, 4171, 3410, 1758, 1703, 486, 3723, 471, 353, 4859, 392, 3410, 3180, 3723, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 7412, 5460, 12565, 12, 2867, 389, 2704, 5460, 12565, 13, 7010, 202, 3700, 7786, 7010, 202, 482, 7010, 202, 95, 203, 202, 202, 6528, 24899, 2704, 5460, 12565, 480, 1758, 12, 20, 3631, 315, 1941, 1758, 1269, 261, 20, 92, 20, 2225, 1769, 203, 202, 202, 6528, 24899, 2704, 5460, 12565, 480, 3410, 9334, 315, 1887, 1269, 1297, 486, 845, 783, 3410, 1758, 1199, 1769, 1082, 203, 202, 202, 6528, 12, 291, 5541, 24899, 2704, 5460, 12565, 3631, 315, 7786, 23178, 848, 1338, 506, 906, 4193, 358, 392, 2062, 3410, 1758, 1199, 1769, 203, 202, 202, 9565, 18, 13866, 5460, 12565, 24899, 2704, 5460, 12565, 1769, 203, 202, 202, 13996, 5460, 414, 63, 67, 2704, 5460, 12565, 65, 273, 638, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Copyright (c) 2016-2018 Clearmatics Technologies Ltd // SPDX-License-Identifier: LGPL-3.0+ pragma solidity ^0.4.23; import "../libraries/ERC223Compatible.sol"; import '../libraries/SafeMath.sol'; /** * @title Reference implementation of the ERC223 standard token. */ contract Token is ERC223 { using SafeMath for uint256; mapping(address => uint256) balances; // List of user balances. event AccountTransfer(); event test(address to); constructor() public { totalSupply = 0; } function mint(uint256 _value) public { totalSupply = totalSupply.add(_value); balances[msg.sender] = balances[msg.sender].add(_value); } function burn(uint256 _value) public { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); } function metadataTransfer(address _to, uint256 _value, bytes32 _ref) public { transfer(_to, _value, _ref); } function rawTransfer(address _to, uint256 _value) public { transfer(_to, _value); } /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _ref Transaction metadata. */ function transfer(address _to, uint256 _value, bytes32 _ref) public { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); // Standard function transfer similar to ERC20 transfer with no _ref . // Added due to backwards compatibility reasons . uint256 codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _ref); } else { emit AccountTransfer(); } emit Transfer(msg.sender, _to, _value, _ref); } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint256 _value) public { bytes32 empty; return transfer(_to, _value, empty); } /** * @dev Returns balance of the `_owner`. * * @param _owner The address whose balance will be returned. * @return balance Balance of the `_owner`. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
* @dev Transfer the specified amount of tokens to the specified address. This function works the same with the previous one but doesn't contain `_data` param. Added due to backwards compatibility reasons. @param _to Receiver address. @param _value Amount of tokens that will be transferred./
function transfer(address _to, uint256 _value) public { bytes32 empty; return transfer(_to, _value, empty); }
1,010,855
[ 1, 5912, 326, 1269, 3844, 434, 2430, 358, 326, 1269, 1758, 18, 1377, 1220, 445, 6330, 326, 1967, 598, 326, 2416, 1245, 1377, 1496, 3302, 1404, 912, 1375, 67, 892, 68, 579, 18, 1377, 25808, 6541, 358, 12727, 8926, 14000, 18, 225, 389, 869, 565, 31020, 1758, 18, 225, 389, 1132, 16811, 434, 2430, 716, 903, 506, 906, 4193, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 288, 203, 3639, 1731, 1578, 1008, 31, 203, 3639, 327, 7412, 24899, 869, 16, 389, 1132, 16, 1008, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/upgrades-core/contracts/Initializable.sol"; import "./interfaces/IPriceModule.sol"; contract APContract is Initializable { address public yieldsterDAO; address public yieldsterTreasury; address public yieldsterGOD; address public emergencyVault; address public yieldsterExchange; address public stringUtils; address public whitelistModule; address public whitelistManager; address public proxyFactory; address public priceModule; address public platFormManagementFee; address public profitManagementFee; address public stockDeposit; address public stockWithdraw; address public safeMinter; address public safeUtils; address public exchangeRegistry; struct Vault { mapping(address => bool) vaultAssets; mapping(address => bool) vaultDepositAssets; mapping(address => bool) vaultWithdrawalAssets; mapping(address => bool) vaultEnabledStrategy; address depositStrategy; address withdrawStrategy; address vaultAPSManager; address vaultStrategyManager; uint256[] whitelistGroup; bool created; uint256 slippage; } struct VaultActiveStrategy { mapping(address => bool) isActiveStrategy; mapping(address => uint256) activeStrategyIndex; address[] activeStrategyList; } struct Strategy { mapping(address => bool) strategyProtocols; bool created; address minter; address executor; address benefeciary; uint256 managementFeePercentage; } struct SmartStrategy { address minter; address executor; bool created; } struct vaultActiveManagemetFee { mapping(address => bool) isActiveManagementFee; mapping(address => uint256) activeManagementFeeIndex; address[] activeManagementFeeList; } event VaultCreation(address vaultAddress); mapping(address => vaultActiveManagemetFee) managementFeeStrategies; mapping(address => mapping(address => mapping(address => bool))) vaultStrategyEnabledProtocols; mapping(address => VaultActiveStrategy) vaultActiveStrategies; mapping(address => bool) assets; mapping(address => bool) protocols; mapping(address => Vault) vaults; mapping(address => Strategy) strategies; mapping(address => SmartStrategy) smartStrategies; mapping(address => bool) vaultCreated; mapping(address => bool) APSManagers; mapping(address => address) minterStrategyMap; function initialize( address _yieldsterDAO, address _yieldsterTreasury, address _yieldsterGOD, address _emergencyVault, address _apsManager ) external initializer { yieldsterDAO = _yieldsterDAO; yieldsterTreasury = _yieldsterTreasury; yieldsterGOD = _yieldsterGOD; emergencyVault = _emergencyVault; APSManagers[_apsManager] = true; } function configureAPS( address _whitelistModule, address _platformManagementFee, address _profitManagementFee, address _stringUtils, address _yieldsterExchange, address _exchangeRegistry, address _priceModule, address _safeUtils ) external onlyYieldsterDAO { whitelistModule = _whitelistModule; platFormManagementFee = _platformManagementFee; stringUtils = _stringUtils; yieldsterExchange = _yieldsterExchange; exchangeRegistry = _exchangeRegistry; priceModule = _priceModule; safeUtils = _safeUtils; profitManagementFee = _profitManagementFee; } /// @dev Function to add proxy Factory address to Yieldster. /// @param _proxyFactory Address of proxy factory. function addProxyFactory(address _proxyFactory) external onlyManager { proxyFactory = _proxyFactory; } function setProfitAndPlatformManagementFeeStrategies( address _platformManagement, address _profitManagement ) external onlyYieldsterDAO { if (_profitManagement != address(0)) profitManagementFee = _profitManagement; if (_platformManagement != address(0)) platFormManagementFee = _platformManagement; } //Modifiers modifier onlyYieldsterDAO { require( yieldsterDAO == msg.sender, "Only Yieldster DAO is allowed to perform this operation" ); _; } modifier onlyManager { require( APSManagers[msg.sender], "Only APS managers allowed to perform this operation!" ); _; } function isVault(address _address) external view returns (bool) { return vaults[_address].created; } /// @dev Function to add APS manager to Yieldster. /// @param _manager Address of the manager. function addManager(address _manager) external onlyYieldsterDAO { APSManagers[_manager] = true; } /// @dev Function to remove APS manager from Yieldster. /// @param _manager Address of the manager. function removeManager(address _manager) external onlyYieldsterDAO { APSManagers[_manager] = false; } /// @dev Function to change whitelist Manager. /// @param _whitelistManager Address of the whitelist manager. function changeWhitelistManager(address _whitelistManager) external onlyYieldsterDAO { whitelistManager = _whitelistManager; } /// @dev Function to set Yieldster GOD. /// @param _yieldsterGOD Address of the Yieldster GOD. function setYieldsterGOD(address _yieldsterGOD) external { require( msg.sender == yieldsterGOD, "Only Yieldster GOD can perform this operation" ); yieldsterGOD = _yieldsterGOD; } /// @dev Function to set Yieldster DAO. /// @param _yieldsterDAO Address of the Yieldster DAO. function setYieldsterDAO(address _yieldsterDAO) external { require( msg.sender == yieldsterDAO, "Only Yieldster DAO can perform this operation" ); yieldsterDAO = _yieldsterDAO; } /// @dev Function to set Yieldster Treasury. /// @param _yieldsterTreasury Address of the Yieldster Treasury. function setYieldsterTreasury(address _yieldsterTreasury) external { require( msg.sender == yieldsterDAO, "Only Yieldster DAO can perform this operation" ); yieldsterTreasury = _yieldsterTreasury; } /// @dev Function to disable Yieldster GOD. function disableYieldsterGOD() external { require( msg.sender == yieldsterGOD, "Only Yieldster GOD can perform this operation" ); yieldsterGOD = address(0); } /// @dev Function to set Emergency vault. /// @param _emergencyVault Address of the Yieldster Emergency vault. function setEmergencyVault(address _emergencyVault) external onlyYieldsterDAO { emergencyVault = _emergencyVault; } /// @dev Function to set Safe Minter. /// @param _safeMinter Address of the Safe Minter. function setSafeMinter(address _safeMinter) external onlyYieldsterDAO { safeMinter = _safeMinter; } /// @dev Function to set safeUtils contract. /// @param _safeUtils Address of the safeUtils contract. function setSafeUtils(address _safeUtils) external onlyYieldsterDAO { safeUtils = _safeUtils; } /// @dev Function to set stringUtils contract. /// @param _stringUtils Address of the stringUtils contract. function setStringUtils(address _stringUtils) external onlyYieldsterDAO { stringUtils = _stringUtils; } /// @dev Function to set whitelistModule contract. /// @param _whitelistModule Address of the whitelistModule contract. function setWhitelistModule(address _whitelistModule) external onlyYieldsterDAO { whitelistModule = _whitelistModule; } /// @dev Function to set exchangeRegistry address. /// @param _exchangeRegistry Address of the exchangeRegistry. function setExchangeRegistry(address _exchangeRegistry) external onlyYieldsterDAO { exchangeRegistry = _exchangeRegistry; } /// @dev Function to get strategy address from minter. /// @param _minter Address of the minter. function getStrategyFromMinter(address _minter) external view returns (address) { return minterStrategyMap[_minter]; } /// @dev Function to set Yieldster Exchange. /// @param _yieldsterExchange Address of the Yieldster exchange. function setYieldsterExchange(address _yieldsterExchange) external onlyYieldsterDAO { yieldsterExchange = _yieldsterExchange; } /// @dev Function to set stock Deposit and Withdraw. /// @param _stockDeposit Address of the stock deposit contract. /// @param _stockWithdraw Address of the stock withdraw contract. function setStockDepositWithdraw( address _stockDeposit, address _stockWithdraw ) external onlyYieldsterDAO { stockDeposit = _stockDeposit; stockWithdraw = _stockWithdraw; } /// @dev Function to change the APS Manager for a vault. /// @param _vaultAPSManager Address of the new APS Manager. function changeVaultAPSManager(address _vaultAPSManager) external { require(vaults[msg.sender].created, "Vault is not present"); vaults[msg.sender].vaultAPSManager = _vaultAPSManager; } /// @dev Function to change the Strategy Manager for a vault. /// @param _vaultStrategyManager Address of the new Strategy Manager. function changeVaultStrategyManager(address _vaultStrategyManager) external { require(vaults[msg.sender].created, "Vault is not present"); vaults[msg.sender].vaultStrategyManager = _vaultStrategyManager; } /// @dev Function to change the Slippage Settings for a vault. /// @param _slippage value of slippage. function setVaultSlippage(uint256 _slippage) external { require(vaults[msg.sender].created, "Vault is not present"); vaults[msg.sender].slippage = _slippage; } /// @dev Function to get the Slippage Settings for a vault. function getVaultSlippage() external view returns (uint256) { require(vaults[msg.sender].created, "Vault is not present"); return vaults[msg.sender].slippage; } //Price Module /// @dev Function to set Yieldster price module. /// @param _priceModule Address of the price module. function setPriceModule(address _priceModule) external onlyManager { priceModule = _priceModule; } /// @dev Function to get the USD price for a token. /// @param _tokenAddress Address of the token. function getUSDPrice(address _tokenAddress) external view returns (uint256) { return IPriceModule(priceModule).getUSDPrice(_tokenAddress); } //Vaults /// @dev Function to create a vault. /// @param _vaultAddress Address of the new vault. function createVault(address _vaultAddress) external { require( msg.sender == proxyFactory, "Only Proxy Factory can perform this operation" ); vaultCreated[_vaultAddress] = true; } /// @dev Function to add a vault in the APS. /// @param _vaultAPSManager Address of the vaults APS Manager. /// @param _vaultStrategyManager Address of the vaults Strateg Manager. /// @param _whitelistGroup List of whitelist groups applied to the vault. function addVault( address _vaultAPSManager, address _vaultStrategyManager, uint256[] calldata _whitelistGroup ) external { require(vaultCreated[msg.sender], "Vault not created"); Vault memory newVault = Vault({ vaultAPSManager: _vaultAPSManager, vaultStrategyManager: _vaultStrategyManager, whitelistGroup: _whitelistGroup, depositStrategy: stockDeposit, withdrawStrategy: stockWithdraw, created: true, slippage: 50 }); vaults[msg.sender] = newVault; //applying Platform management fee managementFeeStrategies[msg.sender].isActiveManagementFee[ platFormManagementFee ] = true; managementFeeStrategies[msg.sender].activeManagementFeeIndex[ platFormManagementFee ] = managementFeeStrategies[msg.sender].activeManagementFeeList.length; managementFeeStrategies[msg.sender].activeManagementFeeList.push( platFormManagementFee ); //applying Profit management fee managementFeeStrategies[msg.sender].isActiveManagementFee[ profitManagementFee ] = true; managementFeeStrategies[msg.sender].activeManagementFeeIndex[ profitManagementFee ] = managementFeeStrategies[msg.sender].activeManagementFeeList.length; managementFeeStrategies[msg.sender].activeManagementFeeList.push( profitManagementFee ); } /// @dev Function to Manage the vault assets. /// @param _enabledDepositAsset List of deposit assets to be enabled in the vault. /// @param _enabledWithdrawalAsset List of withdrawal assets to be enabled in the vault. /// @param _disabledDepositAsset List of deposit assets to be disabled in the vault. /// @param _disabledWithdrawalAsset List of withdrawal assets to be disabled in the vault. function setVaultAssets( address[] calldata _enabledDepositAsset, address[] calldata _enabledWithdrawalAsset, address[] calldata _disabledDepositAsset, address[] calldata _disabledWithdrawalAsset ) external { require(vaults[msg.sender].created, "Vault not present"); for (uint256 i = 0; i < _enabledDepositAsset.length; i++) { address asset = _enabledDepositAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultDepositAssets[asset] = true; } for (uint256 i = 0; i < _enabledWithdrawalAsset.length; i++) { address asset = _enabledWithdrawalAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultWithdrawalAssets[asset] = true; } for (uint256 i = 0; i < _disabledDepositAsset.length; i++) { address asset = _disabledDepositAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultDepositAssets[asset] = false; } for (uint256 i = 0; i < _disabledWithdrawalAsset.length; i++) { address asset = _disabledWithdrawalAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultWithdrawalAssets[asset] = false; } } /// @dev Function to get the list of management fee strategies applied to the vault. function getVaultManagementFee() external view returns (address[] memory) { require(vaults[msg.sender].created, "Vault not present"); return managementFeeStrategies[msg.sender].activeManagementFeeList; } /// @dev Function to get the deposit strategy applied to the vault. function getDepositStrategy() external view returns (address) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].depositStrategy; } /// @dev Function to get the withdrawal strategy applied to the vault. function getWithdrawStrategy() external view returns (address) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].withdrawStrategy; } /// @dev Function to set the management fee strategies applied to a vault. /// @param _vaultAddress Address of the vault. /// @param _managementFeeAddress Address of the management fee strategy. function setManagementFeeStrategies( address _vaultAddress, address _managementFeeAddress ) external { require(vaults[_vaultAddress].created, "Vault not present"); require( vaults[_vaultAddress].vaultStrategyManager == msg.sender, "Sender not Authorized" ); managementFeeStrategies[_vaultAddress].isActiveManagementFee[ _managementFeeAddress ] = true; managementFeeStrategies[_vaultAddress].activeManagementFeeIndex[ _managementFeeAddress ] = managementFeeStrategies[_vaultAddress] .activeManagementFeeList .length; managementFeeStrategies[_vaultAddress].activeManagementFeeList.push( _managementFeeAddress ); } /// @dev Function to deactivate a vault strategy. /// @param _managementFeeAddress Address of the Management Fee Strategy. function removeManagementFeeStrategies( address _vaultAddress, address _managementFeeAddress ) external { require(vaults[_vaultAddress].created, "Vault not present"); require( managementFeeStrategies[_vaultAddress].isActiveManagementFee[ _managementFeeAddress ], "Provided ManagementFee is not active" ); require( vaults[_vaultAddress].vaultStrategyManager == msg.sender || yieldsterDAO == msg.sender, "Sender not Authorized" ); require( platFormManagementFee != _managementFeeAddress || yieldsterDAO == msg.sender, "Platfrom Management only changable by dao!" ); managementFeeStrategies[_vaultAddress].isActiveManagementFee[ _managementFeeAddress ] = false; if ( managementFeeStrategies[_vaultAddress] .activeManagementFeeList .length == 1 ) { managementFeeStrategies[_vaultAddress] .activeManagementFeeList .pop(); } else { uint256 index = managementFeeStrategies[_vaultAddress] .activeManagementFeeIndex[_managementFeeAddress]; uint256 lastIndex = managementFeeStrategies[_vaultAddress] .activeManagementFeeList .length - 1; delete managementFeeStrategies[_vaultAddress] .activeManagementFeeList[index]; managementFeeStrategies[_vaultAddress].activeManagementFeeIndex[ managementFeeStrategies[_vaultAddress].activeManagementFeeList[ lastIndex ] ] = index; managementFeeStrategies[_vaultAddress].activeManagementFeeList[ index ] = managementFeeStrategies[_vaultAddress].activeManagementFeeList[ lastIndex ]; managementFeeStrategies[_vaultAddress] .activeManagementFeeList .pop(); } } /// @dev Function to set vault active strategy. /// @param _strategyAddress Address of the strategy. function setVaultActiveStrategy(address _strategyAddress) external { require(vaults[msg.sender].created, "Vault not present"); require( _isStrategyEnabled(msg.sender, _strategyAddress), "This strategy is not enabled" ); require(strategies[_strategyAddress].created, "Strategy not present"); vaultActiveStrategies[msg.sender].isActiveStrategy[ _strategyAddress ] = true; vaultActiveStrategies[msg.sender].activeStrategyIndex[ _strategyAddress ] = vaultActiveStrategies[msg.sender].activeStrategyList.length; vaultActiveStrategies[msg.sender].activeStrategyList.push( _strategyAddress ); } /// @dev Function to deactivate a vault strategy. /// @param _strategyAddress Address of the strategy. function deactivateVaultStrategy(address _strategyAddress) external { require(vaults[msg.sender].created, "Vault not present"); require( vaultActiveStrategies[msg.sender].isActiveStrategy[ _strategyAddress ], "Provided strategy is not active" ); vaultActiveStrategies[msg.sender].isActiveStrategy[ _strategyAddress ] = false; if (vaultActiveStrategies[msg.sender].activeStrategyList.length == 1) { vaultActiveStrategies[msg.sender].activeStrategyList.pop(); } else { uint256 index = vaultActiveStrategies[msg.sender] .activeStrategyIndex[_strategyAddress]; uint256 lastIndex = vaultActiveStrategies[msg.sender] .activeStrategyList .length - 1; delete vaultActiveStrategies[msg.sender].activeStrategyList[index]; vaultActiveStrategies[msg.sender].activeStrategyIndex[ vaultActiveStrategies[msg.sender].activeStrategyList[lastIndex] ] = index; vaultActiveStrategies[msg.sender].activeStrategyList[ index ] = vaultActiveStrategies[msg.sender].activeStrategyList[lastIndex]; vaultActiveStrategies[msg.sender].activeStrategyList.pop(); } } /// @dev Function to get vault active strategy. function getVaultActiveStrategy(address _vaultAddress) external view returns (address[] memory) { require(vaults[_vaultAddress].created, "Vault not present"); return vaultActiveStrategies[_vaultAddress].activeStrategyList; } function isStrategyActive(address _vaultAddress, address _strategyAddress) external view returns (bool) { return vaultActiveStrategies[_vaultAddress].isActiveStrategy[ _strategyAddress ]; } function getStrategyManagementDetails( address _vaultAddress, address _strategyAddress ) external view returns (address, uint256) { require(vaults[_vaultAddress].created, "Vault not present"); require(strategies[_strategyAddress].created, "Strategy not present"); require( vaultActiveStrategies[_vaultAddress].isActiveStrategy[ _strategyAddress ], "Strategy not Active" ); return ( strategies[_strategyAddress].benefeciary, strategies[_strategyAddress].managementFeePercentage ); } /// @dev Function to Manage the vault strategies. /// @param _vaultStrategy Address of the strategy. /// @param _enabledStrategyProtocols List of protocols that are enabled in the strategy. /// @param _disabledStrategyProtocols List of protocols that are disabled in the strategy. /// @param _assetsToBeEnabled List of assets that have to be enabled along with the strategy. function setVaultStrategyAndProtocol( address _vaultStrategy, address[] calldata _enabledStrategyProtocols, address[] calldata _disabledStrategyProtocols, address[] calldata _assetsToBeEnabled ) external { require(vaults[msg.sender].created, "Vault not present"); require(strategies[_vaultStrategy].created, "Strategy not present"); vaults[msg.sender].vaultEnabledStrategy[_vaultStrategy] = true; for (uint256 i = 0; i < _enabledStrategyProtocols.length; i++) { address protocol = _enabledStrategyProtocols[i]; require( _isProtocolPresent(protocol), "Protocol not supported by Yieldster" ); vaultStrategyEnabledProtocols[msg.sender][_vaultStrategy][ protocol ] = true; } for (uint256 i = 0; i < _disabledStrategyProtocols.length; i++) { address protocol = _disabledStrategyProtocols[i]; require( _isProtocolPresent(protocol), "Protocol not supported by Yieldster" ); vaultStrategyEnabledProtocols[msg.sender][_vaultStrategy][ protocol ] = false; } for (uint256 i = 0; i < _assetsToBeEnabled.length; i++) { address asset = _assetsToBeEnabled[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultDepositAssets[asset] = true; vaults[msg.sender].vaultWithdrawalAssets[asset] = true; } } /// @dev Function to disable the vault strategies. /// @param _strategyAddress Address of the strategy. /// @param _assetsToBeDisabled List of assets that have to be disabled along with the strategy. function disableVaultStrategy( address _strategyAddress, address[] calldata _assetsToBeDisabled ) external { require(vaults[msg.sender].created, "Vault not present"); require(strategies[_strategyAddress].created, "Strategy not present"); require( vaults[msg.sender].vaultEnabledStrategy[_strategyAddress], "Strategy was not enabled" ); vaults[msg.sender].vaultEnabledStrategy[_strategyAddress] = false; for (uint256 i = 0; i < _assetsToBeDisabled.length; i++) { address asset = _assetsToBeDisabled[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultDepositAssets[asset] = false; vaults[msg.sender].vaultWithdrawalAssets[asset] = false; } } /// @dev Function to set smart strategy applied to the vault. /// @param _smartStrategyAddress Address of the smart strategy. /// @param _type type of smart strategy(deposit or withdraw). function setVaultSmartStrategy(address _smartStrategyAddress, uint256 _type) external { require(vaults[msg.sender].created, "Vault not present"); require( _isSmartStrategyPresent(_smartStrategyAddress), "Smart Strategy not Supported by Yieldster" ); if (_type == 1) { vaults[msg.sender].depositStrategy = _smartStrategyAddress; } else if (_type == 2) { vaults[msg.sender].withdrawStrategy = _smartStrategyAddress; } else { revert("Invalid type provided"); } } /// @dev Function to check if a particular protocol is enabled in a strategy for a vault. /// @param _vaultAddress Address of the vault. /// @param _strategyAddress Address of the strategy. /// @param _protocolAddress Address of the protocol to check. function _isStrategyProtocolEnabled( address _vaultAddress, address _strategyAddress, address _protocolAddress ) external view returns (bool) { if ( vaults[_vaultAddress].created && strategies[_strategyAddress].created && protocols[_protocolAddress] && vaults[_vaultAddress].vaultEnabledStrategy[_strategyAddress] && vaultStrategyEnabledProtocols[_vaultAddress][_strategyAddress][ _protocolAddress ] ) { return true; } else { return false; } } /// @dev Function to check if a strategy is enabled for the vault. /// @param _vaultAddress Address of the vault. /// @param _strategyAddress Address of the strategy. function _isStrategyEnabled(address _vaultAddress, address _strategyAddress) public view returns (bool) { if ( vaults[_vaultAddress].created && strategies[_strategyAddress].created && vaults[_vaultAddress].vaultEnabledStrategy[_strategyAddress] ) { return true; } else { return false; } } /// @dev Function to check if the asset is supported by the vault. /// @param cleanUpAsset Address of the asset. function _isVaultAsset(address cleanUpAsset) external view returns (bool) { require(vaults[msg.sender].created, "Vault is not present"); return vaults[msg.sender].vaultAssets[cleanUpAsset]; } // Assets /// @dev Function to check if an asset is supported by Yieldster. /// @param _address Address of the asset. function _isAssetPresent(address _address) private view returns (bool) { return assets[_address]; } /// @dev Function to add an asset to the Yieldster. /// @param _tokenAddress Address of the asset. function addAsset(address _tokenAddress) external onlyManager { require(!_isAssetPresent(_tokenAddress), "Asset already present!"); assets[_tokenAddress] = true; } /// @dev Function to remove an asset from the Yieldster. /// @param _tokenAddress Address of the asset. function removeAsset(address _tokenAddress) external onlyManager { require(_isAssetPresent(_tokenAddress), "Asset not present!"); delete assets[_tokenAddress]; } /// @dev Function to check if an asset is supported deposit asset in the vault. /// @param _assetAddress Address of the asset. function isDepositAsset(address _assetAddress) external view returns (bool) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].vaultDepositAssets[_assetAddress]; } /// @dev Function to check if an asset is supported withdrawal asset in the vault. /// @param _assetAddress Address of the asset. function isWithdrawalAsset(address _assetAddress) external view returns (bool) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].vaultWithdrawalAssets[_assetAddress]; } //Strategies /// @dev Function to check if a strategy is supported by Yieldster. /// @param _address Address of the strategy. function _isStrategyPresent(address _address) private view returns (bool) { return strategies[_address].created; } /// @dev Function to add a strategy to Yieldster. /// @param _strategyAddress Address of the strategy. /// @param _strategyProtocols List of protocols present in the strategy. /// @param _minter Address of strategy minter. /// @param _executor Address of strategy executor. function addStrategy( address _strategyAddress, address[] calldata _strategyProtocols, address _minter, address _executor, address _benefeciary, uint256 _managementFeePercentage ) external onlyManager { require( !_isStrategyPresent(_strategyAddress), "Strategy already present!" ); Strategy memory newStrategy = Strategy({ created: true, minter: _minter, executor: _executor, benefeciary: _benefeciary, managementFeePercentage: _managementFeePercentage }); strategies[_strategyAddress] = newStrategy; minterStrategyMap[_minter] = _strategyAddress; for (uint256 i = 0; i < _strategyProtocols.length; i++) { address protocol = _strategyProtocols[i]; require( _isProtocolPresent(protocol), "Protocol not supported by Yieldster" ); strategies[_strategyAddress].strategyProtocols[protocol] = true; } } /// @dev Function to remove a strategy from Yieldster. /// @param _strategyAddress Address of the strategy. function removeStrategy(address _strategyAddress) external onlyManager { require(_isStrategyPresent(_strategyAddress), "Strategy not present!"); delete strategies[_strategyAddress]; } /// @dev Function to get strategy executor address. /// @param _strategy Address of the strategy. function strategyExecutor(address _strategy) external view returns (address) { return strategies[_strategy].executor; } /// @dev Function to change executor of strategy. /// @param _strategyAddress Address of the strategy. /// @param _executor Address of the executor. function changeStrategyExecutor(address _strategyAddress, address _executor) external onlyManager { require(_isStrategyPresent(_strategyAddress), "Strategy not present!"); strategies[_strategyAddress].executor = _executor; } //Smart Strategy /// @dev Function to check if a smart strategy is supported by Yieldster. /// @param _address Address of the smart strategy. function _isSmartStrategyPresent(address _address) private view returns (bool) { return smartStrategies[_address].created; } /// @dev Function to add a smart strategy to Yieldster. /// @param _smartStrategyAddress Address of the smart strategy. function addSmartStrategy( address _smartStrategyAddress, address _minter, address _executor ) external onlyManager { require( !_isSmartStrategyPresent(_smartStrategyAddress), "Smart Strategy already present!" ); SmartStrategy memory newSmartStrategy = SmartStrategy({ minter: _minter, executor: _executor, created: true }); smartStrategies[_smartStrategyAddress] = newSmartStrategy; minterStrategyMap[_minter] = _smartStrategyAddress; } /// @dev Function to remove a smart strategy from Yieldster. /// @param _smartStrategyAddress Address of the smart strategy. function removeSmartStrategy(address _smartStrategyAddress) external onlyManager { require( !_isSmartStrategyPresent(_smartStrategyAddress), "Smart Strategy not present" ); delete smartStrategies[_smartStrategyAddress]; } /// @dev Function to get ssmart strategy executor address. /// @param _smartStrategy Address of the strategy. function smartStrategyExecutor(address _smartStrategy) external view returns (address) { return smartStrategies[_smartStrategy].executor; } /// @dev Function to change executor of smart strategy. /// @param _smartStrategy Address of the smart strategy. /// @param _executor Address of the executor. function changeSmartStrategyExecutor( address _smartStrategy, address _executor ) external onlyManager { require( _isSmartStrategyPresent(_smartStrategy), "Smart Strategy not present!" ); smartStrategies[_smartStrategy].executor = _executor; } // Protocols /// @dev Function to check if a protocol is supported by Yieldster. /// @param _address Address of the protocol. function _isProtocolPresent(address _address) private view returns (bool) { return protocols[_address]; } /// @dev Function to add a protocol to Yieldster. /// @param _protocolAddress Address of the protocol. function addProtocol(address _protocolAddress) external onlyManager { require( !_isProtocolPresent(_protocolAddress), "Protocol already present!" ); protocols[_protocolAddress] = true; } /// @dev Function to remove a protocol from Yieldster. /// @param _protocolAddress Address of the protocol. function removeProtocol(address _protocolAddress) external onlyManager { require(_isProtocolPresent(_protocolAddress), "Protocol not present!"); delete protocols[_protocolAddress]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.7.0; pragma experimental ABIEncoderV2; interface IPriceModule { function getUSDPrice(address ) external view returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
@dev Function to get the Slippage Settings for a vault.
function getVaultSlippage() external view returns (uint256) { require(vaults[msg.sender].created, "Vault is not present"); return vaults[msg.sender].slippage; }
13,825,054
[ 1, 2083, 358, 336, 326, 348, 3169, 2433, 8709, 364, 279, 9229, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11031, 3714, 55, 3169, 2433, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 26983, 87, 63, 3576, 18, 15330, 8009, 4824, 16, 315, 12003, 353, 486, 3430, 8863, 203, 3639, 327, 9229, 87, 63, 3576, 18, 15330, 8009, 87, 3169, 2433, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 public _token; // Address where funds are collected address public _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public _rate; // Amount of wei raised uint256 public _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor(uint256 rate, address wallet, IERC20 token) public { require(rate > 0); require(wallet != address(0)); require(token != address(0)); _rate = rate; _wallet = wallet; _token = token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param beneficiary Address performing the token purchase */ function buyTokens(address beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal { require(beneficiary != address(0)); require(weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address beneficiary, uint256 weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { _token.transferFrom(owner,beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address beneficiary, uint256 weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public _openingTime; uint256 public _closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isOpen()); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor(uint256 openingTime, uint256 closingTime) public { // solium-disable-next-line security/no-block-members require(openingTime >= block.timestamp); require(closingTime >= openingTime); _openingTime = openingTime; _closingTime = closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > _closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(beneficiary, weiAmount); } } /** * @title EscrowAccountCrowdsale. */ contract EscrowAccountCrowdsale is TimedCrowdsale { using SafeMath for uint256; EscrowVault public vault; /** * @dev Constructor, creates EscrowAccountCrowdsale. */ function EscrowAccountCrowdsale() public { vault = new EscrowVault(_wallet); } /** * @dev Investors can claim refunds here if whitelisted is unsuccessful */ function returnInvestoramount(address _beneficiary, uint256 _percentage) internal onlyOwner { vault.refund(_beneficiary); } /** * @dev Investors can claim refunds here if whitelisted is unsuccessful */ function adminChargeForDebit(address _beneficiary, uint256 _adminCharge) internal onlyOwner { vault.debitForFailed(_beneficiary,_adminCharge); } function afterWhtelisted(address _beneficiary) internal onlyOwner{ vault.closeAfterWhitelisted(_beneficiary); } function afterWhtelistedBuy(address _beneficiary) internal { vault.closeAfterWhitelisted(_beneficiary); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } /** * @title EscrowVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if whitelist fails, * and forwarding it if whitelist is successful. */ contract EscrowVault is Ownable { using SafeMath for uint256; mapping (address => uint256) public deposited; address public wallet; event Closed(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ function EscrowVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner payable { deposited[investor] = deposited[investor].add(msg.value); } /** * @dev Transfers deposited amount to wallet address after verification is completed. * @param _beneficiary depositor address. */ function closeAfterWhitelisted(address _beneficiary) onlyOwner public { uint256 depositedValue = deposited[_beneficiary]; deposited[_beneficiary] = 0; wallet.transfer(depositedValue); } /** * @param investor Investor address */ function debitForFailed(address investor, uint256 _debit)public onlyOwner { uint256 depositedValue = deposited[investor]; depositedValue=depositedValue.sub(_debit); wallet.transfer(_debit); deposited[investor] = depositedValue; } /** * @dev * @param investor Investor address */ function refund(address investor)public onlyOwner { uint256 depositedValue = deposited[investor]; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); deposited[investor] = 0; } } /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it whitelisted and crowdsale ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) public _balances; /** * @dev Withdraw tokens only after whitelisted ends and after crowdsale ends. */ function withdrawTokens() public { require(hasClosed()); uint256 amount = _balances[msg.sender]; require(amount > 0); _balances[msg.sender] = 0; _deliverTokens(msg.sender, amount); } /** * @dev Debits token for the failed verification * @param _beneficiary address from which tokens debited * @param _token amount of tokens to be debited */ function failedWhitelistForDebit(address _beneficiary,uint256 _token) internal { require(_beneficiary != address(0)); uint256 amount = _balances[_beneficiary]; _balances[_beneficiary] = amount.sub(_token); } /** * @dev debits entire tokens after refund, if verification completely failed * @param _beneficiary address from which tokens debited */ function failedWhitelist(address _beneficiary) internal { require(_beneficiary != address(0)); uint256 amount = _balances[_beneficiary]; _balances[_beneficiary] = 0; } function getInvestorDepositAmount(address _investor) public constant returns(uint256 paid){ return _balances[_investor]; } /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _balances[_beneficiary] = _balances[_beneficiary].add(_tokenAmount); } } contract BitcoinageCrowdsale is TimedCrowdsale,EscrowAccountCrowdsale,PostDeliveryCrowdsale { enum Stage {KYC_FAILED, KYC_SUCCESS,AML_FAILED, AML_SUCCESS} //stage PreSale or PublicSale enum Phase {PRESALE, PUBLICSALE} //stage ICO Phase public phase; uint256 private constant DECIMALFACTOR = 10**uint256(18); uint256 public _totalSupply=200000000 * DECIMALFACTOR; uint256 public presale=5000000* DECIMALFACTOR; uint256 public publicsale=110000000* DECIMALFACTOR; uint256 public teamAndAdvisorsAndBountyAllocation = 12000000 * DECIMALFACTOR; uint256 public operatingBudgetAllocation = 5000000 * DECIMALFACTOR; uint256 public tokensVested = 28000000 * DECIMALFACTOR; struct whitelisted{ Stage stage; } uint256 public adminCharge=0.025 ether; uint256 public minContribAmount = 0.2 ether; // min invesment mapping(address => whitelisted) public whitelist; // How much ETH each address has invested to this crowdsale mapping (address => uint256) public investedAmountOf; // How many distinct addresses have invested uint256 public investorCount; // decimalFactor event updateRate(uint256 tokenRate, uint256 time); /** * @dev BitcoinageCrowdsale is a base contract for managing a token crowdsale. * BitcoinageCrowdsale have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ function BitcoinageCrowdsale(uint256 _starttime, uint256 _endTime, uint256 _rate, address _wallet,IERC20 _token) TimedCrowdsale(_starttime,_endTime)Crowdsale(_rate, _wallet,_token) { phase = Phase.PRESALE; } /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev token purchased on sending ether * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable onlyWhileOpen{ require(_beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(_rate); if(phase==Phase.PRESALE){ assert(presale>=tokens); presale=presale.sub(tokens); }else{ assert(publicsale>=tokens); publicsale=publicsale.sub(tokens); } _forwardFunds(); _processPurchase(_beneficiary, tokens); if(investedAmountOf[msg.sender] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[msg.sender] = investedAmountOf[msg.sender].add(weiAmount); if(whitelist[_beneficiary].stage==Stage.AML_SUCCESS){ afterWhtelistedBuy(_beneficiary); } } function validPurchase() internal constant returns (bool) { bool minContribution = minContribAmount <= msg.value; return minContribution; } /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary].stage==Stage.AML_SUCCESS); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary,uint256 _stage) external onlyOwner { require(_beneficiary != address(0)); if(_stage==1){ failedWhitelistForDebit(_beneficiary,_rate.mul(adminCharge)); adminChargeForDebit(_beneficiary,adminCharge); whitelist[_beneficiary].stage=Stage.KYC_FAILED; uint256 value=investedAmountOf[_beneficiary]; value=value.sub(adminCharge); investedAmountOf[_beneficiary]=value; }else if(_stage==2){ whitelist[_beneficiary].stage=Stage.KYC_SUCCESS; }else if(_stage==3){ whitelist[_beneficiary].stage=Stage.AML_FAILED; returnInvestoramount(_beneficiary,adminCharge); failedWhitelist(_beneficiary); investedAmountOf[_beneficiary]=0; }else if(_stage==4){ whitelist[_beneficiary].stage=Stage.AML_SUCCESS; afterWhtelisted( _beneficiary); } } /** * @dev Withdraw tokens only after Investors added into whitelist . */ function withdrawTokens() public isWhitelisted(msg.sender) { uint256 amount = _balances[msg.sender]; require(amount > 0); _deliverTokens(msg.sender, amount); _balances[msg.sender] = 0; } /** * @dev Change crowdsale ClosingTime * @param _endTime is End time in Seconds */ function changeEndtime(uint256 _endTime) public onlyOwner { require(_endTime > 0); _closingTime = _endTime; } /** * @dev Change crowdsale OpeningTime * @param _startTime is End time in Seconds */ function changeStarttime(uint256 _startTime) public onlyOwner { require(_startTime > 0); _openingTime = _startTime; } /** * @dev Change Stage. * @param _rate for ETH Per Token */ function changeStage(uint256 _rate) public onlyOwner { require(_rate>0); _rate=_rate; phase=Phase.PUBLICSALE; } /** * @dev Change Token rate per ETH * @param _rate is set the current rate of AND Token */ function changeRate(uint256 _rate) public onlyOwner { require(_rate > 0); _rate = _rate; emit updateRate(_rate,block.timestamp); } /** * @dev Change adminCharge Amount. * @param _adminCharge for debit ETH amount */ function changeAdminCharge(uint256 _adminCharge) public onlyOwner { require(_adminCharge > 0); adminCharge=_adminCharge; } /** * @dev transfer tokens to advisor and bounty team. * @param to for recipiant address * @param tokens is amount of tokens */ function transferTeamAndAdvisorsAndBountyAllocation (address to, uint256 tokens) public onlyOwner { require ( to != 0x0 && tokens > 0 && teamAndAdvisorsAndBountyAllocation >= tokens ); _deliverTokens(to, tokens); teamAndAdvisorsAndBountyAllocation = teamAndAdvisorsAndBountyAllocation.sub(tokens); } /** * @dev transfer vested tokens. * @param to for recipiant address * @param tokens is amount of tokens */ function transferTokensVested(address to, uint256 tokens) public onlyOwner { require ( to != 0x0 && tokens > 0 && tokensVested >= tokens ); _deliverTokens(to, tokens); tokensVested = tokensVested.sub(tokens); } /** * @dev transfer tokens to operating team. * @param to for recipiant address * @param tokens is amount of tokens */ function transferOperatingBudgetAllocation(address to, uint256 tokens) public onlyOwner { require ( to != 0x0 && tokens > 0 && operatingBudgetAllocation >= tokens ); _deliverTokens(to, tokens); operatingBudgetAllocation = operatingBudgetAllocation.sub(tokens); } }
stage PreSale or PublicSalestage ICO
contract BitcoinageCrowdsale is TimedCrowdsale,EscrowAccountCrowdsale,PostDeliveryCrowdsale { Phase public phase; uint256 private constant DECIMALFACTOR = 10**uint256(18); uint256 public _totalSupply=200000000 * DECIMALFACTOR; uint256 public presale=5000000* DECIMALFACTOR; uint256 public publicsale=110000000* DECIMALFACTOR; uint256 public teamAndAdvisorsAndBountyAllocation = 12000000 * DECIMALFACTOR; uint256 public operatingBudgetAllocation = 5000000 * DECIMALFACTOR; uint256 public tokensVested = 28000000 * DECIMALFACTOR; enum Stage {KYC_FAILED, KYC_SUCCESS,AML_FAILED, AML_SUCCESS} enum Phase {PRESALE, PUBLICSALE} struct whitelisted{ Stage stage; } uint256 public adminCharge=0.025 ether; mapping(address => whitelisted) public whitelist; event updateRate(uint256 tokenRate, uint256 time); mapping (address => uint256) public investedAmountOf; uint256 public investorCount; function BitcoinageCrowdsale(uint256 _starttime, uint256 _endTime, uint256 _rate, address _wallet,IERC20 _token) TimedCrowdsale(_starttime,_endTime)Crowdsale(_rate, _wallet,_token) { phase = Phase.PRESALE; } function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable onlyWhileOpen{ require(_beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(_rate); if(phase==Phase.PRESALE){ assert(presale>=tokens); presale=presale.sub(tokens); assert(publicsale>=tokens); publicsale=publicsale.sub(tokens); } _forwardFunds(); _processPurchase(_beneficiary, tokens); if(investedAmountOf[msg.sender] == 0) { investorCount++; } if(whitelist[_beneficiary].stage==Stage.AML_SUCCESS){ afterWhtelistedBuy(_beneficiary); } } function buyTokens(address _beneficiary) public payable onlyWhileOpen{ require(_beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(_rate); if(phase==Phase.PRESALE){ assert(presale>=tokens); presale=presale.sub(tokens); assert(publicsale>=tokens); publicsale=publicsale.sub(tokens); } _forwardFunds(); _processPurchase(_beneficiary, tokens); if(investedAmountOf[msg.sender] == 0) { investorCount++; } if(whitelist[_beneficiary].stage==Stage.AML_SUCCESS){ afterWhtelistedBuy(_beneficiary); } } }else{ function buyTokens(address _beneficiary) public payable onlyWhileOpen{ require(_beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(_rate); if(phase==Phase.PRESALE){ assert(presale>=tokens); presale=presale.sub(tokens); assert(publicsale>=tokens); publicsale=publicsale.sub(tokens); } _forwardFunds(); _processPurchase(_beneficiary, tokens); if(investedAmountOf[msg.sender] == 0) { investorCount++; } if(whitelist[_beneficiary].stage==Stage.AML_SUCCESS){ afterWhtelistedBuy(_beneficiary); } } investedAmountOf[msg.sender] = investedAmountOf[msg.sender].add(weiAmount); function buyTokens(address _beneficiary) public payable onlyWhileOpen{ require(_beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(_rate); if(phase==Phase.PRESALE){ assert(presale>=tokens); presale=presale.sub(tokens); assert(publicsale>=tokens); publicsale=publicsale.sub(tokens); } _forwardFunds(); _processPurchase(_beneficiary, tokens); if(investedAmountOf[msg.sender] == 0) { investorCount++; } if(whitelist[_beneficiary].stage==Stage.AML_SUCCESS){ afterWhtelistedBuy(_beneficiary); } } function validPurchase() internal constant returns (bool) { bool minContribution = minContribAmount <= msg.value; return minContribution; } modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary].stage==Stage.AML_SUCCESS); _; } function addToWhitelist(address _beneficiary,uint256 _stage) external onlyOwner { require(_beneficiary != address(0)); if(_stage==1){ failedWhitelistForDebit(_beneficiary,_rate.mul(adminCharge)); adminChargeForDebit(_beneficiary,adminCharge); whitelist[_beneficiary].stage=Stage.KYC_FAILED; uint256 value=investedAmountOf[_beneficiary]; value=value.sub(adminCharge); investedAmountOf[_beneficiary]=value; whitelist[_beneficiary].stage=Stage.KYC_SUCCESS; whitelist[_beneficiary].stage=Stage.AML_FAILED; returnInvestoramount(_beneficiary,adminCharge); failedWhitelist(_beneficiary); investedAmountOf[_beneficiary]=0; whitelist[_beneficiary].stage=Stage.AML_SUCCESS; afterWhtelisted( _beneficiary); } } function addToWhitelist(address _beneficiary,uint256 _stage) external onlyOwner { require(_beneficiary != address(0)); if(_stage==1){ failedWhitelistForDebit(_beneficiary,_rate.mul(adminCharge)); adminChargeForDebit(_beneficiary,adminCharge); whitelist[_beneficiary].stage=Stage.KYC_FAILED; uint256 value=investedAmountOf[_beneficiary]; value=value.sub(adminCharge); investedAmountOf[_beneficiary]=value; whitelist[_beneficiary].stage=Stage.KYC_SUCCESS; whitelist[_beneficiary].stage=Stage.AML_FAILED; returnInvestoramount(_beneficiary,adminCharge); failedWhitelist(_beneficiary); investedAmountOf[_beneficiary]=0; whitelist[_beneficiary].stage=Stage.AML_SUCCESS; afterWhtelisted( _beneficiary); } } }else if(_stage==2){ }else if(_stage==3){ }else if(_stage==4){ function withdrawTokens() public isWhitelisted(msg.sender) { uint256 amount = _balances[msg.sender]; require(amount > 0); _deliverTokens(msg.sender, amount); _balances[msg.sender] = 0; } function changeEndtime(uint256 _endTime) public onlyOwner { require(_endTime > 0); _closingTime = _endTime; } function changeStarttime(uint256 _startTime) public onlyOwner { require(_startTime > 0); _openingTime = _startTime; } function changeStage(uint256 _rate) public onlyOwner { require(_rate>0); _rate=_rate; phase=Phase.PUBLICSALE; } function changeRate(uint256 _rate) public onlyOwner { require(_rate > 0); _rate = _rate; emit updateRate(_rate,block.timestamp); } function changeAdminCharge(uint256 _adminCharge) public onlyOwner { require(_adminCharge > 0); adminCharge=_adminCharge; } function transferTeamAndAdvisorsAndBountyAllocation (address to, uint256 tokens) public onlyOwner { require ( to != 0x0 && tokens > 0 && teamAndAdvisorsAndBountyAllocation >= tokens ); _deliverTokens(to, tokens); teamAndAdvisorsAndBountyAllocation = teamAndAdvisorsAndBountyAllocation.sub(tokens); } function transferTokensVested(address to, uint256 tokens) public onlyOwner { require ( to != 0x0 && tokens > 0 && tokensVested >= tokens ); _deliverTokens(to, tokens); tokensVested = tokensVested.sub(tokens); } function transferOperatingBudgetAllocation(address to, uint256 tokens) public onlyOwner { require ( to != 0x0 && tokens > 0 && operatingBudgetAllocation >= tokens ); _deliverTokens(to, tokens); operatingBudgetAllocation = operatingBudgetAllocation.sub(tokens); } }
12,581,172
[ 1, 12869, 2962, 30746, 578, 7224, 55, 287, 395, 410, 467, 3865, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 24420, 410, 39, 492, 2377, 5349, 353, 23925, 39, 492, 2377, 5349, 16, 6412, 492, 3032, 39, 492, 2377, 5349, 16, 3349, 8909, 39, 492, 2377, 5349, 288, 203, 203, 225, 19459, 1071, 6855, 31, 203, 7010, 225, 2254, 5034, 3238, 5381, 25429, 26835, 273, 1728, 636, 11890, 5034, 12, 2643, 1769, 203, 225, 2254, 5034, 1071, 389, 4963, 3088, 1283, 33, 22, 12648, 380, 25429, 26835, 31, 203, 225, 2254, 5034, 1071, 4075, 5349, 33, 25, 9449, 14, 25429, 26835, 31, 203, 225, 2254, 5034, 1071, 1071, 87, 5349, 33, 2499, 17877, 14, 25429, 26835, 31, 203, 225, 2254, 5034, 1071, 5927, 1876, 1871, 3516, 1383, 1876, 38, 592, 93, 17353, 273, 2593, 9449, 380, 25429, 26835, 31, 203, 225, 2254, 5034, 1071, 16929, 16124, 17353, 273, 1381, 9449, 380, 25429, 26835, 31, 203, 225, 2254, 5034, 1071, 2430, 58, 3149, 273, 9131, 9449, 380, 25429, 26835, 31, 203, 7010, 2792, 16531, 288, 47, 61, 39, 67, 11965, 16, 1475, 61, 39, 67, 12778, 16, 7982, 67, 11965, 16, 432, 1495, 67, 12778, 97, 3196, 203, 225, 2792, 19459, 288, 3670, 5233, 900, 16, 23295, 2053, 4596, 37, 900, 97, 203, 225, 1958, 26944, 95, 203, 4202, 16531, 225, 6009, 31, 203, 289, 203, 225, 2254, 5034, 1071, 3981, 17649, 33, 20, 18, 20, 2947, 225, 2437, 31, 203, 225, 2874, 12, 2867, 516, 26944, 13, 1071, 10734, 31, 203, 225, 871, 1089, 4727, 12, 11890, 5034, 1147, 4727, 16, 2254, 5034, 813, 1769, 203, 21281, 225, 2874, 261, 2867, 516, 2254, 2 ]
./full_match/11155111/0xbE3d97A00b4bE98A626a5c6DEc64f74F5F28da1f/sources/contracts/honeycast.sol
* @dev Returns the ceiling of the division of two numbers. This differs from standard division with '/' in that it rounds up instead of rounding down./ (a + b - 1) / b can overflow on addition, so we distribute.
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a == 0 ? 0 : (a - 1) / b + 1; }
3,815,355
[ 1, 1356, 326, 5898, 4973, 434, 326, 16536, 434, 2795, 5600, 18, 1220, 21944, 628, 4529, 16536, 598, 2023, 316, 716, 518, 21196, 731, 3560, 434, 13885, 2588, 18, 19, 261, 69, 397, 324, 300, 404, 13, 342, 324, 848, 9391, 603, 2719, 16, 1427, 732, 25722, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1377, 445, 8416, 7244, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 1850, 327, 279, 422, 374, 692, 374, 294, 261, 69, 300, 404, 13, 342, 324, 397, 404, 31, 203, 1377, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x9Cdfcc394206fb9A49BD8E1A1cc54067D6b83b44/sources/ELCON.sol
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "ELCON"; symbol = "ELCN"; decimals = 18; _totalSupply = 11000000.000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
5,248,065
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 2247, 2248, 14432, 203, 3639, 3273, 273, 315, 2247, 12821, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 4648, 9449, 18, 12648, 2787, 9449, 31, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0xeFA890da824c741FCB0BC5dB0C92BBB1433a8F87/sources/_openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
* @dev See {ERC721-_beforeTokenTransfer}./ Will only trigger during construction. Batch transferring (minting) is not available afterwards.
function _beforeTokenTransfer( address from, address to, uint256 firstTokenId, uint256 batchSize ) internal virtual override(ERC721) { super._beforeTokenTransfer(from, to, firstTokenId, batchSize); if (batchSize > 1) { revert("ERC721Enumerable: consecutive transfers not supported"); } uint256 tokenId = firstTokenId; if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } }
3,263,521
[ 1, 9704, 288, 654, 39, 27, 5340, 17, 67, 5771, 1345, 5912, 5496, 19, 9980, 1338, 3080, 4982, 16171, 18, 5982, 906, 74, 20245, 261, 81, 474, 310, 13, 353, 486, 2319, 23838, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1122, 1345, 548, 16, 203, 3639, 2254, 5034, 16494, 203, 565, 262, 2713, 5024, 3849, 12, 654, 39, 27, 5340, 13, 288, 203, 3639, 2240, 6315, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 1122, 1345, 548, 16, 16494, 1769, 203, 203, 3639, 309, 261, 5303, 1225, 405, 404, 13, 288, 203, 5411, 15226, 2932, 654, 39, 27, 5340, 3572, 25121, 30, 18221, 29375, 486, 3260, 8863, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 1147, 548, 273, 1122, 1345, 548, 31, 203, 203, 3639, 309, 261, 2080, 422, 1758, 12, 20, 3719, 288, 203, 5411, 389, 1289, 1345, 774, 1595, 5157, 21847, 12, 2316, 548, 1769, 203, 5411, 389, 4479, 1345, 1265, 5541, 21847, 12, 2080, 16, 1147, 548, 1769, 203, 3639, 289, 203, 3639, 309, 261, 869, 422, 1758, 12, 20, 3719, 288, 203, 5411, 389, 4479, 1345, 1265, 1595, 5157, 21847, 12, 2316, 548, 1769, 203, 5411, 389, 1289, 1345, 774, 5541, 21847, 12, 869, 16, 1147, 548, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/56/0xab84Cd8946F4589c2342B733C908cc84d2eCEd1e/sources/contracts/E-RON.sol
* @notice method which allows to removing the owner of the token @dev methods which are only callable by the owner will not be callable anymore @dev only callable by the owner @dev only callable if the token is not paused/
function renounceOwnership() public override onlyOwner whenNotPaused { super.renounceOwnership(); }
3,252,312
[ 1, 2039, 1492, 5360, 358, 9427, 326, 3410, 434, 326, 1147, 225, 2590, 1492, 854, 1338, 4140, 635, 326, 3410, 903, 486, 506, 4140, 16828, 225, 1338, 4140, 635, 326, 3410, 225, 1338, 4140, 309, 326, 1147, 353, 486, 17781, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1654, 8386, 5460, 12565, 1435, 1071, 3849, 1338, 5541, 1347, 1248, 28590, 288, 203, 565, 2240, 18, 1187, 8386, 5460, 12565, 5621, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; // added the experimental to try to return a struc in getAllUniversities import "openzeppelin-solidity/contracts/access/Roles.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /* To use with Remix: import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/access/Roles.sol"; import "github.com/OpenZeppelin/zeppelin-solidity/contracts/ownership/Ownable.sol"; */ contract ClassContract is Ownable { using Roles for Roles.Role; // We want to use the Roles library Roles.Role universityOwners; //Stores University owner Roles Roles.Role teachers; // Stores teacher Roles Roles.Role students; // Stores student Roles; uint public universityIdGenerator; mapping (uint => University) public universities; // Mapping to keep track of the Universities mapping (address => bool) studentFees; // Mapping to keep track if student has paid fees or not mapping (address => bool) grades; // Mapping to keep track of studets' grades struct University { string name; string description; string website; string phoneNumber; bool open; uint memberIdGenerator; mapping (address => UniversityMember) owners; mapping (address => UniversityMember) teachers; mapping (address => UniversityMember) students; } struct UniversityInfo { string name; string description; string website; string phoneNumber; bool open; } struct UniversityMember { string fullName; string email; uint id; bool active; } // Events event LogUniversityAdded(string name, string desc, uint universityId); // Modifiers modifier validAddress(address _address) { require(_address != address(0), "ADDRESS CANNOT BE THE ZERO ADDRESS"); _; } modifier ownerAtUniversity(uint universityId) { require((universities[universityId].owners[msg.sender].active == true), "DOES NOT BELONG TO THE UNIVERSITY OWNERS OR IS INACTIVE"); require(universityOwners.has(msg.sender), "DOES NOT HAVE UNIVERSITY OWNER ROLE"); _; } // Add Universities function addUniversity(string memory _name, string memory _description, string memory _website, string memory _phoneNumber) public onlyOwner returns (uint) { University memory newUniversity; newUniversity.name = _name; newUniversity.description = _description; newUniversity.website = _website; newUniversity.phoneNumber = _phoneNumber; newUniversity.open = true; universities[universityIdGenerator] = newUniversity; universityIdGenerator += 1; emit LogUniversityAdded(_name, _description, universityIdGenerator); return (universityIdGenerator - 1); } /* Roles and membership */ function addUniversityOwnerRoles(address _ownerAddr, string memory _fullName, string memory _email, uint universityId) public onlyOwner validAddress(_ownerAddr) { universityOwners.add(_ownerAddr); UniversityMember memory newUniversityMember; newUniversityMember.fullName = _fullName; newUniversityMember.email = _email; newUniversityMember.id = universities[universityId].memberIdGenerator; universities[universityId].owners[_ownerAddr] = newUniversityMember; universities[universityId].memberIdGenerator += 1; } function addUniversityMember(address _addr, string memory _name, string memory _email, uint _universityId, string memory _memberRole) public validAddress(_addr) ownerAtUniversity(_universityId) returns (bool) { UniversityMember memory newUniversityMember; newUniversityMember.fullName = _name; newUniversityMember.email = _email; newUniversityMember.id = universities[_universityId].memberIdGenerator; universities[_universityId].memberIdGenerator += 1; if (keccak256(abi.encodePacked(_memberRole)) == keccak256(abi.encodePacked("teacher"))) { teachers.add(_addr); universities[_universityId].teachers[_addr] = newUniversityMember; } else if (keccak256(abi.encodePacked(_memberRole)) == keccak256(abi.encodePacked("student"))) { students.add(_addr); universities[_universityId].students[_addr] = newUniversityMember; } return true; } function getAllUniversities() public view returns (UniversityInfo[] memory) { UniversityInfo[] memory results = new UniversityInfo[](universityIdGenerator); for (uint i = 0; i < universityIdGenerator; i++) { results[i].name = universities[universityIdGenerator].name; results[i].description = universities[universityIdGenerator].description; results[i].website = universities[universityIdGenerator].website; results[i].phoneNumber = universities[universityIdGenerator].phoneNumber; results[i].open = universities[universityIdGenerator].open; } return results; } function addTeacherRoles(address[] memory _teachers) public onlyOwner { for(uint i = 0; i < _teachers.length; i++) { teachers.add(_teachers[i]); } } function addStudentRoles(address[] memory _students) public onlyOwner { for(uint j = 0; j < _students.length; j++) { students.add(_students[j]); } } function areFeesEnough(uint amount) external pure returns (bool) { return amount >= 4 ether; } function payFees() public payable { require(students.has(msg.sender), "DOES NOT HAVE STUDENT ROLE"); if(this.areFeesEnough(msg.value)) { address(uint160(owner())).transfer(msg.value); // Cast to address(uint160) to make address payable studentFees[msg.sender] = true; } } function gradeStudent(address student, bool grade) public { require(teachers.has(msg.sender), "DOES NOT HAVE TEACHER ROLE"); require(students.has(student), "ADDRESS PROVIDED IS NOT A STUDENT"); grades[student] = grade; } function hasPaidFees(address account) validAddress(account) public view returns (bool) { require(students.has(account),"Provided account is not a student"); return studentFees[account]; } function terminateClass() onlyOwner public { selfdestruct(msg.sender); } function getBalance(address account) public view returns (uint) { return account.balance; } }
Mapping to keep track if student has paid fees or not
mapping (address => bool) studentFees;
6,410,013
[ 1, 3233, 358, 3455, 3298, 309, 18110, 711, 30591, 1656, 281, 578, 486, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 1426, 13, 18110, 2954, 281, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.1.1 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File contracts/utils/DecimalMath.sol pragma solidity 0.6.9; /// @dev Implements simple fixed point math add, sub, mul and div operations. /// @author Alberto Cuesta Cañada library DecimalMath { using SafeMath for uint256; /// @dev Returns 1 in the fixed point representation, with `decimals` decimals. function unit(uint8 decimals) internal pure returns (uint256) { return 10**uint256(decimals); } /// @dev Adds x and y, assuming they are both fixed point with 18 decimals. function addd(uint256 x, uint256 y) internal pure returns (uint256) { return x.add(y); } /// @dev Subtracts y from x, assuming they are both fixed point with 18 decimals. function subd(uint256 x, uint256 y) internal pure returns (uint256) { return x.sub(y); } /// @dev Multiplies x and y, assuming they are both fixed point with 18 digits. function muld(uint256 x, uint256 y) internal pure returns (uint256) { return muld(x, y, 18); } /// @dev Multiplies x and y, assuming they are both fixed point with `decimals` digits. function muld( uint256 x, uint256 y, uint8 decimals ) internal pure returns (uint256) { return x.mul(y).div(unit(decimals)); } /// @dev Divides x between y, assuming they are both fixed point with 18 digits. function divd(uint256 x, uint256 y) internal pure returns (uint256) { return divd(x, y, 18); } /// @dev Divides x between y, assuming they are both fixed point with `decimals` digits. function divd( uint256 x, uint256 y, uint8 decimals ) internal pure returns (uint256) { return x.mul(unit(decimals)).div(y); } } // File contracts/utils/Decimal.sol pragma solidity 0.6.9; library Decimal { using DecimalMath for uint256; using SafeMath for uint256; struct decimal { uint256 d; } function zero() internal pure returns (decimal memory) { return decimal(0); } function one() internal pure returns (decimal memory) { return decimal(DecimalMath.unit(18)); } function toUint(decimal memory x) internal pure returns (uint256) { return x.d; } function modD(decimal memory x, decimal memory y) internal pure returns (decimal memory) { return decimal(x.d % y.d); } function cmp(decimal memory x, decimal memory y) internal pure returns (int8) { if (x.d > y.d) { return 1; } else if (x.d < y.d) { return -1; } return 0; } /// @dev add two decimals function addD(decimal memory x, decimal memory y) internal pure returns (decimal memory) { decimal memory t; t.d = x.d.add(y.d); return t; } /// @dev subtract two decimals function subD(decimal memory x, decimal memory y) internal pure returns (decimal memory) { decimal memory t; t.d = x.d.sub(y.d); return t; } /// @dev multiple two decimals function mulD(decimal memory x, decimal memory y) internal pure returns (decimal memory) { decimal memory t; t.d = x.d.muld(y.d); return t; } /// @dev multiple a decimal by a uint256 function mulScalar(decimal memory x, uint256 y) internal pure returns (decimal memory) { decimal memory t; t.d = x.d.mul(y); return t; } /// @dev divide two decimals function divD(decimal memory x, decimal memory y) internal pure returns (decimal memory) { decimal memory t; t.d = x.d.divd(y.d); return t; } /// @dev divide a decimal by a uint256 function divScalar(decimal memory x, uint256 y) internal pure returns (decimal memory) { decimal memory t; t.d = x.d.div(y); return t; } } // File @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // File contracts/utils/SignedDecimalMath.sol pragma solidity 0.6.9; /// @dev Implements simple signed fixed point math add, sub, mul and div operations. library SignedDecimalMath { using SignedSafeMath for int256; /// @dev Returns 1 in the fixed point representation, with `decimals` decimals. function unit(uint8 decimals) internal pure returns (int256) { return int256(10**uint256(decimals)); } /// @dev Adds x and y, assuming they are both fixed point with 18 decimals. function addd(int256 x, int256 y) internal pure returns (int256) { return x.add(y); } /// @dev Subtracts y from x, assuming they are both fixed point with 18 decimals. function subd(int256 x, int256 y) internal pure returns (int256) { return x.sub(y); } /// @dev Multiplies x and y, assuming they are both fixed point with 18 digits. function muld(int256 x, int256 y) internal pure returns (int256) { return muld(x, y, 18); } /// @dev Multiplies x and y, assuming they are both fixed point with `decimals` digits. function muld( int256 x, int256 y, uint8 decimals ) internal pure returns (int256) { return x.mul(y).div(unit(decimals)); } /// @dev Divides x between y, assuming they are both fixed point with 18 digits. function divd(int256 x, int256 y) internal pure returns (int256) { return divd(x, y, 18); } /// @dev Divides x between y, assuming they are both fixed point with `decimals` digits. function divd( int256 x, int256 y, uint8 decimals ) internal pure returns (int256) { return x.mul(unit(decimals)).div(y); } } // File contracts/utils/SignedDecimal.sol pragma solidity 0.6.9; library SignedDecimal { using SignedDecimalMath for int256; using SignedSafeMath for int256; struct signedDecimal { int256 d; } function zero() internal pure returns (signedDecimal memory) { return signedDecimal(0); } function toInt(signedDecimal memory x) internal pure returns (int256) { return x.d; } function isNegative(signedDecimal memory x) internal pure returns (bool) { if (x.d < 0) { return true; } return false; } function abs(signedDecimal memory x) internal pure returns (Decimal.decimal memory) { Decimal.decimal memory t; if (x.d < 0) { t.d = uint256(0 - x.d); } else { t.d = uint256(x.d); } return t; } /// @dev add two decimals function addD(signedDecimal memory x, signedDecimal memory y) internal pure returns (signedDecimal memory) { signedDecimal memory t; t.d = x.d.add(y.d); return t; } /// @dev subtract two decimals function subD(signedDecimal memory x, signedDecimal memory y) internal pure returns (signedDecimal memory) { signedDecimal memory t; t.d = x.d.sub(y.d); return t; } /// @dev multiple two decimals function mulD(signedDecimal memory x, signedDecimal memory y) internal pure returns (signedDecimal memory) { signedDecimal memory t; t.d = x.d.muld(y.d); return t; } /// @dev multiple a signedDecimal by a int256 function mulScalar(signedDecimal memory x, int256 y) internal pure returns (signedDecimal memory) { signedDecimal memory t; t.d = x.d.mul(y); return t; } /// @dev divide two decimals function divD(signedDecimal memory x, signedDecimal memory y) internal pure returns (signedDecimal memory) { signedDecimal memory t; t.d = x.d.divd(y.d); return t; } /// @dev divide a signedDecimal by a int256 function divScalar(signedDecimal memory x, int256 y) internal pure returns (signedDecimal memory) { signedDecimal memory t; t.d = x.d.div(y); return t; } } // File contracts/utils/DecimalERC20.sol pragma solidity 0.6.9; abstract contract DecimalERC20 { using SafeMath for uint256; using Decimal for Decimal.decimal; mapping(address => uint256) private decimalMap; //◥◤◥◤◥◤◥◤◥◤◥◤◥◤◥◤ add state variables below ◥◤◥◤◥◤◥◤◥◤◥◤◥◤◥◤// //◢◣◢◣◢◣◢◣◢◣◢◣◢◣◢◣ add state variables above ◢◣◢◣◢◣◢◣◢◣◢◣◢◣◢◣// uint256[50] private __gap; // // INTERNAL functions // // CAUTION: do not input _from == _to s.t. this function will always fail function _transfer( IERC20 _token, address _to, Decimal.decimal memory _value ) internal { _updateDecimal(address(_token)); Decimal.decimal memory balanceBefore = _balanceOf(_token, _to); uint256 roundedDownValue = _toUint(_token, _value); // solhint-disable avoid-low-level-calls (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(_token.transfer.selector, _to, roundedDownValue) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "DecimalERC20: transfer failed"); _validateBalance(_token, _to, roundedDownValue, balanceBefore); } function _transferFrom( IERC20 _token, address _from, address _to, Decimal.decimal memory _value ) internal { _updateDecimal(address(_token)); Decimal.decimal memory balanceBefore = _balanceOf(_token, _to); uint256 roundedDownValue = _toUint(_token, _value); // solhint-disable avoid-low-level-calls (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(_token.transferFrom.selector, _from, _to, roundedDownValue) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "DecimalERC20: transferFrom failed"); _validateBalance(_token, _to, roundedDownValue, balanceBefore); } function _approve( IERC20 _token, address _spender, Decimal.decimal memory _value ) internal { _updateDecimal(address(_token)); // to be compatible with some erc20 tokens like USDT __approve(_token, _spender, Decimal.zero()); __approve(_token, _spender, _value); } // // VIEW // function _allowance( IERC20 _token, address _owner, address _spender ) internal view returns (Decimal.decimal memory) { return _toDecimal(_token, _token.allowance(_owner, _spender)); } function _balanceOf(IERC20 _token, address _owner) internal view returns (Decimal.decimal memory) { return _toDecimal(_token, _token.balanceOf(_owner)); } function _totalSupply(IERC20 _token) internal view returns (Decimal.decimal memory) { return _toDecimal(_token, _token.totalSupply()); } function _toDecimal(IERC20 _token, uint256 _number) internal view returns (Decimal.decimal memory) { uint256 tokenDecimals = _getTokenDecimals(address(_token)); if (tokenDecimals >= 18) { return Decimal.decimal(_number.div(10**(tokenDecimals.sub(18)))); } return Decimal.decimal(_number.mul(10**(uint256(18).sub(tokenDecimals)))); } function _toUint(IERC20 _token, Decimal.decimal memory _decimal) internal view returns (uint256) { uint256 tokenDecimals = _getTokenDecimals(address(_token)); if (tokenDecimals >= 18) { return _decimal.toUint().mul(10**(tokenDecimals.sub(18))); } return _decimal.toUint().div(10**(uint256(18).sub(tokenDecimals))); } function _getTokenDecimals(address _token) internal view returns (uint256) { uint256 tokenDecimals = decimalMap[_token]; if (tokenDecimals == 0) { (bool success, bytes memory data) = _token.staticcall(abi.encodeWithSignature("decimals()")); require(success && data.length != 0, "DecimalERC20: get decimals failed"); tokenDecimals = abi.decode(data, (uint256)); } return tokenDecimals; } // // PRIVATE // function _updateDecimal(address _token) private { uint256 tokenDecimals = _getTokenDecimals(_token); if (decimalMap[_token] != tokenDecimals) { decimalMap[_token] = tokenDecimals; } } function __approve( IERC20 _token, address _spender, Decimal.decimal memory _value ) private { // solhint-disable avoid-low-level-calls (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(_token.approve.selector, _spender, _toUint(_token, _value)) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "DecimalERC20: approve failed"); } // To prevent from deflationary token, check receiver's balance is as expectation. function _validateBalance( IERC20 _token, address _to, uint256 _roundedDownValue, Decimal.decimal memory _balanceBefore ) private view { require( _balanceOf(_token, _to).cmp(_balanceBefore.addD(_toDecimal(_token, _roundedDownValue))) == 0, "DecimalERC20: balance inconsistent" ); } } // File contracts/interface/IAmm.sol pragma solidity 0.6.9; pragma experimental ABIEncoderV2; interface IAmm { /** * @notice asset direction, used in getInputPrice, getOutputPrice, swapInput and swapOutput * @param ADD_TO_AMM add asset to Amm * @param REMOVE_FROM_AMM remove asset from Amm */ enum Dir { ADD_TO_AMM, REMOVE_FROM_AMM } struct LiquidityChangedSnapshot { SignedDecimal.signedDecimal cumulativeNotional; // the base/quote reserve of amm right before liquidity changed Decimal.decimal quoteAssetReserve; Decimal.decimal baseAssetReserve; // total position size owned by amm after last snapshot taken // `totalPositionSize` = currentBaseAssetReserve - lastLiquidityChangedHistoryItem.baseAssetReserve + prevTotalPositionSize SignedDecimal.signedDecimal totalPositionSize; } function reserveSnapshots(uint256) external view returns (ReserveSnapshot memory); struct ReserveSnapshot { Decimal.decimal quoteAssetReserve; Decimal.decimal baseAssetReserve; uint256 timestamp; uint256 blockNumber; } function swapInput( Dir _dir, Decimal.decimal calldata _quoteAssetAmount, Decimal.decimal calldata _baseAssetAmountLimit ) external returns (Decimal.decimal memory); function swapOutput( Dir _dir, Decimal.decimal calldata _baseAssetAmount, Decimal.decimal calldata _quoteAssetAmountLimit, bool _skipFluctuationCheck ) external returns (Decimal.decimal memory); function migrateLiquidity(Decimal.decimal calldata _liquidityMultiplier, Decimal.decimal calldata _priceLimitRatio) external; function shutdown() external; function settleFunding() external returns (SignedDecimal.signedDecimal memory); function calcFee(Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory, Decimal.decimal memory); // // VIEW // function calcBaseAssetAfterLiquidityMigration( SignedDecimal.signedDecimal memory _baseAssetAmount, Decimal.decimal memory _fromQuoteReserve, Decimal.decimal memory _fromBaseReserve ) external view returns (SignedDecimal.signedDecimal memory); function getInputTwap(Dir _dir, Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory); function getOutputTwap(Dir _dir, Decimal.decimal calldata _baseAssetAmount) external view returns (Decimal.decimal memory); function getInputPrice(Dir _dir, Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory); function getOutputPrice(Dir _dir, Decimal.decimal calldata _baseAssetAmount) external view returns (Decimal.decimal memory); function getInputPriceWithReserves( Dir _dir, Decimal.decimal memory _quoteAssetAmount, Decimal.decimal memory _quoteAssetPoolAmount, Decimal.decimal memory _baseAssetPoolAmount ) external pure returns (Decimal.decimal memory); function getOutputPriceWithReserves( Dir _dir, Decimal.decimal memory _baseAssetAmount, Decimal.decimal memory _quoteAssetPoolAmount, Decimal.decimal memory _baseAssetPoolAmount ) external pure returns (Decimal.decimal memory); function getSpotPrice() external view returns (Decimal.decimal memory); function getLiquidityHistoryLength() external view returns (uint256); // overridden by state variable function quoteAsset() external view returns (IERC20); function open() external view returns (bool); // can not be overridden by state variable due to type `Deciaml.decimal` function getSettlementPrice() external view returns (Decimal.decimal memory); function getBaseAssetDeltaThisFundingPeriod() external view returns (SignedDecimal.signedDecimal memory); function getCumulativeNotional() external view returns (SignedDecimal.signedDecimal memory); function getMaxHoldingBaseAsset() external view returns (Decimal.decimal memory); function getOpenInterestNotionalCap() external view returns (Decimal.decimal memory); enum TwapCalcOption { RESERVE_ASSET, INPUT_ASSET } enum QuoteAssetDir { QUOTE_IN, QUOTE_OUT } struct TwapInputAsset { Dir dir; Decimal.decimal assetAmount; QuoteAssetDir inOrOut; } struct TwapPriceCalcParams { TwapCalcOption opt; uint256 snapshotIndex; TwapInputAsset asset; } function getSnapshotLen() external view returns (uint256); function getPriceWithSpecificSnapshot(TwapPriceCalcParams memory params) external view returns (Decimal.decimal memory); function getLiquidityChangedSnapshots(uint256 i) external view returns (LiquidityChangedSnapshot memory); } // File contracts/interface/IInsuranceFund.sol pragma solidity 0.6.9; interface IInsuranceFund { function withdraw(IERC20 _quoteToken, Decimal.decimal calldata _amount) external; function isExistedAmm(IAmm _amm) external view returns (bool); function getAllAmms() external view returns (IAmm[] memory); } // File contracts/interface/ISmartWallet.sol pragma solidity 0.6.9; interface ISmartWallet { function executeCall( address target, bytes calldata callData, uint256 value ) external payable returns (bytes memory); function initialize(address _lob, address _trader) external; function executeMarketOrder( IAmm _asset, SignedDecimal.signedDecimal memory _orderSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage ) external; function executeClosePosition( IAmm _asset, Decimal.decimal memory _slippage ) external; function executeOrder( uint order_id ) external; } // File contracts/interface/ISmartWalletFactory.sol pragma solidity 0.6.9; interface ISmartWalletFactory { function getSmartWallet( address ) external returns (address); } // File contracts/LimitOrderBook.sol pragma solidity 0.6.9; contract LimitOrderBook is Ownable, DecimalERC20{ using Decimal for Decimal.decimal; using SignedDecimal for SignedDecimal.signedDecimal; /* * EVENTS */ event OrderCreated(address indexed trader, uint order_id); event OrderFilled(address indexed trader, uint order_id); event OrderChanged(address indexed trader, uint order_id); event OrderCancelled(address indexed trader, uint order_id); event TrailingOrderCreated(uint order_id, uint snapshotIndex); event TrailingOrderFilled(uint order_id); event TrailingOrderChanged(uint order_id); event TrailingOrderCancelled(uint order_id); event ContractPoked(uint order_id, uint reserve_index); /* * ENUMS */ /* * Order types that the user is able to create. * Note that market orders are actually executed instantly on clearing house * therefore there should never actually be a market order in the LOB */ enum OrderType { MARKET, LIMIT, STOPMARKET, STOPLIMIT, TRAILINGSTOPMARKET, TRAILINGSTOPLIMIT} /* * STRUCTS */ /* * @notice Every order is stored within a limit order struct (regardless of * the type of order) * @param asset is the address of the perp AMM for that particular asset * @param trader is the user that created the order - note that the order will * actually be executed on their smart wallet (as stored in the factory) * @param orderType represents the order type * @param reduceOnly whether the order is reduceOnly or not. A reduce only order * will never increase the size of a position and will either reduce the size * or close the position. * @param stillValid whether the order can be executed. There are two conditions * where an order is no longer valid: the trader cancels the order, or the * order gets executed (to prevent double spend) * @param expiry is the blockTimestamp when this order expires. If this value * is 0 then the order will not expire * @param stopPrice is the trigger price for any stop order. A stop BUY can * only be executed above this price, whilst a stop SELL is executed below * @param limitPrice is the trigger price for any limit order. a limit BUY can * only be executed below this price, whilst a limit SELL is executed above * @param orderSize is the size of the order (denominated in the base asset) * @param collateral is the amount of collateral or margin that will be used * for this order. This amount is guaranteed ie an order with 300 USDC will * always use 300 USDC. * @param leverage is the maximum amount of leverage that the trader will accept. * @param slippage is the minimum amount of ASSET that the user will accept. * The trader will usually achieve the amount specified by orderSize. This * parameter allows the user to specify their tolerance to price impact / frontrunning * @param tipFee is the fee that goes to the keeper for executing the order. * This fee is taken when the order is created, and paid out when executing. */ struct LimitOrder { address asset; address trader; bool reduceOnly; bool stillValid; OrderType orderType; uint256 expiry; Decimal.decimal stopPrice; Decimal.decimal limitPrice; SignedDecimal.signedDecimal orderSize; Decimal.decimal collateral; Decimal.decimal leverage; Decimal.decimal slippage; Decimal.decimal tipFee; } LimitOrder[] public orders; /* * @notice Additional information is stored for trailing orders below * @param witnessPrice is either the highest or lowest price witnessed by an order. * The trailing stop/limit trigger prices are calculated from this value. * @param trail is the absolute difference between the witnessPrice and stop price * @param trailPct is a percentage (number between 0 and 1) that is used to * calculate a relative stop price * @param gap is the absolute difference between the witnessPrice and limit price * @param gapPct is a percentage (number between 0 and 1) that is used to * calculate a relative limit price * @param usePct whether the trigger prices are calculated relatively or absolutely * @param snapshotCreated the index of reserveSnapshotted on AMM contract when * the trailing order was created * @param snapshotLastUpdated the index when the witness price was last updated * @param snapshotTimestamp the timestamp when the order was last updated * @param lastUpdatedKeeper the last address that successfully updated the witness * price. This address will be paid on execution of the order */ struct TrailingOrderData { Decimal.decimal witnessPrice; Decimal.decimal trail; Decimal.decimal trailPct; Decimal.decimal gap; Decimal.decimal gapPct; uint256 snapshotCreated; uint256 snapshotLastUpdated; uint256 snapshotTimestamp; address lastUpdatedKeeper; bool usePct; } /* Utilising mapping here to ensure order_id is the same for LimitOrder struct and TrailingOrderData struct */ mapping (uint256 => TrailingOrderData) public trailingOrders; /* * VARIABLES */ /* All smart wallets will be deployed by the factory - this allows you to get the contract address of the smart wallet for any trader */ ISmartWalletFactory public factory; /* Other smart contracts that we interact with */ address constant USDC = 0xDDAfbb505ad214D7b80b1f830fcCc89B60fb7A83; address constant INSURANCEFUND = 0x8C29F6F7fc1999aB84b476952E986F974Acb3824; /* Trailing orders can only be updated every 10 minutes - this is to prevent the need for the contract to be poked as frequently. 10 minutes has been chosen as the 15 minute TWAP is used by PERP for liquidations.*/ uint256 public pokeContractDelay = 10 minutes; /* The minimum fee that needs to be attached to an order for it to be executed by a keeper. This can be adjusted at a later stage. This is to prevent spam attacks on the network */ Decimal.decimal public minimumTipFee; /* * FUNCTIONS TO ADD ORDERS */ /* * @notice This function will create a limit order and store it within the contract. * Please see documentation for _createOrder() */ function addLimitOrder( IAmm _asset, Decimal.decimal memory _limitPrice, SignedDecimal.signedDecimal memory _positionSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage, Decimal.decimal memory _tipFee, bool _reduceOnly, uint256 _expiry ) external { requireNonZeroInput(_limitPrice, "Limit cannot be zero"); _createOrder(_asset, OrderType.LIMIT, Decimal.zero(), _limitPrice, _positionSize, _collateral, _leverage, _slippage, _tipFee, _reduceOnly, _expiry); } /* * @notice This function will create a stop market order and store it within the contract. * Please see documentation for _createOrder() */ function addStopOrder( IAmm _asset, Decimal.decimal memory _stopPrice, SignedDecimal.signedDecimal memory _positionSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage, Decimal.decimal memory _tipFee, bool _reduceOnly, uint256 _expiry ) external { requireNonZeroInput(_stopPrice, "Stop cannot be zero"); _createOrder(_asset, OrderType.STOPMARKET, _stopPrice, Decimal.zero(), _positionSize, _collateral, _leverage, _slippage, _tipFee, _reduceOnly, _expiry); } /* * @notice This function will create a stop limit order and store it within the contract. * Please see documentation for _createOrder() */ function addStopLimitOrder( IAmm _asset, Decimal.decimal memory _stopPrice, Decimal.decimal memory _limitPrice, SignedDecimal.signedDecimal memory _positionSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage, Decimal.decimal memory _tipFee, bool _reduceOnly, uint256 _expiry ) external { requireNonZeroInput(_limitPrice, "Limit cannot be zero"); requireNonZeroInput(_stopPrice, "Stop cannot be zero"); _createOrder(_asset, OrderType.STOPLIMIT, _stopPrice, _limitPrice, _positionSize, _collateral, _leverage, _slippage, _tipFee, _reduceOnly, _expiry); } /* * @notice This function will create a trailing stop order and store it within the contract. * Please see documentation for _createOrder() and _createTrailingOrder() * Abs is absolute value */ function addTrailingStopMarketOrderAbs( IAmm _asset, Decimal.decimal memory _trail, SignedDecimal.signedDecimal memory _positionSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _tipFee, bool _reduceOnly, uint256 _expiry ) external { requireNonZeroInput(_trail, "Trail cannot be zero"); _createOrder(_asset, OrderType.TRAILINGSTOPMARKET, Decimal.zero(), Decimal.zero(), _positionSize, _collateral, _leverage, Decimal.zero(), _tipFee, _reduceOnly, _expiry); _createTrailingOrder(_asset, _trail, Decimal.zero(), false); } /* * @notice This function will create a trailing stop order and store it within the contract. * Please see documentation for _createOrder() and _createTrailingOrder() * Pct is relative value (will calculate trigger price as percentage) */ function addTrailingStopMarketOrderPct( IAmm _asset, Decimal.decimal memory _trailPct, SignedDecimal.signedDecimal memory _positionSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _tipFee, bool _reduceOnly, uint256 _expiry ) external { requireNonZeroInput(_trailPct, "Trail cannot be zero"); _createOrder(_asset, OrderType.TRAILINGSTOPMARKET, Decimal.zero(), Decimal.zero(), _positionSize, _collateral, _leverage, Decimal.zero(), _tipFee, _reduceOnly, _expiry); _createTrailingOrder(_asset, _trailPct, Decimal.zero(), true); } /* * @notice This function will create a trailing stop limit order and store it within the contract. * Please see documentation for _createOrder() and _createTrailingOrder() * Abs is absolute value */ function addTrailingStopLimitOrderAbs( IAmm _asset, Decimal.decimal memory _trail, Decimal.decimal memory _gap, SignedDecimal.signedDecimal memory _positionSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage, Decimal.decimal memory _tipFee, bool _reduceOnly, uint256 _expiry ) external { requireNonZeroInput(_trail, "Trail cannot be zero"); requireNonZeroInput(_gap, "Gap cannot be zero"); _createOrder(_asset, OrderType.TRAILINGSTOPLIMIT, Decimal.zero(), Decimal.zero(), _positionSize, _collateral, _leverage, _slippage, _tipFee, _reduceOnly, _expiry); _createTrailingOrder(_asset, _trail, _gap, false); } /* * @notice This function will create a trailing stop limit order and store it within the contract. * Please see documentation for _createOrder() and _createTrailingOrder() * Pct is relative value (will calculate trigger price as percentage) */ function addTrailingStopLimitOrderPct( IAmm _asset, Decimal.decimal memory _trailPct, Decimal.decimal memory _gapPct, SignedDecimal.signedDecimal memory _positionSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage, Decimal.decimal memory _tipFee, bool _reduceOnly, uint256 _expiry ) external { requireNonZeroInput(_trailPct, "Trail cannot be zero"); requireNonZeroInput(_gapPct, "Gap cannot be zero"); _createOrder(_asset, OrderType.TRAILINGSTOPLIMIT, Decimal.zero(), Decimal.zero(), _positionSize, _collateral, _leverage, _slippage, _tipFee, _reduceOnly, _expiry); _createTrailingOrder(_asset, _trailPct, _gapPct, true); } /* * @notice Will create an advanced order and store it within the contract * @param _asset the AMM address for the asset being traded * @param _orderType the type of order (as enum) * @param _stopPrice the STOP trigger price * @param _limitPrice the LIMIT trigger price * @param _positionSize the size of the order in base asset * @param _collateral the amount of margin/collateral that will be used for order * @param _leverage the maximum leverage acceptable for trade * @param _slippage the minimum amount of base asset that the trader will accept * This is subtly different to _positionSize. Let us assume that the trader * has created an order to buy 1 BTC below 50K. The price of bitcoin hits * 49,980 and so an order gets executed. His actual execution price may be * 50,500 (due to price impact). He can adjust the slippage parameter to * decide whether he wants the transaction to be executed at this price or not. * If slippage is set to 0, then any price is accepted. * @param _tipFee is the fee that will go to the keeper that executes the order. * This fee is taken as soon as the order is created. * @param _reduceOnly whether the order is reduceonly or not * @param _expiry when the order expires (block timestamp). If this variable is * 0 then it will never expire. */ function _createOrder( IAmm _asset, OrderType _orderType, Decimal.decimal memory _stopPrice, Decimal.decimal memory _limitPrice, SignedDecimal.signedDecimal memory _positionSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage, Decimal.decimal memory _tipFee, bool _reduceOnly, uint256 _expiry ) internal { //Check expiry parameter require(((_expiry == 0 ) || (block.timestamp<_expiry)), 'Event will expire in past'); //Check whether fee is sufficient require(_tipFee.cmp(minimumTipFee) >= 0, 'Just the tip! Tip is below minimum tip fee'); //Check on the smart wallet factory whether this trader has a smart wallet address _smartWallet = factory.getSmartWallet(msg.sender); require(_smartWallet != address(0), 'Need smart wallet'); //Need to make sure the asset is actually a PERP asset require(IInsuranceFund(INSURANCEFUND).isExistedAmm(IAmm(_asset)), "amm not found"); //Sanity checks requireNonZeroInput(_positionSize.abs(), "Cannot do empty order"); require(_slippage.cmp(Decimal.one()) == -1, "Slippage must be percentage"); requireNonZeroInput(_collateral, "Cannot spend 0 collateral"); require(_leverage.cmp(Decimal.one()) != -1, "Minimum 1x leverage"); //Take fee from user - user needs to approve this contract to spend their USDC first _transferFrom(IERC20(USDC), _smartWallet, address(this), _tipFee); //Emit event on order creation emit OrderCreated(msg.sender,orders.length); //Add values to array orders.push(LimitOrder({ asset: address(_asset), trader: msg.sender, orderType: _orderType, stopPrice: _stopPrice, limitPrice: _limitPrice, orderSize: _positionSize, collateral: _collateral, leverage: _leverage, slippage: _slippage, tipFee: _tipFee, reduceOnly: _reduceOnly, stillValid: true, expiry: _expiry })); } /* * @notice Will create a trailing order * @param _trail variable used to calculate the stop trigger price for a trailing * order. Note that this will either be an absolute value or a percentage (0-1) * @param _gap variable used to calculate the limit trigger price for a trailing * order. Note that this will either be an absolute value or a percentage (0-1) * @param _usePct whether or not you are calculating using absolute or relative */ function _createTrailingOrder( IAmm _asset, Decimal.decimal memory _trail, Decimal.decimal memory _gap, bool _usePct ) internal { //Get the current index of AMM ReserveSnapshotted uint _currSnapshot = IAmm(_asset).getSnapshotLen()-1; uint _thisOrderId = orders.length-1; //Get the current spot price of the asset Decimal.decimal memory _initPrice = IAmm(_asset).getSpotPrice(); if(_usePct) { //Ensure that the percentages satisfy 0<=PCT<1 require(_trail.cmp(Decimal.one()) == -1, 'Invalid trail percent'); require(_gap.cmp(Decimal.one()) == -1, 'Invalid gap percent'); //Create trailing order struct trailingOrders[_thisOrderId] = TrailingOrderData({ witnessPrice: _initPrice, trail: Decimal.zero(), trailPct: _trail, gap: Decimal.zero(), gapPct: _gap, usePct: true, snapshotCreated: _currSnapshot, snapshotLastUpdated: _currSnapshot, snapshotTimestamp: block.timestamp, lastUpdatedKeeper: address(0) }); } else { //Create trailing order struct trailingOrders[_thisOrderId] = TrailingOrderData({ witnessPrice: _initPrice, trail: _trail, trailPct: Decimal.zero(), gap: _gap, gapPct: Decimal.zero(), usePct: false, snapshotCreated: _currSnapshot, snapshotLastUpdated: _currSnapshot, snapshotTimestamp: block.timestamp, lastUpdatedKeeper: address(0) }); } //Need to calculate stop and limit prices from the witness Price _updateTrailingPrice(_thisOrderId); //Emit event emit TrailingOrderCreated(_thisOrderId, _currSnapshot); } /* * FUNCTIONS TO INTERACT WITH ORDERS (MODIFY/DELETE/ETC) */ /* * @notice allows a user to modify their orders after they have been submitted. * Once an order has been submitted, it is not possible to change the ASSET, * or the TIPFEE, or the ORDERTYPE. The other parameters are similar to those * described above. * Note: there is a separate function to modify trailing orders */ function modifyOrder( uint order_id, Decimal.decimal memory _stopPrice, Decimal.decimal memory _limitPrice, SignedDecimal.signedDecimal memory _orderSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage, bool _reduceOnly, uint _expiry) external onlyMyOrder(order_id) onlyValidOrder(order_id){ //Ensure that you don't set an order that expires in the past require(((_expiry == 0 ) || (block.timestamp<_expiry)), 'Event will expire in past'); //Can only modify non-trailing orders with this function OrderType _thisOrderType = orders[order_id].orderType; require(_thisOrderType == OrderType.LIMIT || _thisOrderType == OrderType.STOPMARKET || _thisOrderType == OrderType.STOPLIMIT, "Can only modify stop/limit orders"); //Sanity checks requireNonZeroInput(_orderSize.abs(), "Cannot do empty order"); requireNonZeroInput(_collateral, "Cannot spend 0 collateral"); require(_leverage.cmp(Decimal.one()) != -1, "Minimum 1x leverage"); //Update parameters orders[order_id].stopPrice = _stopPrice; orders[order_id].limitPrice = _limitPrice; orders[order_id].orderSize = _orderSize; orders[order_id].collateral = _collateral; orders[order_id].leverage = _leverage; orders[order_id].slippage = _slippage; orders[order_id].reduceOnly = _reduceOnly; orders[order_id].expiry = _expiry; //Emit event emit OrderChanged(orders[order_id].trader, order_id); } /* * @notice allows a user to modify their orders after they have been submitted. * Once an order has been submitted, it is not possible to change the ASSET, * or the TIPFEE, or the ORDERTYPE. The other parameters are similar to those * described above. * Note: this function can only modify trailing orders. It is not possible to * change the type of trailing order (eg relative vs absolute) */ function modifyTrailingOrder( uint order_id, Decimal.decimal memory _newStop, Decimal.decimal memory _newLimit, SignedDecimal.signedDecimal memory _orderSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage, bool _reduceOnly, uint _expiry) external onlyMyOrder(order_id) onlyValidOrder(order_id){ //Check order doesn't expire in the past require(((_expiry == 0 ) || (block.timestamp<_expiry)), 'Event will expire in past'); //Can only modify trailing orders with this function OrderType _thisOrderType = orders[order_id].orderType; require(_thisOrderType == OrderType.TRAILINGSTOPMARKET || _thisOrderType == OrderType.TRAILINGSTOPLIMIT, "Can only modify trailing orders"); //Sanity checks requireNonZeroInput(_orderSize.abs(), "Cannot do empty order"); requireNonZeroInput(_collateral, "Cannot spend 0 collateral"); require(_leverage.cmp(Decimal.one()) != -1, "Minimum 1x leverage"); //Update parameters orders[order_id].orderSize = _orderSize; orders[order_id].collateral = _collateral; orders[order_id].leverage = _leverage; orders[order_id].slippage = _slippage; orders[order_id].reduceOnly = _reduceOnly; orders[order_id].expiry = _expiry; if(trailingOrders[order_id].usePct) { //Ensure that percentage satisfies 0<=PCT<1 require(_newStop.cmp(Decimal.one()) == -1, 'Invalid trail percent'); require(_newLimit.cmp(Decimal.one()) == -1, 'Invalid gap percent'); //Update trailing order parameters trailingOrders[order_id].trailPct = _newStop; trailingOrders[order_id].gapPct = _newLimit; } else { trailingOrders[order_id].trail = _newStop; trailingOrders[order_id].gap = _newLimit; } //Update stop and limit triggers based on these nnew parameters _updateTrailingPrice(order_id); //Emit event emit OrderChanged(orders[order_id].trader, order_id); emit TrailingOrderChanged(order_id); } /* * @notice Delete an order */ function deleteOrder( uint order_id ) external onlyMyOrder(order_id) onlyValidOrder(order_id){ LimitOrder memory order = orders[order_id]; if((order.orderType == OrderType.TRAILINGSTOPMARKET || order.orderType == OrderType.TRAILINGSTOPLIMIT)) { emit TrailingOrderCancelled(order_id); delete trailingOrders[order_id]; } emit OrderCancelled(order.trader, order_id); delete orders[order_id]; } /* * @notice Execute an order using the order_id * All the logic verifying the order can be successfully executed occurs on the SmartWallet.sol contract */ function execute(uint order_id) external onlyValidOrder(order_id) { //First check that the order hasn't been cancelled/already been executed LimitOrder memory order = orders[order_id]; address _trader = order.trader; require(order.stillValid, 'No longer valid'); //Get the smart wallet of the trader from the factory contract address _smartwallet = factory.getSmartWallet(order.trader); //Try and execute the order (should return true if successful) ISmartWallet(_smartwallet).executeOrder(order_id); if((order.orderType == OrderType.TRAILINGSTOPMARKET || order.orderType == OrderType.TRAILINGSTOPLIMIT)) { //If this is a trailing order, then the botFee gets split between the keeper that //executed the transaction, and the last keeper to update the price if(trailingOrders[order_id].lastUpdatedKeeper != address(0)) { //Making sure that a keeper has actually updated the price, otherwise the executor gets full fee _transfer(IERC20(USDC), msg.sender, order.tipFee.divScalar(2)); _transfer(IERC20(USDC), trailingOrders[order_id].lastUpdatedKeeper, order.tipFee.divScalar(2)); } else { _transfer(IERC20(USDC), msg.sender, order.tipFee); } emit TrailingOrderFilled(order_id); delete trailingOrders[order_id]; } else { //Fee goes to executor _transfer(IERC20(USDC), msg.sender, order.tipFee); } //Invalidate order to prevent double spend delete orders[order_id]; //emit event emit OrderFilled(_trader, order_id); } /* * FUNCTIONS RELATING TO TRAILING ORDERS */ /* * @notice internal function that sets the limitPrice and stopPrice trigger * values based on the witnessPrice variable. Need to set witnessPrice before * calling this function otherwisei you will cause problems. */ function _updateTrailingPrice( uint order_id ) internal { //Get the price as witness Price Decimal.decimal memory _newPrice = trailingOrders[order_id].witnessPrice; //If the order is LONG/BUY then the trigger prices will be above witnessPrice bool isLong = orders[order_id].orderSize.isNegative() ? false : true; if(trailingOrders[order_id].usePct) { //Update trail PCT Decimal.decimal memory tpct = isLong ? Decimal.one().addD(trailingOrders[order_id].trailPct) : Decimal.one().subD(trailingOrders[order_id].trailPct); //Update gap PCT Decimal.decimal memory gpct = isLong ? Decimal.one().addD(trailingOrders[order_id].gapPct) : Decimal.one().subD(trailingOrders[order_id].gapPct); //Calculate trigger prices as percentage of witness Price orders[order_id].stopPrice = _newPrice.mulD(tpct); orders[order_id].limitPrice = orders[order_id].stopPrice.mulD(gpct); } else { //Calculate trigger prices as absolute difference of witness Price orders[order_id].stopPrice = isLong ? _newPrice.addD(trailingOrders[order_id].trail) : _newPrice.subD(trailingOrders[order_id].trail); orders[order_id].limitPrice = isLong ? orders[order_id].stopPrice.addD(trailingOrders[order_id].gap) : orders[order_id].stopPrice.subD(trailingOrders[order_id].gap); } } /* * @notice inform the smart contract that a particular order needs to update its parameters * @param order_id the id of the order to be updated * @param _reserveIndex the index of the AMM ReserveSnapshotted array with the * local price maximum/minimum * The purpose of this function is to incentivise/reward bots that will update the stop/limit prices * for orders. */ function pokeContract( uint order_id, uint _reserveIndex ) external onlyValidOrder(order_id){ //Can only poke for orders that are trailing orders OrderType _thisOrderType = orders[order_id].orderType; require(_thisOrderType == OrderType.TRAILINGSTOPMARKET || _thisOrderType == OrderType.TRAILINGSTOPLIMIT, "Can only poke trailing orders"); //You cannot update the price with values that were accurate before the order was created require(_reserveIndex > trailingOrders[order_id].snapshotCreated, "Order hadn't been created"); //check whether A. there is a higher/lower price that occurred before the current updated value or // B. if it has been more than 15 minutes since the last update after the current updated value require(_reserveIndex < trailingOrders[order_id].snapshotLastUpdated || (block.timestamp - trailingOrders[order_id].snapshotTimestamp > pokeContractDelay), "Can only be updated every 10 minutes"); trailingOrders[order_id].snapshotTimestamp = block.timestamp; bool isLong = orders[order_id].orderSize.isNegative() ? false : true; //Get the price of the AMM at that snapshot Decimal.decimal memory _newPrice = getPriceAtSnapshot( IAmm(orders[order_id].asset), _reserveIndex); //Check that the new price is above/below the current maximum/minimum require(trailingOrders[order_id].witnessPrice.cmp(_newPrice) == (isLong ? int128(1) : -1), "Incorrect trailing price"); //Update witness price and then update further parameters trailingOrders[order_id].witnessPrice = _newPrice; trailingOrders[order_id].snapshotLastUpdated = _reserveIndex; trailingOrders[order_id].lastUpdatedKeeper = msg.sender; _updateTrailingPrice(order_id); emit ContractPoked(order_id, _reserveIndex); } /* * VIEW FUNCTIONS */ function getNumberOrders() public view returns (uint){ return orders.length; } function getTrailingData( uint order_id ) public view returns (TrailingOrderData memory){ return trailingOrders[order_id]; } //Similar function exists on AMM but this is slightly more efficient. function getPriceAtSnapshot( IAmm _asset, uint256 _snapshotIndex ) public view returns (Decimal.decimal memory) { require(_snapshotIndex < _asset.getSnapshotLen(),'Snapshot Index does not exist'); IAmm.ReserveSnapshot memory snap = _asset.reserveSnapshots(_snapshotIndex); return snap.quoteAssetReserve.divD(snap.baseAssetReserve); } function getLimitOrder( uint order_id ) public view onlyValidOrder(order_id) returns (LimitOrder memory) { return (orders[order_id]); } function getLimitOrderPrices( uint id ) public view onlyValidOrder(id) returns( Decimal.decimal memory, Decimal.decimal memory, SignedDecimal.signedDecimal memory, Decimal.decimal memory, Decimal.decimal memory, Decimal.decimal memory, Decimal.decimal memory, address, bool) { LimitOrder memory order = orders[id]; return (order.stopPrice, order.limitPrice, order.orderSize, order.collateral, order.leverage, order.slippage, order.tipFee, order.asset, order.reduceOnly); } function getLimitOrderParams( uint id ) public view onlyValidOrder(id) returns( address, address, OrderType, bool, bool, uint256) { LimitOrder memory order = orders[id]; return (order.asset, order.trader, order.orderType, order.reduceOnly, order.stillValid, order.expiry); } /* * ADMIN / SETUP FUNCTIONS */ function setFactory(address _addr) public onlyOwner{ factory = ISmartWalletFactory(_addr); } function changeMinimumFee(Decimal.decimal memory _fee) public onlyOwner { minimumTipFee = _fee; } /* * MODIFIERS */ modifier onlyValidOrder(uint order_id) { require(order_id < orders.length, 'Invalid ID'); LimitOrder memory order = orders[order_id]; require(order.stillValid, 'No longer valid'); require(((order.expiry == 0 ) || (block.timestamp<order.expiry)), 'Order expired'); _; } modifier onlyMyOrder(uint order_id) { require(msg.sender == orders[order_id].trader, "Not your order"); _; } function requireNonZeroInput(Decimal.decimal memory _decimal, string memory errorMessage) private pure { require(_decimal.toUint() != 0, errorMessage); } }
@notice This function will create a limit order and store it within the contract. Please see documentation for _createOrder()/
function addLimitOrder( IAmm _asset, Decimal.decimal memory _limitPrice, SignedDecimal.signedDecimal memory _positionSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage, Decimal.decimal memory _tipFee, bool _reduceOnly, uint256 _expiry ) external { requireNonZeroInput(_limitPrice, "Limit cannot be zero"); _createOrder(_asset, OrderType.LIMIT, Decimal.zero(), _limitPrice, _positionSize, _collateral, _leverage, _slippage, _tipFee, _reduceOnly, _expiry); }
966,501
[ 1, 2503, 445, 903, 752, 279, 1800, 1353, 471, 1707, 518, 3470, 326, 6835, 18, 7801, 2621, 7323, 364, 389, 2640, 2448, 1435, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 527, 3039, 2448, 12, 203, 565, 467, 37, 7020, 389, 9406, 16, 203, 565, 11322, 18, 12586, 3778, 389, 3595, 5147, 16, 203, 565, 16724, 5749, 18, 5679, 5749, 3778, 389, 3276, 1225, 16, 203, 565, 11322, 18, 12586, 3778, 389, 12910, 2045, 287, 16, 203, 565, 11322, 18, 12586, 3778, 389, 298, 5682, 16, 203, 565, 11322, 18, 12586, 3778, 389, 87, 3169, 2433, 16, 203, 565, 11322, 18, 12586, 3778, 389, 14587, 14667, 16, 203, 565, 1426, 389, 12498, 3386, 16, 203, 565, 2254, 5034, 389, 22409, 203, 225, 262, 3903, 288, 203, 565, 2583, 3989, 7170, 1210, 24899, 3595, 5147, 16, 315, 3039, 2780, 506, 3634, 8863, 203, 565, 389, 2640, 2448, 24899, 9406, 16, 4347, 559, 18, 8283, 16, 11322, 18, 7124, 9334, 389, 3595, 5147, 16, 389, 3276, 1225, 16, 203, 1377, 389, 12910, 2045, 287, 16, 389, 298, 5682, 16, 389, 87, 3169, 2433, 16, 389, 14587, 14667, 16, 389, 12498, 3386, 16, 389, 22409, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; // Adaptado de https://docs.soliditylang.org/en/latest/solidity-by-example.html al español, para explicar herencia en Solidity // Subasta simple que permite que varias direcciones pujen por un premio (no se tiene en cuenta) contract SimpleAuction { address payable public beneficiary; // Beneficiario de la Subasta uint public auctionEndTime; // Tiempo de fin de la subasta en segundos address public highestBidder; // Direccian de la puja mas alta uint public highestBid; // Valor de la puja mas alta mapping(address => uint) pendingReturns; // Mapa de dinero a devolver a los otros pujantes bool ended; // Variable logica que determina si la puja ya termino // Errores /// La subasta ya termino error AuctionAlreadyEnded(); /// La puja es menor a la puja mas alta error BidNotHighEnough(uint highestBid); /// La subasta aun no ha terminado error AuctionNotYetEnded(); /// Ya se llamo el fin de la subasta error AuctionEndAlreadyCalled(); /// No es el beneficiario error NotBeneficiary(); /// Construye el contrato, solo se necesitan el tiempo de la subasta y el beneficiario constructor( uint _biddingTime, address payable _beneficiary ) { beneficiary = _beneficiary; auctionEndTime = block.timestamp + _biddingTime; } /// Recibe una puja y la guarda solo si esta supera la puja actual function bid() virtual public payable { if (block.timestamp > auctionEndTime) // Verifica que la subasta no haya terminado revert AuctionAlreadyEnded(); if (msg.value <= highestBid) // Verifica que la puja sobrepase la puja actual revert BidNotHighEnough(highestBid); if (highestBid != 0) { pendingReturns[highestBidder] += highestBid; // Guardar el monto de dinero a devolver a la dirección que previamente sostenía la puja más alta } // Actualiza los datos de la puja más alta highestBidder = msg.sender; highestBid = msg.value; } /// Función para devolver el dinero a los pujantes previos, debe ser llamada por el pujante en cuestión function withdraw() public returns (bool) { uint amount = pendingReturns[msg.sender]; // Obtener el monto if (amount > 0) { pendingReturns[msg.sender] = 0; // Actualizar el monto a 0 // Enviar monto if (!payable(msg.sender).send(amount)) { pendingReturns[msg.sender] = amount; return false; } } return true; } /// Terminar la subasta, solo puede ser llamada por el beneficiario function auctionEnd() virtual public { if (msg.sender != beneficiary) revert NotBeneficiary(); if (block.timestamp < auctionEndTime) revert AuctionNotYetEnded(); if (ended) revert AuctionEndAlreadyCalled(); ended = true; // Transferir el dinero al beneficiario beneficiary.transfer(highestBid); } } // Subasta a ciegas, no tiene limite de tiempo, para cada puja se guarda un hash con la informacion de la puja, lo que asegura que sea a ciegas // A llegar el tiempo de revelacion, se revelan todas las pujas y se designa el ganador de la subasta, finalmente se devuelve el dinero al resto // de pujantes contract BlindAuction is SimpleAuction { // Estructura de Subasta struct Bid { bytes32 blindedBid; uint deposit; } uint public revealEnd; // Tiempo en segundos de la revelacion de la subasta mapping(address => Bid[]) public bids; // Mapa de direcciones a arreglos de subastas, una misma direccion puede realizar varias subastas /// Muy temprano para llamar esta funcion error TooEarly(uint time); /// Muy tarde para llamar esta funcion error TooLate(uint time); modifier onlyBefore(uint _time) { if (block.timestamp >= _time) revert TooLate(_time); _; } modifier onlyAfter(uint _time) { if (block.timestamp <= _time) revert TooEarly(_time); _; } /// Construye el contrato, instanciado el constructor del padre y la variable de fin de revelacion de la subasta constructor(uint _biddingTime,uint _revealTime,address payable _beneficiary) SimpleAuction(_biddingTime, _beneficiary) { revealEnd = auctionEndTime + _revealTime; } /// Realiza una puja a ciegas donde _blindedBid es el hash de los datos de la puja, igual a keccak256(abi.encodePacked(value, fake, secret)) /// La puja es valida si "deposit" (el valor enviado) es al menos "value" y "fake" es falso /// Si se configura "fake" como verdadero y no se envía el valor exacto de "value" es una forma /// de ocultar la verdadera puja, aun asi se requiere que se haga un deposito. /// 'secret' es simplemente una contraseña que uso el pujante para la encriptacion /// El ether enviado solo será reembolsado solo si la puja es correctamente revelada en la fase de revelacion de pujas /// Solo puede ser llamada antes del fin de la subasta (periodo de pujas) function bid(bytes32 _blindedBid) public payable onlyBefore(auctionEndTime) { // Agregar la puja a la lista de pujas del pujante bids[msg.sender].push(Bid({ blindedBid: _blindedBid, deposit: msg.value })); } /// Funcion que debe ser llamada por cada pujante para revelar sus pujas /// El pujante recibira un reembolso de ether por cada puja correctamente revelada /// sean validas o invalidas, a excepcion de la puja ganadora. /// Solo puede ser llamada despues del periodo de pujas y antes del fin de revelacion de pujas function reveal( uint[] memory _values, bool[] memory _fake, bytes32[] memory _secret ) public onlyAfter(auctionEndTime) onlyBefore(revealEnd) { // Verificar que se hayan provisto los datos suficientes para revelar todas las pujas hechas uint length = bids[msg.sender].length; require(_values.length == length); require(_fake.length == length); require(_secret.length == length); uint refund; // Dinero de reembolso for (uint i = 0; i < length; i++) { // Iterar sobre cada puja Bid storage bidToCheck = bids[msg.sender][i]; // Obtener los datos de la puja, encriptar y comparar con el hash guardado previamente (uint value, bool fake, bytes32 secret) = (_values[i], _fake[i], _secret[i]); if (bidToCheck.blindedBid != keccak256(abi.encodePacked(value, fake, secret))) { continue; // Si el hash no coincide ignorar esta puja ya que no fue correctamente revelada } refund += bidToCheck.deposit; // Verificar que sea una puja valida y de ser asi ubicar la puja // y disminuir el valor reembolsar por revelacion if (!fake && bidToCheck.deposit >= value) { if (placeBid(msg.sender, value)) refund -= value; } bidToCheck.blindedBid = bytes32(0); // Modificar el hash para que esta puja no se pueda volver a revelar } payable(msg.sender).transfer(refund); // Finalmente enviar el dinero total de reembolso por revelacion } /// Finalizar la subasta, sobreescribe la funcion del padre ya que esta solo puede ser llamada /// despues de finalizar las revelaciones de pujas, sin embargo luego llama a la funcion del padre /// para realizar los efectos de finalizacion function auctionEnd() override public onlyAfter(revealEnd) { SimpleAuction.auctionEnd(); } /// Registra las puja valida enviada, solo si esta supera la mayor puja actual /// Solo puede ser usada internamente function placeBid(address bidder, uint value) internal returns (bool success) { if (value <= highestBid) { return false; } if (highestBidder != address(0)) { pendingReturns[highestBidder] += highestBid; } highestBid = value; highestBidder = bidder; return true; } /// Sobreescribir la funcion del padre para que se use la nueva funcion que requiere un parametro function bid() override public payable { revert("Funcion erronea, debe enviar la puja encriptada"); } } // Subasta con etapa de revelacion y pujas falsas, cada direccion puede realizar multiples pujas falsas y verdaderas, // las pujas deben ser reveladas en la fase de revelacion donde se decide que pujas realmente se haran y el dinero que se // debe reembolsar a los pujantes contract RevealAuction is SimpleAuction { // Estructura de Subasta struct Bid { bool fake; uint deposit; } uint public revealEnd; // Tiempo en segundos de la revelacion de la subasta mapping(address => Bid[]) public bids; // Mapa de direcciones a arreglos de subastas, una misma direccion puede realizar varias subastas /// Muy temprano para llamar esta funcion error TooEarly(uint time); /// Muy tarde para llamar esta funcion error TooLate(uint time); modifier onlyBefore(uint _time) { if (block.timestamp >= _time) revert TooLate(_time); _; } modifier onlyAfter(uint _time) { if (block.timestamp <= _time) revert TooEarly(_time); _; } /// Construye el contrato, instanciado el constructor del padre y la variable de fin de revelacion de la subasta constructor(uint _biddingTime,uint _revealTime,address payable _beneficiary) SimpleAuction(_biddingTime, _beneficiary) { revealEnd = auctionEndTime + _revealTime; } /// Realiza una puja a ciegas donde "_fake" es un booleano que define si la puja es verdadera o falsa /// Solo puede ser llamada antes del fin de la subasta (periodo de pujas) function bid(bool _fake) public payable onlyBefore(auctionEndTime) { // Agregar la puja a la lista de pujas del pujante bids[msg.sender].push(Bid({ fake: _fake, deposit: msg.value })); } /// Funcion que debe ser llamada por cada pujante para revelar sus pujas /// es decir, ponerlas en accion function reveal() public onlyAfter(auctionEndTime) onlyBefore(revealEnd){ // Verificar que se hayan provisto los datos suficientes para revelar todas las pujas hechas uint length = bids[msg.sender].length; uint refund; // Dinero de reembolso for (uint i = 0; i < length; i++) { // Iterar sobre cada puja Bid storage bidToCheck = bids[msg.sender][i]; refund += bidToCheck.deposit; // Verificar que sea una puja valida y de ser asi ubicar la puja if (!bidToCheck.fake) { if (placeBid(msg.sender, bidToCheck.deposit)) refund -= bidToCheck.deposit; } bidToCheck.deposit = 0; // Modificar el valor para que no se vuelva a revelar esta puja } pendingReturns[msg.sender] += refund; // Finalmente añadir al dinero total que puede reembolsar } /// Finalizar la subasta, sobreescribe la funcion del padre ya que esta solo puede ser llamada /// despues de finalizar las revelaciones de pujas, sin embargo luego llama a la funcion del padre /// para realizar los efectos de finalizacion function auctionEnd() override public onlyAfter(revealEnd) { SimpleAuction.auctionEnd(); } /// Registra las puja valida enviada, solo si esta supera la mayor puja actual /// Solo puede ser usada internamente function placeBid(address bidder, uint value) internal returns (bool success) { if (value <= highestBid) { return false; } if (highestBidder != address(0)) { pendingReturns[highestBidder] += highestBid; } highestBid = value; highestBidder = bidder; return true; } /// Sobreescribir la funcion del padre para que se use la nueva funcion que requiere un parametro function bid() override public payable { revert("Funcion erronea, debe enviar la puja encriptada"); } }
Construye el contrato, instanciado el constructor del padre y la variable de fin de revelacion de la subasta
constructor(uint _biddingTime,uint _revealTime,address payable _beneficiary) SimpleAuction(_biddingTime, _beneficiary) { revealEnd = auctionEndTime + _revealTime; }
15,821,849
[ 1, 442, 701, 9835, 73, 415, 16252, 31093, 16, 316, 541, 8450, 6821, 415, 3885, 1464, 4627, 266, 677, 7125, 2190, 443, 574, 443, 283, 941, 19861, 443, 7125, 720, 689, 69, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 11890, 389, 70, 1873, 310, 950, 16, 11890, 389, 266, 24293, 950, 16, 2867, 8843, 429, 389, 70, 4009, 74, 14463, 814, 13, 4477, 37, 4062, 24899, 70, 1873, 310, 950, 16, 389, 70, 4009, 74, 14463, 814, 13, 288, 203, 3639, 283, 24293, 1638, 273, 279, 4062, 25255, 397, 389, 266, 24293, 950, 31, 203, 565, 289, 203, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0xf90bA889C8f993Fd625D05D8aB0459dbFE46C3FD/sources/contracts/fee-distribution/FeeDistributor.sol
We assume that `votingEscrow` has been deployed in a week previous to this one. If `votingEscrow` did not have a non-zero supply at the beginning of the current week then any tokens which are distributed this week will be lost permanently.
constructor(IVotingEscrow votingEscrow, uint256 startTime) EIP712("FeeDistributor", "1") { _votingEscrow = votingEscrow; startTime = _roundDownTimestamp(startTime); uint256 currentWeek = _roundDownTimestamp(block.timestamp); require(startTime >= currentWeek, "Cannot start before current week"); if (startTime == currentWeek) { require(votingEscrow.totalSupply(currentWeek) > 0, "Zero total supply results in lost tokens"); } _startTime = startTime; _timeCursor = startTime; }
3,839,386
[ 1, 3218, 6750, 716, 1375, 90, 17128, 6412, 492, 68, 711, 2118, 19357, 316, 279, 4860, 2416, 358, 333, 1245, 18, 971, 1375, 90, 17128, 6412, 492, 68, 5061, 486, 1240, 279, 1661, 17, 7124, 14467, 622, 326, 8435, 434, 326, 783, 4860, 1508, 1281, 2430, 1492, 854, 16859, 333, 4860, 903, 506, 13557, 16866, 715, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 8188, 17128, 6412, 492, 331, 17128, 6412, 492, 16, 2254, 5034, 8657, 13, 512, 2579, 27, 2138, 2932, 14667, 1669, 19293, 3113, 315, 21, 7923, 288, 203, 3639, 389, 90, 17128, 6412, 492, 273, 331, 17128, 6412, 492, 31, 203, 203, 3639, 8657, 273, 389, 2260, 4164, 4921, 12, 1937, 950, 1769, 203, 3639, 2254, 5034, 783, 6630, 273, 389, 2260, 4164, 4921, 12, 2629, 18, 5508, 1769, 203, 3639, 2583, 12, 1937, 950, 1545, 783, 6630, 16, 315, 4515, 787, 1865, 783, 4860, 8863, 203, 3639, 309, 261, 1937, 950, 422, 783, 6630, 13, 288, 203, 5411, 2583, 12, 90, 17128, 6412, 492, 18, 4963, 3088, 1283, 12, 2972, 6630, 13, 405, 374, 16, 315, 7170, 2078, 14467, 1686, 316, 13557, 2430, 8863, 203, 3639, 289, 203, 3639, 389, 1937, 950, 273, 8657, 31, 203, 3639, 389, 957, 6688, 273, 8657, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT /* B L I T B L 0 x L \ L \ I B L I T B L 0 x T L T L B I <3 B I L T L T 0 B 0 B B L L T B L 0 x L \ 0 \ 0 B L I T B L 0 x Blitblox by sayangel.eth Derivative project for Blitmap and Flipmap. Experimenting with 3D glTF on chain. */ pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/interfaces/IERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import '@openzeppelin/contracts/utils/Strings.sol'; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./IBlitmap.sol"; import "./IFlipmap.sol"; contract Blitblox is ERC721, Ownable, ReentrancyGuard { struct glTFCursor { uint8 x; uint8 y; uint256 color1; uint256 color2; uint256 color3; uint256 color4; } uint256 private constant PRECISION_MULTIPLIER = 1000; uint256 private _mintPrice = 0.02 ether; string private _proxyUri; mapping(uint256 => bytes1) private _tokenStyles; mapping(address => uint256) private _creators; IFlipmap flipmap; IBlitmap blitmap; modifier onlyCreators() { require(isCreator(msg.sender)); _; } constructor(address _blitAddress, address _flipAddress) ERC721("Blitblox", "BX") Ownable() { blitmap = IBlitmap(_blitAddress); flipmap = IFlipmap(_flipAddress); } function tokenURI(uint256 tokenId) override(ERC721) public view returns (string memory) { //wrap the original SVG in an anaglyph style filter string memory svg = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 32 32"><filter id="i1" width="150%" height="150%"><feOffset result="offOut" in="SourceGraphic" dx="1" dy="0"/><feOffset result="off2Out" in="SourceGraphic" dx="-1" dy="0"/><feColorMatrix result="matrixOut" in="offOut" type="matrix" values="0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0.4 0"/><feColorMatrix result="matrix2Out" in="off2Out" type="matrix" values="1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.4 0"/><feBlend result="blend1" in="matrix2Out" in2="SourceGraphic" mode="normal"/><feBlend in="matrixOut" in2="blend1" mode="normal"/></filter><g filter="url(#i1)"><image width="100%" height="100%" href="data:image/svg+xml;base64,'; if(tokenId < 1700) svg = string(abi.encodePacked(svg, Base64.encode(bytes(blitmap.tokenSvgDataOf(tokenId))))); else svg = string(abi.encodePacked(svg, Base64.encode(bytes(flipmap.tokenSvgDataOf(tokenId))))); svg = string(abi.encodePacked(svg, '"/></g></svg>')); svg = string(abi.encodePacked('data:image/svg+xml;base64,', Base64.encode(bytes(svg)))); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Blitblox #', Strings.toString(tokenId), '", "description": "Blitblox is a derivative project of Blitmap and Flipmap. It generates a three dimensional voxel version of the corresponding map. All 3D data is generated and stored on chain as a glTF.", "image":"', svg, '","animation_url":"', _proxyUri, Strings.toString(tokenId),'.glb"}')))); return string(abi.encodePacked('data:application/json;base64,', json)); } /* * As of Jan 2022 OS and other platforms with glTF support expect a glb via HTTP response. * hack around this by returning the contract response via an HTTP proxy that * calls tokenGltfDataOf() and returns response. */ function setProxyUri(string memory proxyUri) public onlyOwner { _proxyUri = proxyUri; } function mint(uint256 tokenId, bytes1 style) external payable nonReentrant { require(_mintPrice == msg.value); if(tokenId < 1700) require(blitmap.ownerOf(tokenId) == msg.sender); else require(flipmap.ownerOf(tokenId) == msg.sender); address creatorA = owner(); address creatorB = owner(); //artist gets full royalties on original if(tokenId < 100) { creatorA = blitmap.tokenCreatorOf(tokenId); creatorB = blitmap.tokenCreatorOf(tokenId); } //siblings and flipmaps divide royalties between composition and pallette artist if(tokenId > 99) { uint256 tokenIdA; uint256 tokenIdB; if(tokenId < 1700 ){ (tokenIdA, tokenIdB) = blitmap.tokenParentsOf(tokenId); } else (tokenIdA, tokenIdB) = flipmap.tokenParentsOf(tokenId); creatorA = blitmap.tokenCreatorOf(tokenIdA); creatorB = blitmap.tokenCreatorOf(tokenIdB); } _tokenStyles[tokenId] = style; _safeMint(msg.sender, tokenId); // 25% royalty to original artists. // of that, 75% to composition artist and 25% to palette artist. _creators[creatorA] += 0.00375 ether; _creators[creatorB] += 0.00125 ether; _creators[owner()] += 0.015 ether; } function isCreator(address _address) public view returns (bool) { return _creators[_address] > 0; } function availableBalanceForCreator(address creatorAddress) public view returns (uint256) { return _creators[creatorAddress]; } function withdrawAvailableBalance() public nonReentrant onlyCreators { uint256 withdrawAmount = _creators[msg.sender]; _creators[msg.sender] = 0; payable(msg.sender).transfer(withdrawAmount); } function voxel4(string[32] memory lookup, glTFCursor memory pos) internal pure returns (string memory) { return string(abi.encodePacked( '{"mesh":', Strings.toString(pos.color1), ',"translation": [', lookup[pos.x], ', 0.0,', lookup[31 - pos.y],']},', '{"mesh":', Strings.toString(pos.color2), ',"translation": [', lookup[pos.x + 1], ', 0.0,', lookup[31 - pos.y],']},', string(abi.encodePacked( '{"mesh":', Strings.toString(pos.color3), ',"translation": [', lookup[pos.x + 2], ', 0.0,', lookup[31 - pos.y],']},', '{"mesh":', Strings.toString(pos.color4), ',"translation": [', lookup[pos.x + 3], ', 0.0,', lookup[31- pos.y],']}' )) )) ; } function bitTest(bytes1 aByte, uint8 index) internal pure returns (bool) { return uint8(aByte) >> index & 1 == 1; } function colorIndex(bytes1 aByte, uint8 index1, uint8 index2) internal pure returns (uint) { if (bitTest(aByte, index2) && bitTest(aByte, index1)) { return 3; } else if (bitTest(aByte, index2) && !bitTest(aByte, index1)) { return 2; } else if (!bitTest(aByte, index2) && bitTest(aByte, index1)) { return 1; } return 0; } function styleByteToInts(bytes1 style) internal pure returns (uint8, uint8) { /* * decode the style of a given token. * first 4 bits represent the voxel style: * 0 - normal * 1 - normal with transparency * 2 - exploded * 3 - exploded with transparency * last 4 bits represent the color index to apply transparency to. Value between 0-3. */ return (uint8(style >> 4), uint8(style & hex"0F")); } /*function setTokenStyle(uint256 tokenId, bytes1 style) public { require(ownerOf(tokenId) == msg.sender, "This wallet does not own this Blitblox."); _tokenStyles[tokenId] = style; } function getTokenStyle (uint256 tokenId) public view returns (uint8, uint8) { return styleByteToInts(_tokenStyles[tokenId]); }*/ //returns an approximation of the original RGB value in sRGB color space. function intRGBValTosRGBVal(uint256 val) internal pure returns (string memory result) { uint256 res = (val * PRECISION_MULTIPLIER) * (PRECISION_MULTIPLIER * PRECISION_MULTIPLIER) / (255 * PRECISION_MULTIPLIER); res = (res ** 2)/( PRECISION_MULTIPLIER * PRECISION_MULTIPLIER); string memory sRGBString = string( abi.encodePacked(bytes(Strings.toString(uint(res/( PRECISION_MULTIPLIER * PRECISION_MULTIPLIER)))), bytes("."))); sRGBString = string(abi.encodePacked(sRGBString, bytes( Strings.toString( res % ( PRECISION_MULTIPLIER * PRECISION_MULTIPLIER) / 100000 ) ) ) ); sRGBString = string(abi.encodePacked(sRGBString, bytes( Strings.toString( res % ( PRECISION_MULTIPLIER * PRECISION_MULTIPLIER / 10) / 10000 ) ) ) ); sRGBString = string(abi.encodePacked(sRGBString, bytes( Strings.toString( res % ( PRECISION_MULTIPLIER * PRECISION_MULTIPLIER / 100) / 1000 ) ) ) ); return sRGBString; } function tokenGltfDataOf(uint256 tokenId) public view returns (string memory) { bytes memory data; if(tokenId < 1700 ) { data = blitmap.tokenDataOf(tokenId); } else { data = flipmap.tokenDataOf(tokenId); } return tokenGltfData(data, _tokenStyles[tokenId]); } /* * glTF data built from blitmap/flipmap token data. Just like original SVGs data is built in chunks of 4 voxels at a time. * The output is a 32 x 32 grid of voxels. Each voxel is a node in the scene that references 1 of 4 meshes depending on its color. * There are 4 mesh primitives with the only difference being material index. There is only one mesh buffer: a voxel/cube. * Voxel spacing and material transparency are affected by the tokens saved style. */ function tokenGltfData(bytes memory data, bytes1 style) public pure returns (string memory) { (uint8 voxelStyle, uint8 transparencyIndex) = styleByteToInts(style); string[32] memory lookup = [ "0", "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" ]; glTFCursor memory pos; uint256[3][4] memory colors = [ [byteToUint(data[0]), byteToUint(data[1]), byteToUint(data[2])], [byteToUint(data[3]), byteToUint(data[4]), byteToUint(data[5])], [byteToUint(data[6]), byteToUint(data[7]), byteToUint(data[8])], [byteToUint(data[9]), byteToUint(data[10]), byteToUint(data[11])] ]; string[8] memory p; string memory gltfAccumulator = '{"asset": {"generator": "Blitblox.sol","version": "2.0"},"scene": 0,"scenes": [{"nodes": [0]}],'; gltfAccumulator = strConcat(gltfAccumulator, '"nodes": [{"children": [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,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024],'); gltfAccumulator = strConcat(gltfAccumulator, '"matrix": [1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0]},'); for (uint i = 12; i < 268; i += 8) { pos.color1 = colorIndex(data[i], 6, 7); pos.color2 = colorIndex(data[i], 4, 5); pos.color3 = colorIndex(data[i], 2, 3); pos.color4 = colorIndex(data[i], 0, 1); p[0] = voxel4(lookup, pos); p[0] = strConcat(p[0], ','); pos.x += 4; pos.color1 = colorIndex(data[i + 1], 6, 7); pos.color2 = colorIndex(data[i + 1], 4, 5); pos.color3 = colorIndex(data[i + 1], 2, 3); pos.color4 = colorIndex(data[i + 1], 0, 1); p[1] = voxel4(lookup, pos); p[1] = strConcat(p[1], ','); pos.x += 4; pos.color1 = colorIndex(data[i + 2], 6, 7); pos.color2 = colorIndex(data[i + 2], 4, 5); pos.color3 = colorIndex(data[i + 2], 2, 3); pos.color4 = colorIndex(data[i + 2], 0, 1); p[2] = voxel4(lookup, pos); p[2] = strConcat(p[2], ','); pos.x += 4; pos.color1 = colorIndex(data[i + 3], 6, 7); pos.color2 = colorIndex(data[i + 3], 4, 5); pos.color3 = colorIndex(data[i + 3], 2, 3); pos.color4 = colorIndex(data[i + 3], 0, 1); p[3] = voxel4(lookup, pos); p[3] = strConcat(p[3], ','); pos.x += 4; pos.color1 = colorIndex(data[i + 4], 6, 7); pos.color2 = colorIndex(data[i + 4], 4, 5); pos.color3 = colorIndex(data[i + 4], 2, 3); pos.color4 = colorIndex(data[i + 4], 0, 1); p[4] = voxel4(lookup, pos); p[4] = strConcat(p[4], ','); pos.x += 4; pos.color1 = colorIndex(data[i + 5], 6, 7); pos.color2 = colorIndex(data[i + 5], 4, 5); pos.color3 = colorIndex(data[i + 5], 2, 3); pos.color4 = colorIndex(data[i + 5], 0, 1); p[5] = voxel4(lookup, pos); p[5] = strConcat(p[5], ','); pos.x += 4; pos.color1 = colorIndex(data[i + 6], 6, 7); pos.color2 = colorIndex(data[i + 6], 4, 5); pos.color3 = colorIndex(data[i + 6], 2, 3); pos.color4 = colorIndex(data[i + 6], 0, 1); p[6] = voxel4(lookup, pos); p[6] = strConcat(p[6], ','); pos.x += 4; pos.color1 = colorIndex(data[i + 7], 6, 7); pos.color2 = colorIndex(data[i + 7], 4, 5); pos.color3 = colorIndex(data[i + 7], 2, 3); pos.color4 = colorIndex(data[i + 7], 0, 1); p[7] = voxel4(lookup, pos); if(i + 9 < 268){ p[7] = strConcat(p[7], ','); } pos.x += 4; gltfAccumulator = string(abi.encodePacked(gltfAccumulator, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7])); if (pos.x >= 32) { pos.x = 0; pos.y += 1; } } gltfAccumulator = strConcat(gltfAccumulator, '],'); gltfAccumulator = strConcat(gltfAccumulator, '"materials": ['); for(uint i=0; i < colors.length; i++){ gltfAccumulator = strConcat(gltfAccumulator,'{"pbrMetallicRoughness": {"baseColorFactor": ['); gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][0])), bytes(",") )); gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][1])), bytes(",") )); gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][2])), bytes(",") )); if(voxelStyle % 2 == 1 && i == transparencyIndex) { gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("0.5"))); } else { gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("1.0"))); } gltfAccumulator = strConcat(gltfAccumulator,'],"metallicFactor": 0.0},'); if(voxelStyle % 2 == 1 && i == transparencyIndex) { gltfAccumulator = strConcat(gltfAccumulator, '"alphaMode": "BLEND",'); } gltfAccumulator = strConcat(gltfAccumulator, '"name": "material"}'); if(i + 1 < colors.length ){ gltfAccumulator = strConcat(gltfAccumulator, ','); } } gltfAccumulator = strConcat(gltfAccumulator,'],'); gltfAccumulator = strConcat(gltfAccumulator, '"meshes": ['); for(uint i=0; i < colors.length; i++){ gltfAccumulator = strConcat(gltfAccumulator,'{"primitives": [{"attributes": {"POSITION": 0, "NORMAL": 1},"indices": 2,"material": '); gltfAccumulator = strConcat(gltfAccumulator, Strings.toString(i)); gltfAccumulator = strConcat(gltfAccumulator,'}],"name": "Mesh'); gltfAccumulator = strConcat(gltfAccumulator, Strings.toString(i)); gltfAccumulator = strConcat(gltfAccumulator,'"}'); if(i + 1 < colors.length ){ gltfAccumulator = strConcat(gltfAccumulator, ','); } } gltfAccumulator = strConcat(gltfAccumulator,'],'); gltfAccumulator = strConcat(gltfAccumulator, '"accessors": ['); gltfAccumulator = strConcat(gltfAccumulator, '{"bufferView" : 0,"componentType" : 5126,"count" : 24,"max" : [0.5,0.5,0.5],"min" : [-0.5,-0.5,-0.5],"type" : "VEC3"},'); gltfAccumulator = strConcat(gltfAccumulator, '{"bufferView" : 1,"componentType" : 5126,"count" : 24,"type" : "VEC3"},'); gltfAccumulator = strConcat(gltfAccumulator, '{"bufferView" : 2,"componentType" : 5123,"count" : 36,"type" : "SCALAR"}'); gltfAccumulator = strConcat(gltfAccumulator, '],'); gltfAccumulator = strConcat(gltfAccumulator, '"bufferViews": ['); gltfAccumulator = strConcat(gltfAccumulator, '{"buffer" : 0,"byteLength" : 288,"byteOffset" : 0},'); gltfAccumulator = strConcat(gltfAccumulator, '{"buffer" : 0,"byteLength" : 288,"byteOffset" : 288},'); gltfAccumulator = strConcat(gltfAccumulator, '{"buffer" : 0,"byteLength" : 72,"byteOffset" : 576}'); gltfAccumulator = strConcat(gltfAccumulator, '],'); gltfAccumulator = strConcat(gltfAccumulator, '"buffers": [{"byteLength": 648,"uri": "data:application/octet-stream;base64,'); //the strings below are the buffers for a voxel's vertex data. //every node refers to a mesh described by this same buffer. //initially I had a single buffer and applied a scale transform to every node depdnding on style //but this was inefficient and caused a 4x bigger payload and longer execution time. //when the "exploded" style is chosen the buffer is modified to be a smaller voxel. //index and normal buffers are the same regardless of style. if(voxelStyle < 2){ gltfAccumulator = strConcat(gltfAccumulator, 'AAAAvwAAAL8AAAA/AAAAPwAAAL8AAAA/AAAAvwAAAD8AAAA/AAAAPwAAAD8AAAA/AAAAPwAAAL8AAAA/AAAAvwAAAL8AAAA/AAAAPwAAAL8AAAC/AAAAvwAAAL8AAAC/AAAAPwAAAD8AAAA/AAAAPwAAAL8AAAA/AAAAPwAAAD8AAAC/AAAAPwAAAL8AAAC/AAAAvwAAAD8AAAA/AAAAPwAAAD8AAAA/AAAAvwAAAD8AAAC/AAAAPwAAAD8AAAC/AAAAvwAAAL8AAAA/AAAAvwAAAD8AAAA/AAAAvwAAAL8AAAC/AAAAvwAAAD8AAAC/AAAAvwAAAL8AAAC/AAAAvwAAAD8AAAC/AAAAPwAAAL8AAAC/AAAAPwAAAD8AAAC/'); } else { gltfAccumulator = strConcat(gltfAccumulator, 'AADAvgAAwL4AAMA+AADAPgAAwL4AAMA+AADAvgAAwD4AAMA+AADAPgAAwD4AAMA+AADAPgAAwL4AAMA+AADAvgAAwL4AAMA+AADAPgAAwL4AAMC+AADAvgAAwL4AAMC+AADAPgAAwD4AAMA+AADAPgAAwL4AAMA+AADAPgAAwD4AAMC+AADAPgAAwL4AAMC+AADAvgAAwD4AAMA+AADAPgAAwD4AAMA+AADAvgAAwD4AAMC+AADAPgAAwD4AAMC+AADAvgAAwL4AAMA+AADAvgAAwD4AAMA+AADAvgAAwL4AAMC+AADAvgAAwD4AAMC+AADAvgAAwL4AAMC+AADAvgAAwD4AAMC+AADAPgAAwL4AAMC+AADAPgAAwD4AAMC+'); } gltfAccumulator = strConcat(gltfAccumulator, 'AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAgL8AAACAAAAAAAAAgL8AAACAAAAAAAAAgL8AAACAAAAAAAAAgL8AAACAAACAPwAAAAAAAACAAACAPwAAAAAAAACAAACAPwAAAAAAAACAAACAPwAAAAAAAACAAAAAAAAAgD8AAACAAAAAAAAAgD8AAACAAAAAAAAAgD8AAACAAAAAAAAAgD8AAACAAACAvwAAAAAAAACAAACAvwAAAAAAAACAAACAvwAAAAAAAACAAACAvwAAAAAAAACAAAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAABAAIAAwACAAEABAAFAAYABwAGAAUACAAJAAoACwAKAAkADAANAA4ADwAOAA0AEAARABIAEwASABEAFAAVABYAFwAWABUA"}]'); gltfAccumulator = strConcat(gltfAccumulator, '}'); return gltfAccumulator; } function byteToUint(bytes1 b) internal pure returns (uint256) { return uint256(uint8(b)); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory result) { result = string(abi.encodePacked(bytes(_a), bytes(_b))); } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/ERC721/extensions/IERC721Enumerable.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IBlitmap{ function ownerOf(uint256 tokenId) external view returns (address); function tokenCreatorOf(uint256 tokenId) external view returns (address); function tokenDataOf(uint256 tokenId) external view returns (bytes memory) ; function tokenParentsOf(uint256 tokenId) external view returns (uint256, uint256); function tokenSvgDataOf(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IFlipmap{ function ownerOf(uint256 tokenId) external view returns (address); function tokenDataOf(uint256 tokenId) external view returns (bytes memory) ; function tokenParentsOf(uint256 tokenId) external view returns (uint256, uint256); function tokenSvgDataOf(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
SPDX-License-Identifier: MIT SPDX-License-Identifier: MIT* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.0; import "../token/ERC721/extensions/IERC721Enumerable.sol"; pragma solidity ^0.8.0; import "../utils/Context.sol"; constructor() { _setOwner(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
2,559,066
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 11405, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 225, 13456, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 2525, 805, 16, 326, 3410, 2236, 903, 506, 326, 1245, 716, 5993, 383, 1900, 326, 6835, 18, 1220, 848, 5137, 506, 3550, 598, 288, 13866, 5460, 12565, 5496, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 6754, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 14223, 6914, 353, 1772, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 5666, 315, 6216, 2316, 19, 654, 39, 27, 5340, 19, 9489, 19, 45, 654, 39, 27, 5340, 3572, 25121, 18, 18281, 14432, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 5666, 315, 6216, 5471, 19, 1042, 18, 18281, 14432, 203, 203, 565, 3885, 1435, 288, 203, 3639, 389, 542, 5541, 24899, 3576, 12021, 10663, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 8443, 1435, 422, 389, 3576, 12021, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 3639, 389, 542, 5541, 12, 2867, 12, 20, 10019, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 5024, 1338, 5541, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-04-26 */ pragma solidity ^0.4.23; interface IERC721 { function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; } interface IERC1155 { function safeTransferFrom(address from, address to, uint256 tokenId, uint256 amount, bytes data) external; } /// @title MerkleValidator enables matching trait-based and collection-based orders for ERC721 and ERC1155 tokens. /// @author 0age /// @dev This contract is intended to be called during atomicMatch_ via DELEGATECALL. contract MerkleValidator { /// @dev Match an ERC721 order, ensuring that the supplied proof demonstrates inclusion of the tokenId in the associated merkle root. /// @param from The account to transfer the ERC721 token from — this token must first be approved on the seller's AuthenticatedProxy contract. /// @param to The account to transfer the ERC721 token to. /// @param token The ERC721 token to transfer. /// @param tokenId The ERC721 tokenId to transfer. /// @param root A merkle root derived from each valid tokenId — set to 0 to indicate a collection-level or tokenId-specific order. /// @param proof A proof that the supplied tokenId is contained within the associated merkle root. Must be length 0 if root is not set. /// @return A boolean indicating a successful match and transfer. function matchERC721UsingCriteria( address from, address to, IERC721 token, uint256 tokenId, bytes32 root, bytes32[] proof ) external returns (bool) { // Proof verification is performed when there's a non-zero root. if (root != bytes32(0)) { _verifyProof(tokenId, root, proof); } else if (proof.length != 0) { // A root of zero should never have a proof. revert("UnnecessaryProof"); } // Transfer the token. token.transferFrom(from, to, tokenId); return true; } /// @dev Match an ERC721 order using `safeTransferFrom`, ensuring that the supplied proof demonstrates inclusion of the tokenId in the associated merkle root. /// @param from The account to transfer the ERC721 token from — this token must first be approved on the seller's AuthenticatedProxy contract. /// @param to The account to transfer the ERC721 token to. /// @param token The ERC721 token to transfer. /// @param tokenId The ERC721 tokenId to transfer. /// @param root A merkle root derived from each valid tokenId — set to 0 to indicate a collection-level or tokenId-specific order. /// @param proof A proof that the supplied tokenId is contained within the associated merkle root. Must be length 0 if root is not set. /// @return A boolean indicating a successful match and transfer. function matchERC721WithSafeTransferUsingCriteria( address from, address to, IERC721 token, uint256 tokenId, bytes32 root, bytes32[] proof ) external returns (bool) { // Proof verification is performed when there's a non-zero root. if (root != bytes32(0)) { _verifyProof(tokenId, root, proof); } else if (proof.length != 0) { // A root of zero should never have a proof. revert("UnnecessaryProof"); } // Transfer the token. token.safeTransferFrom(from, to, tokenId); return true; } /// @dev Match an ERC1155 order, ensuring that the supplied proof demonstrates inclusion of the tokenId in the associated merkle root. /// @param from The account to transfer the ERC1155 token from — this token must first be approved on the seller's AuthenticatedProxy contract. /// @param to The account to transfer the ERC1155 token to. /// @param token The ERC1155 token to transfer. /// @param tokenId The ERC1155 tokenId to transfer. /// @param amount The amount of ERC1155 tokens with the given tokenId to transfer. /// @param root A merkle root derived from each valid tokenId — set to 0 to indicate a collection-level or tokenId-specific order. /// @param proof A proof that the supplied tokenId is contained within the associated merkle root. Must be length 0 if root is not set. /// @return A boolean indicating a successful match and transfer. function matchERC1155UsingCriteria( address from, address to, IERC1155 token, uint256 tokenId, uint256 amount, bytes32 root, bytes32[] proof ) external returns (bool) { // Proof verification is performed when there's a non-zero root. if (root != bytes32(0)) { _verifyProof(tokenId, root, proof); } else if (proof.length != 0) { // A root of zero should never have a proof. revert("UnnecessaryProof"); } // Transfer the token. token.safeTransferFrom(from, to, tokenId, amount, ""); return true; } /// @dev Ensure that a given tokenId is contained within a supplied merkle root using a supplied proof. /// @param leaf The tokenId. /// @param root A merkle root derived from each valid tokenId. /// @param proof A proof that the supplied tokenId is contained within the associated merkle root. function _verifyProof( uint256 leaf, bytes32 root, bytes32[] memory proof ) private pure { bytes32 computedHash = bytes32(leaf); for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } if (computedHash != root) { revert("InvalidProof"); } } /// @dev Efficiently hash two bytes32 elements using memory scratch space. /// @param a The first element included in the hash. /// @param b The second element included in the hash. /// @return value The resultant hash of the two bytes32 elements. function _efficientHash( bytes32 a, bytes32 b ) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } }
Transfer the token.
token.safeTransferFrom(from, to, tokenId, amount, "");
15,131,245
[ 1, 5912, 326, 1147, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1147, 18, 4626, 5912, 1265, 12, 2080, 16, 358, 16, 1147, 548, 16, 3844, 16, 1408, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x07CFA1637981Cf5c6Bf1Abb6A79cBbf758E13c67/sources/github/alexanderpetrov-sudo/sorry.finance/contract/SORRYFinance_6.0.sol
this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { }
8,184,153
[ 1, 2211, 707, 353, 14549, 364, 13763, 777, 14036, 16, 309, 4862, 14667, 353, 638, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2316, 5912, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 16, 6430, 4862, 14667, 13, 3238, 288, 203, 3639, 309, 12, 5, 22188, 14667, 13, 203, 5411, 12787, 14667, 5621, 203, 540, 203, 203, 203, 565, 289, 203, 203, 3639, 309, 261, 67, 291, 16461, 63, 15330, 65, 597, 401, 67, 291, 16461, 63, 20367, 5717, 288, 203, 5411, 389, 13866, 1265, 16461, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 5411, 389, 13866, 774, 16461, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 5411, 389, 13866, 8336, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 5411, 389, 13866, 20240, 16461, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 5411, 389, 13866, 8336, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 3639, 289, 203, 540, 203, 3639, 309, 12, 5, 22188, 14667, 13, 203, 5411, 5217, 1595, 14667, 5621, 203, 3639, 289, 469, 309, 16051, 67, 291, 16461, 63, 15330, 65, 597, 389, 291, 16461, 63, 20367, 5717, 288, 203, 3639, 289, 469, 309, 16051, 67, 291, 16461, 63, 15330, 65, 597, 401, 67, 291, 16461, 63, 20367, 5717, 288, 203, 3639, 289, 469, 309, 261, 67, 291, 16461, 63, 15330, 65, 597, 389, 291, 16461, 63, 20367, 5717, 288, 203, 3639, 289, 469, 288, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0xAb412B57a88f2567b14Ec20524F1C0D2D67F87d0/sources/contracts/LiquidityMiningRewardDistributor/LiquidityMiningRewardDistributor.sol
* @inheritdoc ILiquidityMiningRewardDistributor/
function addPoints( string memory _bucketName, address _user, uint256 _miningAmount, uint256 _maxStabilizationPeriodEnd, uint256 _maxPeriodTime, uint256 _currentTimestamp ) external override { _require(primexDNS.getBucketAddress(_bucketName) == msg.sender, Errors.FORBIDDEN.selector); uint256 points = _calculatePoints(_miningAmount, _maxStabilizationPeriodEnd, _maxPeriodTime, _currentTimestamp); buckets[_bucketName].totalPoints += points; buckets[_bucketName].lendersInfo[_user].points += points; buckets[_bucketName].lendersInfo[_user].depositedAmount += _miningAmount; }
3,755,305
[ 1, 36, 10093, 467, 48, 18988, 24237, 2930, 310, 17631, 1060, 1669, 19293, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 5636, 12, 203, 3639, 533, 3778, 389, 7242, 461, 16, 203, 3639, 1758, 389, 1355, 16, 203, 3639, 2254, 5034, 389, 1154, 310, 6275, 16, 203, 3639, 2254, 5034, 389, 1896, 510, 22681, 1588, 5027, 1638, 16, 203, 3639, 2254, 5034, 389, 1896, 5027, 950, 16, 203, 3639, 2254, 5034, 389, 2972, 4921, 203, 565, 262, 3903, 3849, 288, 203, 3639, 389, 6528, 12, 30438, 338, 11602, 18, 588, 4103, 1887, 24899, 7242, 461, 13, 422, 1234, 18, 15330, 16, 9372, 18, 7473, 30198, 18, 9663, 1769, 203, 3639, 2254, 5034, 3143, 273, 389, 11162, 5636, 24899, 1154, 310, 6275, 16, 389, 1896, 510, 22681, 1588, 5027, 1638, 16, 389, 1896, 5027, 950, 16, 389, 2972, 4921, 1769, 203, 3639, 9169, 63, 67, 7242, 461, 8009, 4963, 5636, 1011, 3143, 31, 203, 3639, 9169, 63, 67, 7242, 461, 8009, 80, 10130, 966, 63, 67, 1355, 8009, 4139, 1011, 3143, 31, 203, 3639, 9169, 63, 67, 7242, 461, 8009, 80, 10130, 966, 63, 67, 1355, 8009, 323, 1724, 329, 6275, 1011, 389, 1154, 310, 6275, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-06-16 */ pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // // Symbol : ETD // Name : Ethereum Diamond // Total supply : 100000000000000000000000 // Decimals : 9 // Owner Account : 0xeFC92C1E0805a4eDc5BF39262413b27b0fcB82A0 // Enjoy. // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Lib: Safe Math // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } /** ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers */ contract ETDToken is ERC20Interface, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "ETD"; name = "Ethereum Diamond"; decimals = 9; _totalSupply = 100000000000000000000000; balances[0xeFC92C1E0805a4eDc5BF39262413b27b0fcB82A0] = _totalSupply; emit Transfer(address(0), 0xeFC92C1E0805a4eDc5BF39262413b27b0fcB82A0, _totalSupply); } // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ function () public payable { revert(); } }
------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; }
6,683,337
[ 1, 29461, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2935, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 2430, 31, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 2430, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.0; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC4626Vault is IERC20 { /// @notice The address of the underlying token used for the Vault uses for accounting, depositing, and withdrawing function asset() external view returns (address assetTokenAddress); /// @notice Total amount of the underlying asset that is “managed” by Vault function totalAssets() external view returns (uint256 totalManagedAssets); /** * @notice The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met. * @param assets The amount of underlying assets to be convert to vault shares. * @return shares The amount of vault shares converted from the underlying assets. */ function convertToShares(uint256 assets) external view returns (uint256 shares); /** * @notice The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met. * @param shares The amount of vault shares to be converted to the underlying assets. * @return assets The amount of underlying assets converted from the vault shares. */ function convertToAssets(uint256 shares) external view returns (uint256 assets); /** * @notice The maximum number of underlying assets that caller can deposit. * @param caller Account that the assets will be transferred from. * @return maxAssets The maximum amount of underlying assets the caller can deposit. */ function maxDeposit(address caller) external view returns (uint256 maxAssets); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions. * @param assets The amount of underlying assets to be transferred. * @return shares The amount of vault shares that will be minted. */ function previewDeposit(uint256 assets) external view returns (uint256 shares); /** * @notice Mint vault shares to receiver by transferring exact amount of underlying asset tokens from the caller. * @param assets The amount of underlying assets to be transferred to the vault. * @param receiver The account that the vault shares will be minted to. * @return shares The amount of vault shares that were minted. */ function deposit(uint256 assets, address receiver) external returns (uint256 shares); /** * @notice The maximum number of vault shares that caller can mint. * @param caller Account that the underlying assets will be transferred from. * @return maxShares The maximum amount of vault shares the caller can mint. */ function maxMint(address caller) external view returns (uint256 maxShares); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions. * @param shares The amount of vault shares to be minted. * @return assets The amount of underlying assests that will be transferred from the caller. */ function previewMint(uint256 shares) external view returns (uint256 assets); /** * @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller. * @param shares The amount of vault shares to be minted. * @param receiver The account the vault shares will be minted to. * @return assets The amount of underlying assets that were transferred from the caller. */ function mint(uint256 shares, address receiver) external returns (uint256 assets); /** * @notice The maximum number of underlying assets that owner can withdraw. * @param owner Account that owns the vault shares. * @return maxAssets The maximum amount of underlying assets the owner can withdraw. */ function maxWithdraw(address owner) external view returns (uint256 maxAssets); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions. * @param assets The amount of underlying assets to be withdrawn. * @return shares The amount of vault shares that will be burnt. */ function previewWithdraw(uint256 assets) external view returns (uint256 shares); /** * @notice Burns enough vault shares from owner and transfers the exact amount of underlying asset tokens to the receiver. * @param assets The amount of underlying assets to be withdrawn from the vault. * @param receiver The account that the underlying assets will be transferred to. * @param owner Account that owns the vault shares to be burnt. * @return shares The amount of vault shares that were burnt. */ function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares); /** * @notice The maximum number of shares an owner can redeem for underlying assets. * @param owner Account that owns the vault shares. * @return maxShares The maximum amount of shares the owner can redeem. */ function maxRedeem(address owner) external view returns (uint256 maxShares); /** * @notice Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, given current on-chain conditions. * @param shares The amount of vault shares to be burnt. * @return assets The amount of underlying assests that will transferred to the receiver. */ function previewRedeem(uint256 shares) external view returns (uint256 assets); /** * @notice Burns exact amount of vault shares from owner and transfers the underlying asset tokens to the receiver. * @param shares The amount of vault shares to be burnt. * @param receiver The account the underlying assets will be transferred to. * @param owner The account that owns the vault shares to be burnt. * @return assets The amount of underlying assets that were transferred to the receiver. */ function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets); /*/////////////////////////////////////////////////////////////// Events //////////////////////////////////////////////////////////////*/ /** * @dev Emitted when caller has exchanged assets for shares, and transferred those shares to owner. * * Note It must be emitted when tokens are deposited into the Vault in ERC4626.mint or ERC4626.deposit methods. * */ event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares); /** * @dev Emitted when sender has exchanged shares for assets, and transferred those assets to receiver. * * Note It must be emitted when shares are withdrawn from the Vault in ERC4626.redeem or ERC4626.withdraw methods. * */ event Withdraw( address indexed caller, address indexed receiver, address indexed owner, uint256 assets, uint256 shares ); } interface IUnwrapper { // @dev Get bAssetOut status function getIsBassetOut( address _masset, bool _inputIsCredit, address _output ) external view returns (bool isBassetOut); /// @dev Estimate output function getUnwrapOutput( bool _isBassetOut, address _router, address _input, bool _inputIsCredit, address _output, uint256 _amount ) external view returns (uint256 output); /// @dev Unwrap and send function unwrapAndSend( bool _isBassetOut, address _router, address _input, address _output, uint256 _amount, uint256 _minAmountOut, address _beneficiary ) external returns (uint256 outputQuantity); } interface ISavingsManager { /** @dev Admin privs */ function distributeUnallocatedInterest(address _mAsset) external; /** @dev Liquidator */ function depositLiquidation(address _mAsset, uint256 _liquidation) external; /** @dev Liquidator */ function collectAndStreamInterest(address _mAsset) external; /** @dev Public privs */ function collectAndDistributeInterest(address _mAsset) external; } interface ISavingsContractV4 is IERC4626Vault { // DEPRECATED but still backwards compatible function redeem(uint256 _amount) external returns (uint256 massetReturned); function creditBalances(address) external view returns (uint256); // V1 & V2 (use balanceOf) // -------------------------------------------- function depositInterest(uint256 _amount) external; // V1 & V2 function depositSavings(uint256 _amount) external returns (uint256 creditsIssued); // V1 & V2 function depositSavings(uint256 _amount, address _beneficiary) external returns (uint256 creditsIssued); // V2 function redeemCredits(uint256 _amount) external returns (uint256 underlyingReturned); // V2 function redeemUnderlying(uint256 _amount) external returns (uint256 creditsBurned); // V2 function exchangeRate() external view returns (uint256); // V1 & V2 function balanceOfUnderlying(address _user) external view returns (uint256 balance); // V2 function underlyingToCredits(uint256 _credits) external view returns (uint256 underlying); // V2 function creditsToUnderlying(uint256 _underlying) external view returns (uint256 credits); // V2 // -------------------------------------------- function redeemAndUnwrap( uint256 _amount, bool _isCreditAmt, uint256 _minAmountOut, address _output, address _beneficiary, address _router, bool _isBassetOut ) external returns ( uint256 creditsBurned, uint256 massetRedeemed, uint256 outputQuantity ); function depositSavings( uint256 _underlying, address _beneficiary, address _referrer ) external returns (uint256 creditsIssued); function deposit( uint256 assets, address receiver, address referrer ) external returns (uint256 shares); function mint( uint256 shares, address receiver, address referrer ) external returns (uint256 assets); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. // constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return payable(msg.sender); } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ERC205 is Context, IERC20 { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] -= amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()] - amount); } } abstract contract InitializableERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize( string memory nameArg, string memory symbolArg, uint8 decimalsArg ) internal { _name = nameArg; _symbol = symbolArg; _decimals = decimalsArg; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } abstract contract InitializableToken is ERC205, InitializableERC20Detailed { /** * @dev Initialization function for implementing contract * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize(string memory _nameArg, string memory _symbolArg) internal { InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18); } } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } abstract contract ImmutableModule is ModuleKeys { INexus public immutable nexus; /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ constructor(address _nexus) { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { _onlyGovernor(); _; } function _onlyGovernor() internal view { require(msg.sender == _governor(), "Only governor can execute"); } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } } interface IConnector { /** * @notice Deposits the mAsset into the connector * @param _amount Units of mAsset to receive and deposit */ function deposit(uint256 _amount) external; /** * @notice Withdraws a specific amount of mAsset from the connector * @param _amount Units of mAsset to withdraw */ function withdraw(uint256 _amount) external; /** * @notice Withdraws all mAsset from the connector */ function withdrawAll() external; /** * @notice Returns the available balance in the connector. In connections * where there is likely to be an initial dip in value due to conservative * exchange rates (e.g. with Curves `get_virtual_price`), it should return * max(deposited, balance) to avoid temporary negative yield. Any negative yield * should be corrected during a withdrawal or over time. * @return Balance of mAsset in the connector */ function checkBalance() external view returns (uint256); } contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require( initializing || isConstructor() || !initialized, "Contract instance has already been initialized" ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } library StableMath { /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA * Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold) * bAsset ratio unit for use in exact calculations, * where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit */ uint256 private constant RATIO_SCALE = 1e8; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Provides an interface to the ratio unit * @return Ratio scale unit (1e8 or 1 * 10**8) */ function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x * FULL_SCALE; } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 // return 9e38 / 1e18 = 9e18 return (x * y) / scale; } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x * y; // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled + FULL_SCALE - 1; // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil / FULL_SCALE; } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 // e.g. 8e36 / 10e18 = 8e17 return (x * FULL_SCALE) / y; } /*************************************** RATIO FUNCS ****************************************/ /** * @dev Multiplies and truncates a token ratio, essentially flooring the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand operand to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return c Result after multiplying the two inputs and then dividing by the ratio scale */ function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return mulTruncateScale(x, ratio, RATIO_SCALE); } /** * @dev Multiplies and truncates a token ratio, rounding up the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand input to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the shared * ratio scale, rounded up to the closest base unit. */ function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) { // e.g. How much mAsset should I burn for this bAsset (x)? // 1e18 * 1e8 = 1e26 uint256 scaled = x * ratio; // 1e26 + 9.99e7 = 100..00.999e8 uint256 ceil = scaled + RATIO_SCALE - 1; // return 100..00.999e8 / 1e8 = 1e18 return ceil / RATIO_SCALE; } /** * @dev Precisely divides two ratioed units, by first scaling the left hand operand * i.e. How much bAsset is this mAsset worth? * @param x Left hand operand in division * @param ratio bAsset ratio * @return c Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 // return 1e22 / 1e12 = 1e10 return (x * RATIO_SCALE) / ratio; } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } } /** * @title SavingsContract * @author mStable * @notice Savings contract uses the ever increasing "exchangeRate" to increase * the value of the Savers "credits" (ERC20) relative to the amount of additional * underlying collateral that has been deposited into this contract ("interest") * @dev VERSION: 2.2 * DATE: 2022-04-08 */ contract SavingsContract_imbtc_mainnet_22 is ISavingsContractV4, Initializable, InitializableToken, ImmutableModule { using StableMath for uint256; // Core events for depositing and withdrawing event ExchangeRateUpdated(uint256 newExchangeRate, uint256 interestCollected); event SavingsDeposited(address indexed saver, uint256 savingsDeposited, uint256 creditsIssued); event CreditsRedeemed( address indexed redeemer, uint256 creditsRedeemed, uint256 savingsCredited ); event AutomaticInterestCollectionSwitched(bool automationEnabled); // Connector poking event PokerUpdated(address poker); event FractionUpdated(uint256 fraction); event ConnectorUpdated(address connector); event EmergencyUpdate(); event Poked(uint256 oldBalance, uint256 newBalance, uint256 interestDetected); event PokedRaw(); // Tracking events event Referral(address indexed referrer, address beneficiary, uint256 amount); // Rate between 'savings credits' and underlying // e.g. 1 credit (1e17) mulTruncate(exchangeRate) = underlying, starts at 10:1 // exchangeRate increases over time uint256 private constant startingRate = 1e17; uint256 public override exchangeRate; // Underlying asset is underlying IERC20 public immutable underlying; bool private automateInterestCollection; // Yield // Poker is responsible for depositing/withdrawing from connector address public poker; // Last time a poke was made uint256 public lastPoke; // Last known balance of the connector uint256 public lastBalance; // Fraction of capital assigned to the connector (100% = 1e18) uint256 public fraction; // Address of the current connector (all IConnectors are mStable validated) IConnector public connector; // How often do we allow pokes uint256 private constant POKE_CADENCE = 4 hours; // Max APY generated on the capital in the connector uint256 private constant MAX_APY = 4e18; uint256 private constant SECONDS_IN_YEAR = 365 days; // Proxy contract for easy redemption address public immutable unwrapper; constructor( address _nexus, address _underlying, address _unwrapper ) ImmutableModule(_nexus) { require(_underlying != address(0), "mAsset address is zero"); require(_unwrapper != address(0), "Unwrapper address is zero"); underlying = IERC20(_underlying); unwrapper = _unwrapper; } // Add these constants to bytecode at deploytime function initialize( address _poker, string calldata _nameArg, string calldata _symbolArg ) external initializer { InitializableToken._initialize(_nameArg, _symbolArg); require(_poker != address(0), "Invalid poker address"); poker = _poker; fraction = 2e17; automateInterestCollection = true; exchangeRate = startingRate; } /** @dev Only the savings managaer (pulled from Nexus) can execute this */ modifier onlySavingsManager() { require(msg.sender == _savingsManager(), "Only savings manager can execute"); _; } /*************************************** VIEW - E ****************************************/ /** * @dev Returns the underlying balance of a given user * @param _user Address of the user to check * @return balance Units of underlying owned by the user */ function balanceOfUnderlying(address _user) external view override returns (uint256 balance) { (balance, ) = _creditsToUnderlying(balanceOf(_user)); } /** * @dev Converts a given underlying amount into credits * @param _underlying Units of underlying * @return credits Credit units (a.k.a imUSD) */ function underlyingToCredits(uint256 _underlying) external view override returns (uint256 credits) { (credits, ) = _underlyingToCredits(_underlying); } /** * @dev Converts a given credit amount into underlying * @param _credits Units of credits * @return amount Corresponding underlying amount */ function creditsToUnderlying(uint256 _credits) external view override returns (uint256 amount) { (amount, ) = _creditsToUnderlying(_credits); } // Deprecated in favour of `balanceOf(address)` // Maintained for backwards compatibility // Returns the credit balance of a given user function creditBalances(address _user) external view override returns (uint256) { return balanceOf(_user); } /*************************************** INTEREST ****************************************/ /** * @dev Deposit interest (add to savings) and update exchange rate of contract. * Exchange rate is calculated as the ratio between new savings q and credits: * exchange rate = savings / credits * * @param _amount Units of underlying to add to the savings vault */ function depositInterest(uint256 _amount) external override onlySavingsManager { require(_amount > 0, "Must deposit something"); // Transfer the interest from sender to here require(underlying.transferFrom(msg.sender, address(this), _amount), "Must receive tokens"); // Calc new exchange rate, protect against initialisation case uint256 totalCredits = totalSupply(); if (totalCredits > 0) { // new exchange rate is relationship between _totalCredits & totalSavings // _totalCredits * exchangeRate = totalSavings // exchangeRate = totalSavings/_totalCredits (uint256 totalCollat, ) = _creditsToUnderlying(totalCredits); uint256 newExchangeRate = _calcExchangeRate(totalCollat + _amount, totalCredits); exchangeRate = newExchangeRate; emit ExchangeRateUpdated(newExchangeRate, _amount); } } /** @dev Enable or disable the automation of fee collection during deposit process */ function automateInterestCollectionFlag(bool _enabled) external onlyGovernor { automateInterestCollection = _enabled; emit AutomaticInterestCollectionSwitched(_enabled); } /*************************************** DEPOSIT ****************************************/ /** * @dev During a migration period, allow savers to deposit underlying here before the interest has been redirected * @param _underlying Units of underlying to deposit into savings vault * @param _beneficiary Immediately transfer the imUSD token to this beneficiary address * @return creditsIssued Units of credits (imUSD) issued */ function preDeposit(uint256 _underlying, address _beneficiary) external returns (uint256 creditsIssued) { require(exchangeRate == startingRate, "Can only use this method before streaming begins"); return _deposit(_underlying, _beneficiary, false); } /** * @dev Deposit the senders savings to the vault, and credit them internally with "credits". * Credit amount is calculated as a ratio of deposit amount and exchange rate: * credits = underlying / exchangeRate * We will first update the internal exchange rate by collecting any interest generated on the underlying. * @param _underlying Units of underlying to deposit into savings vault * @return creditsIssued Units of credits (imUSD) issued */ function depositSavings(uint256 _underlying) external override returns (uint256 creditsIssued) { return _deposit(_underlying, msg.sender, true); } /** * @dev Deposit the senders savings to the vault, and credit them internally with "credits". * Credit amount is calculated as a ratio of deposit amount and exchange rate: * credits = underlying / exchangeRate * We will first update the internal exchange rate by collecting any interest generated on the underlying. * @param _underlying Units of underlying to deposit into savings vault * @param _beneficiary Immediately transfer the imUSD token to this beneficiary address * @return creditsIssued Units of credits (imUSD) issued */ function depositSavings(uint256 _underlying, address _beneficiary) external override returns (uint256 creditsIssued) { return _deposit(_underlying, _beneficiary, true); } /** * @dev Overloaded `depositSavings` method with an optional referrer address. * @param _underlying Units of underlying to deposit into savings vault * @param _beneficiary Immediately transfer the imUSD token to this beneficiary address * @param _referrer Referrer address for this deposit * @return creditsIssued Units of credits (imUSD) issued */ function depositSavings( uint256 _underlying, address _beneficiary, address _referrer ) external override returns (uint256 creditsIssued) { emit Referral(_referrer, _beneficiary, _underlying); return _deposit(_underlying, _beneficiary, true); } /** * @dev Internally deposit the _underlying from the sender and credit the beneficiary with new imUSD */ function _deposit( uint256 _underlying, address _beneficiary, bool _collectInterest ) internal returns (uint256 creditsIssued) { creditsIssued = _transferAndMint(_underlying, _beneficiary, _collectInterest); } /*************************************** REDEEM ****************************************/ // Deprecated in favour of redeemCredits // Maintaining backwards compatibility, this fn minimics the old redeem fn, in which // credits are redeemed but the interest from the underlying is not collected. function redeem(uint256 _credits) external override returns (uint256 massetReturned) { require(_credits > 0, "Must withdraw something"); (, uint256 payout) = _redeem(_credits, true, true); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } return payout; } /** * @dev Redeem specific number of the senders "credits" in exchange for underlying. * Payout amount is calculated as a ratio of credits and exchange rate: * payout = credits * exchangeRate * @param _credits Amount of credits to redeem * @return massetReturned Units of underlying mAsset paid out */ function redeemCredits(uint256 _credits) external override returns (uint256 massetReturned) { require(_credits > 0, "Must withdraw something"); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } (, uint256 payout) = _redeem(_credits, true, true); return payout; } /** * @dev Redeem credits into a specific amount of underlying. * Credits needed to burn is calculated using: * credits = underlying / exchangeRate * @param _underlying Amount of underlying to redeem * @return creditsBurned Units of credits burned from sender */ function redeemUnderlying(uint256 _underlying) external override returns (uint256 creditsBurned) { require(_underlying > 0, "Must withdraw something"); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } // Ensure that the payout was sufficient (uint256 credits, uint256 massetReturned) = _redeem(_underlying, false, true); require(massetReturned == _underlying, "Invalid output"); return credits; } /** * @notice Redeem credits into a specific amount of underlying, unwrap * into a selected output asset, and send to a beneficiary * Credits needed to burn is calculated using: * credits = underlying / exchangeRate * @param _amount Units to redeem (either underlying or credit amount). * @param _isCreditAmt `true` if `amount` is in credits. eg imUSD. `false` if `amount` is in underlying. eg mUSD. * @param _minAmountOut Minimum amount of `output` tokens to unwrap for. This is to the same decimal places as the `output` token. * @param _output Asset to receive in exchange for the redeemed mAssets. This can be a bAsset or a fAsset. For example: - bAssets (USDC, DAI, sUSD or USDT) or fAssets (GUSD, BUSD, alUSD, FEI or RAI) for mainnet imUSD Vault. - bAssets (USDC, DAI or USDT) or fAsset FRAX for Polygon imUSD Vault. - bAssets (WBTC, sBTC or renBTC) or fAssets (HBTC or TBTCV2) for mainnet imBTC Vault. * @param _beneficiary Address to send `output` tokens to. * @param _router mAsset address if the output is a bAsset. Feeder Pool address if the output is a fAsset. * @param _isBassetOut `true` if `output` is a bAsset. `false` if `output` is a fAsset. * @return creditsBurned Units of credits burned from sender. eg imUSD or imBTC. * @return massetReturned Units of the underlying mAssets that were redeemed or swapped for the output tokens. eg mUSD or mBTC. * @return outputQuantity Units of `output` tokens sent to the beneficiary. */ function redeemAndUnwrap( uint256 _amount, bool _isCreditAmt, uint256 _minAmountOut, address _output, address _beneficiary, address _router, bool _isBassetOut ) external override returns ( uint256 creditsBurned, uint256 massetReturned, uint256 outputQuantity ) { require(_amount > 0, "Must withdraw something"); require(_output != address(0), "Output address is zero"); require(_beneficiary != address(0), "Beneficiary address is zero"); require(_router != address(0), "Router address is zero"); // Collect recent interest generated by basket and update exchange rate if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } // Ensure that the payout was sufficient (creditsBurned, massetReturned) = _redeem(_amount, _isCreditAmt, false); require( _isCreditAmt ? creditsBurned == _amount : massetReturned == _amount, "Invalid output" ); // Approve wrapper to spend contract's underlying; just for this tx underlying.approve(unwrapper, massetReturned); // Unwrap the underlying into `output` and transfer to `beneficiary` outputQuantity = IUnwrapper(unwrapper).unwrapAndSend( _isBassetOut, _router, address(underlying), _output, massetReturned, _minAmountOut, _beneficiary ); } /** * @dev Internally burn the credits and send the underlying to msg.sender */ function _redeem( uint256 _amt, bool _isCreditAmt, bool _transferUnderlying ) internal returns (uint256 creditsBurned, uint256 massetReturned) { // Centralise credit <> underlying calcs and minimise SLOAD count uint256 credits_; uint256 underlying_; uint256 exchangeRate_; // If the input is a credit amt, then calculate underlying payout and cache the exchangeRate if (_isCreditAmt) { credits_ = _amt; (underlying_, exchangeRate_) = _creditsToUnderlying(_amt); } // If the input is in underlying, then calculate credits needed to burn else { underlying_ = _amt; (credits_, exchangeRate_) = _underlyingToCredits(_amt); } _burnTransfer( underlying_, credits_, msg.sender, msg.sender, exchangeRate_, _transferUnderlying ); emit CreditsRedeemed(msg.sender, credits_, underlying_); return (credits_, underlying_); } struct ConnectorStatus { // Limit is the max amount of units allowed in the connector uint256 limit; // Derived balance of the connector uint256 inConnector; } /** * @dev Derives the units of collateral held in the connector * @param _data Struct containing data on balances * @param _exchangeRate Current system exchange rate * @return status Contains max amount of assets allowed in connector */ function _getConnectorStatus(CachedData memory _data, uint256 _exchangeRate) internal pure returns (ConnectorStatus memory) { // Total units of underlying collateralised uint256 totalCollat = _data.totalCredits.mulTruncate(_exchangeRate); // Max amount of underlying that can be held in the connector uint256 limit = totalCollat.mulTruncate(_data.fraction + 2e17); // Derives amount of underlying present in the connector uint256 inConnector = _data.rawBalance >= totalCollat ? 0 : totalCollat - _data.rawBalance; return ConnectorStatus(limit, inConnector); } /*************************************** YIELD - E ****************************************/ /** @dev Modifier allowing only the designated poker to execute the fn */ modifier onlyPoker() { require(msg.sender == poker, "Only poker can execute"); _; } /** * @dev External poke function allows for the redistribution of collateral between here and the * current connector, setting the ratio back to the defined optimal. */ function poke() external onlyPoker { CachedData memory cachedData = _cacheData(); _poke(cachedData, false); } /** * @dev Governance action to set the address of a new poker * @param _newPoker Address of the new poker */ function setPoker(address _newPoker) external onlyGovernor { require(_newPoker != address(0) && _newPoker != poker, "Invalid poker"); poker = _newPoker; emit PokerUpdated(_newPoker); } /** * @dev Governance action to set the percentage of assets that should be held * in the connector. * @param _fraction Percentage of assets that should be held there (where 20% == 2e17) */ function setFraction(uint256 _fraction) external onlyGovernor { require(_fraction <= 5e17, "Fraction must be <= 50%"); fraction = _fraction; CachedData memory cachedData = _cacheData(); _poke(cachedData, true); emit FractionUpdated(_fraction); } /** * @dev Governance action to set the address of a new connector, and move funds (if any) across. * @param _newConnector Address of the new connector */ function setConnector(address _newConnector) external onlyGovernor { // Withdraw all from previous by setting target = 0 CachedData memory cachedData = _cacheData(); cachedData.fraction = 0; _poke(cachedData, true); // Set new connector CachedData memory cachedDataNew = _cacheData(); connector = IConnector(_newConnector); _poke(cachedDataNew, true); emit ConnectorUpdated(_newConnector); } /** * @dev Governance action to perform an emergency withdraw of the assets in the connector, * should it be the case that some or all of the liquidity is trapped in. This causes the total * collateral in the system to go down, causing a hard refresh. */ function emergencyWithdraw(uint256 _withdrawAmount) external onlyGovernor { // withdraw _withdrawAmount from connection connector.withdraw(_withdrawAmount); // reset the connector connector = IConnector(address(0)); emit ConnectorUpdated(address(0)); // set fraction to 0 fraction = 0; emit FractionUpdated(0); // check total collateralisation of credits CachedData memory data = _cacheData(); // use rawBalance as the remaining liquidity in the connector is now written off _refreshExchangeRate(data.rawBalance, data.totalCredits, true); emit EmergencyUpdate(); } /*************************************** YIELD - I ****************************************/ /** @dev Internal poke function to keep the balance between connector and raw balance healthy */ function _poke(CachedData memory _data, bool _ignoreCadence) internal { require(_data.totalCredits > 0, "Must have something to poke"); // 1. Verify that poke cadence is valid, unless this is a manual action by governance uint256 currentTime = uint256(block.timestamp); uint256 timeSinceLastPoke = currentTime - lastPoke; require(_ignoreCadence || timeSinceLastPoke > POKE_CADENCE, "Not enough time elapsed"); lastPoke = currentTime; // If there is a connector, check the balance and settle to the specified fraction % IConnector connector_ = connector; if (address(connector_) != address(0)) { // 2. Check and verify new connector balance uint256 lastBalance_ = lastBalance; uint256 connectorBalance = connector_.checkBalance(); // Always expect the collateral in the connector to increase in value require(connectorBalance >= lastBalance_, "Invalid yield"); if (connectorBalance > 0) { // Validate the collection by ensuring that the APY is not ridiculous _validateCollection( connectorBalance, connectorBalance - lastBalance_, timeSinceLastPoke ); } // 3. Level the assets to Fraction (connector) & 100-fraction (raw) uint256 sum = _data.rawBalance + connectorBalance; uint256 ideal = sum.mulTruncate(_data.fraction); // If there is not enough mAsset in the connector, then deposit if (ideal > connectorBalance) { uint256 deposit_ = ideal - connectorBalance; underlying.approve(address(connector_), deposit_); connector_.deposit(deposit_); } // Else withdraw, if there is too much mAsset in the connector else if (connectorBalance > ideal) { // If fraction == 0, then withdraw everything if (ideal == 0) { connector_.withdrawAll(); sum = IERC20(underlying).balanceOf(address(this)); } else { connector_.withdraw(connectorBalance - ideal); } } // Else ideal == connectorBalance (e.g. 0), do nothing require(connector_.checkBalance() >= ideal, "Enforce system invariant"); // 4i. Refresh exchange rate and emit event lastBalance = ideal; _refreshExchangeRate(sum, _data.totalCredits, false); emit Poked(lastBalance_, ideal, connectorBalance - lastBalance_); } else { // 4ii. Refresh exchange rate and emit event lastBalance = 0; _refreshExchangeRate(_data.rawBalance, _data.totalCredits, false); emit PokedRaw(); } } /** * @dev Internal fn to refresh the exchange rate, based on the sum of collateral and the number of credits * @param _realSum Sum of collateral held by the contract * @param _totalCredits Total number of credits in the system * @param _ignoreValidation This is for use in the emergency situation, and ignores a decreasing exchangeRate */ function _refreshExchangeRate( uint256 _realSum, uint256 _totalCredits, bool _ignoreValidation ) internal { // Based on the current exchange rate, how much underlying is collateralised? (uint256 totalCredited, ) = _creditsToUnderlying(_totalCredits); // Require the amount of capital held to be greater than the previously credited units require(_ignoreValidation || _realSum >= totalCredited, "ExchangeRate must increase"); // Work out the new exchange rate based on the current capital uint256 newExchangeRate = _calcExchangeRate(_realSum, _totalCredits); exchangeRate = newExchangeRate; emit ExchangeRateUpdated( newExchangeRate, _realSum > totalCredited ? _realSum - totalCredited : 0 ); } /** * FORKED DIRECTLY FROM SAVINGSMANAGER.sol * --------------------------------------- * @dev Validates that an interest collection does not exceed a maximum APY. If last collection * was under 30 mins ago, simply check it does not exceed 10bps * @param _newBalance New balance of the underlying * @param _interest Increase in total supply since last collection * @param _timeSinceLastCollection Seconds since last collection */ function _validateCollection( uint256 _newBalance, uint256 _interest, uint256 _timeSinceLastCollection ) internal pure returns (uint256 extrapolatedAPY) { // Protect against division by 0 uint256 protectedTime = StableMath.max(1, _timeSinceLastCollection); uint256 oldSupply = _newBalance - _interest; uint256 percentageIncrease = _interest.divPrecisely(oldSupply); uint256 yearsSinceLastCollection = protectedTime.divPrecisely(SECONDS_IN_YEAR); extrapolatedAPY = percentageIncrease.divPrecisely(yearsSinceLastCollection); if (protectedTime > 30 minutes) { require(extrapolatedAPY < MAX_APY, "Interest protected from inflating past maxAPY"); } else { require(percentageIncrease < 1e15, "Interest protected from inflating past 10 Bps"); } } /*************************************** VIEW - I ****************************************/ struct CachedData { // SLOAD from 'fraction' uint256 fraction; // ERC20 balance of underlying, held by this contract // underlying.balanceOf(address(this)) uint256 rawBalance; // totalSupply() uint256 totalCredits; } /** * @dev Retrieves generic data to avoid duplicate SLOADs */ function _cacheData() internal view returns (CachedData memory) { uint256 balance = underlying.balanceOf(address(this)); return CachedData(fraction, balance, totalSupply()); } /** * @dev Converts masset amount into credits based on exchange rate * c = (masset / exchangeRate) + 1 */ function _underlyingToCredits(uint256 _underlying) internal view returns (uint256 credits, uint256 exchangeRate_) { // e.g. (1e20 * 1e18) / 1e18 = 1e20 // e.g. (1e20 * 1e18) / 14e17 = 7.1429e19 // e.g. 1 * 1e18 / 1e17 + 1 = 11 => 11 * 1e17 / 1e18 = 1.1e18 / 1e18 = 1 exchangeRate_ = exchangeRate; credits = _underlying.divPrecisely(exchangeRate_) + 1; } /** * @dev Works out a new exchange rate, given an amount of collateral and total credits * e = underlying / (credits-1) */ function _calcExchangeRate(uint256 _totalCollateral, uint256 _totalCredits) internal pure returns (uint256 _exchangeRate) { _exchangeRate = _totalCollateral.divPrecisely(_totalCredits - 1); } /** * @dev Converts credit amount into masset based on exchange rate * m = credits * exchangeRate */ function _creditsToUnderlying(uint256 _credits) internal view returns (uint256 underlyingAmount, uint256 exchangeRate_) { // e.g. (1e20 * 1e18) / 1e18 = 1e20 // e.g. (1e20 * 14e17) / 1e18 = 1.4e20 exchangeRate_ = exchangeRate; underlyingAmount = _credits.mulTruncate(exchangeRate_); } /*/////////////////////////////////////////////////////////////// IERC4626Vault //////////////////////////////////////////////////////////////*/ /** * @notice it must be an ERC-20 token contract. Must not revert. * * @return assetTokenAddress the address of the underlying asset token. eg mUSD or mBTC */ function asset() external view override returns (address assetTokenAddress) { return address(underlying); } /** * @return totalManagedAssets the total amount of the underlying asset tokens that is “managed” by Vault. */ function totalAssets() external view override returns (uint256 totalManagedAssets) { return underlying.balanceOf(address(this)); } /** * @notice The amount of shares that the Vault would exchange for the amount of assets provided, in an ideal scenario where all the conditions are met. * @param assets The amount of underlying assets to be convert to vault shares. * @return shares The amount of vault shares converted from the underlying assets. */ function convertToShares(uint256 assets) external view override returns (uint256 shares) { (shares, ) = _underlyingToCredits(assets); } /** * @notice The amount of assets that the Vault would exchange for the amount of shares provided, in an ideal scenario where all the conditions are met. * @param shares The amount of vault shares to be converted to the underlying assets. * @return assets The amount of underlying assets converted from the vault shares. */ function convertToAssets(uint256 shares) external view override returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); } /** * @notice The maximum number of underlying assets that caller can deposit. * caller Account that the assets will be transferred from. * @return maxAssets The maximum amount of underlying assets the caller can deposit. */ function maxDeposit( address /** caller **/ ) external pure override returns (uint256 maxAssets) { maxAssets = type(uint256).max; } /** * @notice Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions. * @param assets The amount of underlying assets to be transferred. * @return shares The amount of vault shares that will be minted. */ function previewDeposit(uint256 assets) external view override returns (uint256 shares) { require(assets > 0, "Must deposit something"); (shares, ) = _underlyingToCredits(assets); } /** * @notice Mint vault shares to receiver by transferring exact amount of underlying asset tokens from the caller. * Credit amount is calculated as a ratio of deposit amount and exchange rate: * credits = underlying / exchangeRate * We will first update the internal exchange rate by collecting any interest generated on the underlying. * Emits a {Deposit} event. * @param assets Units of underlying to deposit into savings vault. eg mUSD or mBTC * @param receiver The address to receive the Vault shares. * @return shares Units of credits issued. eg imUSD or imBTC */ function deposit(uint256 assets, address receiver) external override returns (uint256 shares) { shares = _transferAndMint(assets, receiver, true); } /** * * @notice Overloaded `deposit` method with an optional referrer address. * @param assets Units of underlying to deposit into savings vault. eg mUSD or mBTC * @param receiver Address to the new credits will be issued to. * @param referrer Referrer address for this deposit. * @return shares Units of credits issued. eg imUSD or imBTC */ function deposit( uint256 assets, address receiver, address referrer ) external override returns (uint256 shares) { shares = _transferAndMint(assets, receiver, true); emit Referral(referrer, receiver, assets); } /** * @notice The maximum number of vault shares that caller can mint. * caller Account that the underlying assets will be transferred from. * @return maxShares The maximum amount of vault shares the caller can mint. */ function maxMint( address /* caller */ ) external pure override returns (uint256 maxShares) { maxShares = type(uint256).max; } /** * @notice Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given current on-chain conditions. * @param shares The amount of vault shares to be minted. * @return assets The amount of underlying assests that will be transferred from the caller. */ function previewMint(uint256 shares) external view override returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); return assets; } /** * @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller. * Emits a {Deposit} event. * * @param shares The amount of vault shares to be minted. * @param receiver The account the vault shares will be minted to. * @return assets The amount of underlying assets that were transferred from the caller. */ function mint(uint256 shares, address receiver) external override returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); _transferAndMint(assets, receiver, true); } /** * @notice Mint exact amount of vault shares to the receiver by transferring enough underlying asset tokens from the caller. * @param shares The amount of vault shares to be minted. * @param receiver The account the vault shares will be minted to. * @param referrer Referrer address for this deposit. * @return assets The amount of underlying assets that were transferred from the caller. * Emits a {Deposit}, {Referral} events */ function mint( uint256 shares, address receiver, address referrer ) external override returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); _transferAndMint(assets, receiver, true); emit Referral(referrer, receiver, assets); } /** * @notice The maximum number of underlying assets that owner can withdraw. * @param owner Address that owns the underlying assets. * @return maxAssets The maximum amount of underlying assets the owner can withdraw. */ function maxWithdraw(address owner) external view override returns (uint256 maxAssets) { (maxAssets, ) = _creditsToUnderlying(balanceOf(owner)); } /** * @notice Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, given current on-chain conditions. * @param assets The amount of underlying assets to be withdrawn. * @return shares The amount of vault shares that will be burnt. */ function previewWithdraw(uint256 assets) external view override returns (uint256 shares) { (shares, ) = _underlyingToCredits(assets); } /** * @notice Burns enough vault shares from owner and transfers the exact amount of underlying asset tokens to the receiver. * Emits a {Withdraw} event. * * @param assets The amount of underlying assets to be withdrawn from the vault. * @param receiver The account that the underlying assets will be transferred to. * @param owner Account that owns the vault shares to be burnt. * @return shares The amount of vault shares that were burnt. */ function withdraw( uint256 assets, address receiver, address owner ) external override returns (uint256 shares) { require(assets > 0, "Must withdraw something"); uint256 _exchangeRate; if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } (shares, _exchangeRate) = _underlyingToCredits(assets); _burnTransfer(assets, shares, receiver, owner, _exchangeRate, true); } /** * @notice it must return a limited value if owner is subject to some withdrawal limit or timelock. must return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock. MAY be used in the previewRedeem or redeem methods for shares input parameter. must NOT revert. * * @param owner Address that owns the shares. * @return maxShares Total number of shares that owner can redeem. */ function maxRedeem(address owner) external view override returns (uint256 maxShares) { maxShares = balanceOf(owner); } /** * @notice Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, given current on-chain conditions. * * @return assets the exact amount of underlying assets that would be withdrawn by the caller if redeeming a given exact amount of Vault shares using the redeem method */ function previewRedeem(uint256 shares) external view override returns (uint256 assets) { (assets, ) = _creditsToUnderlying(shares); return assets; } /** * @notice Burns exact amount of vault shares from owner and transfers the underlying asset tokens to the receiver. * Emits a {Withdraw} event. * * @param shares The amount of vault shares to be burnt. * @param receiver The account the underlying assets will be transferred to. * @param owner The account that owns the vault shares to be burnt. * @return assets The amount of underlying assets that were transferred to the receiver. */ function redeem( uint256 shares, address receiver, address owner ) external override returns (uint256 assets) { require(shares > 0, "Must withdraw something"); uint256 _exchangeRate; if (automateInterestCollection) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(underlying)); } (assets, _exchangeRate) = _creditsToUnderlying(shares); _burnTransfer(assets, shares, receiver, owner, _exchangeRate, true); //transferAssets=true } /*/////////////////////////////////////////////////////////////// INTERNAL DEPOSIT/MINT //////////////////////////////////////////////////////////////*/ function _transferAndMint( uint256 assets, address receiver, bool _collectInterest ) internal returns (uint256 shares) { require(assets > 0, "Must deposit something"); require(receiver != address(0), "Invalid beneficiary address"); // Collect recent interest generated by basket and update exchange rate IERC20 mAsset = underlying; if (_collectInterest) { ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(mAsset)); } // Transfer tokens from sender to here require(mAsset.transferFrom(msg.sender, address(this), assets), "Must receive tokens"); // Calc how many credits they receive based on currentRatio (shares, ) = _underlyingToCredits(assets); // add credits to ERC20 balances _mint(receiver, shares); emit Deposit(msg.sender, receiver, assets, shares); emit SavingsDeposited(receiver, assets, shares); } /*/////////////////////////////////////////////////////////////// INTERNAL WITHDRAW/REDEEM //////////////////////////////////////////////////////////////*/ function _burnTransfer( uint256 assets, uint256 shares, address receiver, address owner, uint256 _exchangeRate, bool transferAssets ) internal { require(receiver != address(0), "Invalid beneficiary address"); // If caller is not the owner of the shares uint256 allowed = allowance(owner, msg.sender); if (msg.sender != owner && allowed != type(uint256).max) { require(shares <= allowed, "Amount exceeds allowance"); _approve(owner, msg.sender, allowed - shares); } // Burn required shares from the owner FIRST _burn(owner, shares); // Optionally, transfer tokens from here to receiver if (transferAssets) { require(underlying.transfer(receiver, assets), "Must send tokens"); emit Withdraw(msg.sender, receiver, owner, assets, shares); } // If this withdrawal pushes the portion of stored collateral in the `connector` over a certain // threshold (fraction + 20%), then this should trigger a _poke on the connector. This is to avoid // a situation in which there is a rush on withdrawals for some reason, causing the connector // balance to go up and thus having too large an exposure. CachedData memory cachedData = _cacheData(); ConnectorStatus memory status = _getConnectorStatus(cachedData, _exchangeRate); if (status.inConnector > status.limit) { _poke(cachedData, false); } } }
* @notice Overloaded `deposit` method with an optional referrer address. @param assets Units of underlying to deposit into savings vault. eg mUSD or mBTC @param receiver Address to the new credits will be issued to. @param referrer Referrer address for this deposit. @return shares Units of credits issued. eg imUSD or imBTC/
function deposit( uint256 assets, address receiver, address referrer ) external override returns (uint256 shares) { shares = _transferAndMint(assets, receiver, true); emit Referral(referrer, receiver, assets); }
11,800,869
[ 1, 4851, 4230, 1375, 323, 1724, 68, 707, 598, 392, 3129, 14502, 1758, 18, 225, 7176, 565, 27845, 434, 6808, 358, 443, 1724, 1368, 4087, 899, 9229, 18, 9130, 312, 3378, 40, 578, 312, 38, 15988, 225, 5971, 225, 5267, 358, 326, 394, 6197, 1282, 903, 506, 16865, 358, 18, 225, 14502, 225, 3941, 11110, 1758, 364, 333, 443, 1724, 18, 327, 24123, 282, 27845, 434, 6197, 1282, 16865, 18, 9130, 709, 3378, 40, 578, 709, 38, 15988, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 203, 3639, 2254, 5034, 7176, 16, 203, 3639, 1758, 5971, 16, 203, 3639, 1758, 14502, 203, 565, 262, 3903, 3849, 1135, 261, 11890, 5034, 24123, 13, 288, 203, 3639, 24123, 273, 389, 13866, 1876, 49, 474, 12, 9971, 16, 5971, 16, 638, 1769, 203, 3639, 3626, 3941, 29084, 12, 1734, 11110, 16, 5971, 16, 7176, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.4.25; library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } } contract DCGToken is ERC20, ERC20Detailed{ uint256 public constant initSupply = 1000000000; uint256 public constant tokenPrice = 40000; address internal _dev = 0x82875d05b23838C252E8F55d2A9fa1b34E57e344; // TODO constructor(string _name, string _symbol, uint8 _decimals) public ERC20Detailed(_name, _symbol, _decimals){ _mint(address(this), initSupply * 10 ** uint256(decimals())); } function() public payable { require(msg.value > 0); uint256 amount = msg.value; uint256 sellDGC = amount * tokenPrice; _dev.transfer(amount); IERC20(address(this)).transfer(msg.sender, sellDGC); } }
* @dev Returns the multiplication of two unsigned integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow./ Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. See: https:github.com/OpenZeppelin/openzeppelin-contracts/pull/522
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
201,387
[ 1, 1356, 326, 23066, 434, 2795, 9088, 12321, 16, 15226, 310, 603, 9391, 18, 9354, 2680, 358, 348, 7953, 560, 1807, 12176, 3726, 18, 29076, 30, 300, 5991, 1254, 2780, 9391, 18, 19, 31849, 14850, 30, 333, 353, 19315, 7294, 2353, 29468, 296, 69, 11, 486, 3832, 3634, 16, 1496, 326, 27641, 7216, 353, 13557, 309, 296, 70, 11, 353, 2546, 18432, 18, 2164, 30, 2333, 30, 6662, 18, 832, 19, 3678, 62, 881, 84, 292, 267, 19, 3190, 94, 881, 84, 292, 267, 17, 16351, 87, 19, 13469, 19, 25, 3787, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 202, 202, 430, 261, 69, 422, 374, 13, 288, 203, 1082, 202, 2463, 374, 31, 203, 202, 202, 97, 203, 203, 202, 202, 11890, 5034, 276, 273, 279, 380, 324, 31, 203, 202, 202, 6528, 12, 71, 342, 279, 422, 324, 16, 315, 9890, 10477, 30, 23066, 9391, 8863, 203, 202, 202, 2463, 276, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// @author Unstoppable Domains, Inc. // @date June 16th, 2021 pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol'; import './ChildRegistry.sol'; import './cns/ICNSRegistry.sol'; import './IUNSRegistry.sol'; import './RecordStorage.sol'; import './RootRegistry.sol'; import './metatx/ERC2771RegistryContext.sol'; import './metatx/UNSRegistryForwarder.sol'; /** * @title UNSRegistry v0.3 * @dev An ERC721 Token see https://eips.ethereum.org/EIPS/eip-721. With * additional functions so other trusted contracts to interact with the tokens. */ contract UNSRegistry is ERC721Upgradeable, ERC2771RegistryContext, RecordStorage, UNSRegistryForwarder, RootRegistry, ChildRegistry, IUNSRegistry { string public constant NAME = 'UNS: Registry'; string public constant VERSION = '0.3.0'; string internal _prefix; address internal _mintingManager; modifier onlyApprovedOrOwner(uint256 tokenId) { require(_isApprovedOrOwner(_msgSender(), tokenId), 'Registry: SENDER_IS_NOT_APPROVED_OR_OWNER'); _; } modifier onlyMintingManager() { require(_msgSender() == _mintingManager, 'Registry: SENDER_IS_NOT_MINTING_MANAGER'); _; } modifier protectTokenOperation(uint256 tokenId) { if (isTrustedForwarder(msg.sender)) { require(tokenId == _msgToken(), 'Registry: TOKEN_INVALID'); } else { _invalidateNonce(tokenId); } _; } function initialize(address mintingManager) public initializer { _mintingManager = mintingManager; __ERC721_init_unchained('Unstoppable Domains', 'UD'); __ERC2771RegistryContext_init_unchained(); __UNSRegistryForwarder_init_unchained(); } /// ERC721 Metadata extension function setTokenURIPrefix(string calldata prefix) external override onlyMintingManager { _prefix = prefix; emit NewURIPrefix(prefix); } /// Ownership function isApprovedOrOwner(address spender, uint256 tokenId) external view override returns (bool) { return _isApprovedOrOwner(spender, tokenId); } function approve(address to, uint256 tokenId) public override(IERC721Upgradeable, ERC721Upgradeable) protectTokenOperation(tokenId) { super.approve(to, tokenId); } /// Registry Constants function root() public pure returns (uint256) { return 0; } function childIdOf(uint256 tokenId, string calldata label) external pure override returns (uint256) { return _childId(tokenId, label); } function exists(uint256 tokenId) external view override(IUNSRegistry, IMintableERC721) returns (bool) { return _exists(tokenId); } /// Minting function mint( address to, uint256 tokenId, string calldata uri ) external override onlyMintingManager { _mint(to, tokenId, uri); } function safeMint( address to, uint256 tokenId, string calldata uri ) external override onlyMintingManager { _safeMint(to, tokenId, uri, ''); } function safeMint( address to, uint256 tokenId, string calldata uri, bytes calldata data ) external override onlyMintingManager { _safeMint(to, tokenId, uri, data); } function mintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values ) external override onlyMintingManager { _mint(to, tokenId, uri); _setMany(keys, values, tokenId); } function safeMintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values ) external override onlyMintingManager { _safeMintWithRecords(to, tokenId, uri, keys, values, ''); } function safeMintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values, bytes calldata data ) external override onlyMintingManager { _safeMintWithRecords(to, tokenId, uri, keys, values, data); } /// Transfering function setOwner(address to, uint256 tokenId) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _transfer(ownerOf(tokenId), to, tokenId); } function transferFrom( address from, address to, uint256 tokenId ) public override(IERC721Upgradeable, ERC721Upgradeable) onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reset(tokenId); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public override(IERC721Upgradeable, ERC721Upgradeable) onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reset(tokenId); _safeTransfer(from, to, tokenId, data); } // Token's migration from CNS // This is the keccak-256 hash of "uns.cns_registry" subtracted by 1 bytes32 internal constant _CNS_REGISTRY_SLOT = 0x8ffb960699dc2ba88f34d0e41c029c3c36c95149679fe1d0153a9582bec92378; function setCNSRegistry(address registry) external override { require( StorageSlotUpgradeable.getAddressSlot(_CNS_REGISTRY_SLOT).value == address(0), 'Registry: CNS_REGISTRY_NOT_EMPTY' ); StorageSlotUpgradeable.getAddressSlot(_CNS_REGISTRY_SLOT).value = registry; } function onERC721Received( address, address from, uint256 tokenId, bytes calldata data ) external override returns (bytes4) { if(_msgSender() == StorageSlotUpgradeable.getAddressSlot(_CNS_REGISTRY_SLOT).value) { ICNSRegistry(_msgSender()).burn(tokenId); if(data.length > 0 && abi.decode(data, (bool))) { _mint(address(this), tokenId); _deposit(from, tokenId); } else { _mint(from, tokenId); } return UNSRegistry.onERC721Received.selector; } revert('Registry: ERC721_RECEIVING_PROHIBITED'); } /// Burning function burn(uint256 tokenId) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reset(tokenId); _burn(tokenId); } /// Resolution function resolverOf(uint256 tokenId) external view override returns (address) { return _exists(tokenId) ? address(this) : address(0x0); } function set( string calldata key, string calldata value, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _set(key, value, tokenId); } function setMany( string[] calldata keys, string[] calldata values, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _setMany(keys, values, tokenId); } function setByHash( uint256 keyHash, string calldata value, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _setByHash(keyHash, value, tokenId); } function setManyByHash( uint256[] calldata keyHashes, string[] calldata values, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _setManyByHash(keyHashes, values, tokenId); } function reconfigure( string[] calldata keys, string[] calldata values, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reconfigure(keys, values, tokenId); } function reset(uint256 tokenId) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reset(tokenId); } /** * @dev See {IRootRegistry-depositToPolygon}. */ function depositToPolygon(uint256 tokenId) external override onlyApprovedOrOwner(tokenId) { // A workaround for MintableERC721Predicate // that requires a depositor to be equal to token owner: // https://github.com/maticnetwork/pos-portal/blob/88dbf0a88fd68fa11f7a3b9d36629930f6b93a05/contracts/root/TokenPredicates/MintableERC721Predicate.sol#L94 _transfer(_msgSender(), address(this), tokenId); _deposit(_msgSender(), tokenId); } /** * @dev See {IRootRegistry-withdrawFromPolygon}. */ function withdrawFromPolygon( bytes calldata inputData, uint256 tokenId, string[] calldata keys, string[] calldata values ) external override { _withdraw(inputData); require(ownerOf(tokenId) == _msgSender(), 'Registry: SENDER_IS_NOT_OWNER'); _setMany(keys, values, tokenId); } /** * @dev See {RootRegistry-mint(address,uint256)}. */ function mint(address user, uint256 tokenId) external override onlyPredicate { _mint(user, tokenId); } /** * @dev See {RootRegistry-mint(address,uint256,bytes)}. */ function mint(address user, uint256 tokenId, bytes calldata) external override onlyPredicate { _mint(user, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) { return super.supportsInterface(interfaceId); } /// Internal function _childId(uint256 tokenId, string memory label) internal pure returns (uint256) { require(bytes(label).length != 0, 'Registry: LABEL_EMPTY'); return uint256(keccak256(abi.encodePacked(tokenId, keccak256(abi.encodePacked(label))))); } function _mint( address to, uint256 tokenId, string memory uri ) internal { _mint(to, tokenId); emit NewURI(tokenId, uri); } function _safeMint( address to, uint256 tokenId, string memory uri, bytes memory data ) internal { _safeMint(to, tokenId, data); emit NewURI(tokenId, uri); } function _safeMintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values, bytes memory data ) internal { _safeMint(to, tokenId, uri, data); _setMany(keys, values, tokenId); } function _baseURI() internal view override(ERC721Upgradeable) returns (string memory) { return _prefix; } function _msgSender() internal view override(ContextUpgradeable, ERC2771RegistryContext) returns (address) { return super._msgSender(); } function _msgData() internal view override(ContextUpgradeable, ERC2771RegistryContext) returns (bytes calldata) { return super._msgData(); } // Reserved storage space to allow for layout changes in the future. uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // @author Unstoppable Domains, Inc. // @date December 20th, 2021 pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol'; import './IChildRegistry.sol'; abstract contract ChildRegistry is ERC721Upgradeable, IChildRegistry { // limit batching of tokens due to gas limit restrictions uint256 public constant BATCH_LIMIT = 20; // This is the keccak-256 hash of "uns.polygon.child_chain_manager" subtracted by 1 bytes32 internal constant _CHILD_CHAIN_MANAGER_SLOT = 0x8bea9a6f8afd34f4e29c585f854e0cc5161431bf5fc299d468454d33dce53b87; function setChildChainManager(address clientChainManager) external { require( StorageSlotUpgradeable.getAddressSlot(_CHILD_CHAIN_MANAGER_SLOT).value == address(0), 'Registry: CHILD_CHAIN_MANEGER_NOT_EMPTY' ); StorageSlotUpgradeable.getAddressSlot(_CHILD_CHAIN_MANAGER_SLOT).value = clientChainManager; } function deposit(address user, bytes calldata depositData) external override { require( _msgSender() == StorageSlotUpgradeable.getAddressSlot(_CHILD_CHAIN_MANAGER_SLOT).value, 'Registry: INSUFFICIENT_PERMISSIONS' ); // deposit single if (depositData.length == 32) { uint256 tokenId = abi.decode(depositData, (uint256)); _mint(user, tokenId); // deposit batch } else { uint256[] memory tokenIds = abi.decode(depositData, (uint256[])); uint256 length = tokenIds.length; for (uint256 i; i < length; i++) { _mint(user, tokenIds[i]); } } } function withdraw(uint256 tokenId) external override { require(_msgSender() == ownerOf(tokenId), "Registry: INVALID_TOKEN_OWNER"); _burn(tokenId); } function withdrawBatch(uint256[] calldata tokenIds) external override { uint256 length = tokenIds.length; require(length <= BATCH_LIMIT, "Registry: EXCEEDS_BATCH_LIMIT"); // Iteratively burn ERC721 tokens, for performing // batch withdraw for (uint256 i; i < length; i++) { uint256 tokenId = tokenIds[i]; require( _msgSender() == ownerOf(tokenId), string(abi.encodePacked("Registry: INVALID_TOKEN_OWNER ", tokenId)) ); _burn(tokenId); } // At last emit this event, which will be used // in MintableERC721 predicate contract on L1 // while verifying burn proof emit WithdrawnBatch(_msgSender(), tokenIds); } function withdrawWithMetadata(uint256 tokenId) external override { require(_msgSender() == ownerOf(tokenId), "Registry: INVALID_TOKEN_OWNER"); _burn(tokenId); } } // @author Unstoppable Domains, Inc. // @date June 16th, 2021 pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol'; interface ICNSRegistry is IERC721MetadataUpgradeable { function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); function resolverOf(uint256 tokenId) external view returns (address); function childIdOf(uint256 tokenId, string calldata label) external view returns (uint256); function burn(uint256 tokenId) external; } // @author Unstoppable Domains, Inc. // @date June 16th, 2021 pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol'; import './IERC1967.sol'; import './IRecordStorage.sol'; import './IRootRegistry.sol'; import './IChildRegistry.sol'; interface IUNSRegistry is IERC1967, IERC721MetadataUpgradeable, IERC721ReceiverUpgradeable, IRecordStorage, IRootRegistry, IChildRegistry { event NewURI(uint256 indexed tokenId, string uri); event NewURIPrefix(string prefix); /** * @dev Function to set the token URI Prefix for all tokens. * @param prefix string URI to assign */ function setTokenURIPrefix(string calldata prefix) external; /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); /** * @dev Gets the resolver of the specified token ID. * @param tokenId uint256 ID of the token to query the resolver of * @return address currently marked as the resolver of the given token ID */ function resolverOf(uint256 tokenId) external view returns (address); /** * @dev Provides child token (subdomain) of provided tokenId. * @param tokenId uint256 ID of the token * @param label label of subdomain (for `aaa.bbb.crypto` it will be `aaa`) */ function childIdOf(uint256 tokenId, string calldata label) external pure returns (uint256); /** * @dev Existence of token. * @param tokenId uint256 ID of the token */ function exists(uint256 tokenId) external override view returns (bool); /** * @dev Transfer domain ownership without resetting domain records. * @param to address of new domain owner * @param tokenId uint256 ID of the token to be transferred */ function setOwner(address to, uint256 tokenId) external; /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) external; /** * @dev Mints token. * @param to address to mint the new SLD to. * @param tokenId id of token. * @param uri domain URI. */ function mint( address to, uint256 tokenId, string calldata uri ) external; /** * @dev Safely mints token. * Implements a ERC721Reciever check unlike mint. * @param to address to mint the new SLD to. * @param tokenId id of token. * @param uri domain URI. */ function safeMint( address to, uint256 tokenId, string calldata uri ) external; /** * @dev Safely mints token. * Implements a ERC721Reciever check unlike mint. * @param to address to mint the new SLD to. * @param tokenId id of token. * @param uri domain URI. * @param data bytes data to send along with a safe transfer check */ function safeMint( address to, uint256 tokenId, string calldata uri, bytes calldata data ) external; /** * @dev Mints token with records * @param to address to mint the new SLD to * @param tokenId id of token * @param keys New record keys * @param values New record values * @param uri domain URI */ function mintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values ) external; /** * @dev Safely mints token with records * @param to address to mint the new SLD to * @param tokenId id of token * @param keys New record keys * @param values New record values * @param uri domain URI */ function safeMintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values ) external; /** * @dev Safely mints token with records * @param to address to mint the new SLD to * @param tokenId id of token * @param keys New record keys * @param values New record values * @param uri domain URI * @param data bytes data to send along with a safe transfer check */ function safeMintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values, bytes calldata data ) external; /** * @dev Stores CNS registry address. * It's one-time operation required to set CNS registry address. * UNS registry allows to receive ERC721 tokens only from CNS registry, * by supporting ERC721Receiver interface. * @param registry address of CNS registry contract */ function setCNSRegistry(address registry) external; } // @author Unstoppable Domains, Inc. // @date June 16th, 2021 pragma solidity ^0.8.0; import './IRecordStorage.sol'; import './KeyStorage.sol'; abstract contract RecordStorage is KeyStorage, IRecordStorage { /// @dev mapping of presetIds to keyIds to values mapping(uint256 => mapping(uint256 => string)) internal _records; /// @dev mapping of tokenIds to presetIds mapping(uint256 => uint256) internal _tokenPresets; function get(string calldata key, uint256 tokenId) external view override returns (string memory value) { value = _get(key, tokenId); } function getMany(string[] calldata keys, uint256 tokenId) external view override returns (string[] memory values) { values = new string[](keys.length); for (uint256 i = 0; i < keys.length; i++) { values[i] = _get(keys[i], tokenId); } } function getByHash(uint256 keyHash, uint256 tokenId) external view override returns (string memory key, string memory value) { (key, value) = _getByHash(keyHash, tokenId); } function getManyByHash(uint256[] calldata keyHashes, uint256 tokenId) external view override returns (string[] memory keys, string[] memory values) { keys = new string[](keyHashes.length); values = new string[](keyHashes.length); for (uint256 i = 0; i < keyHashes.length; i++) { (keys[i], values[i]) = _getByHash(keyHashes[i], tokenId); } } function _presetOf(uint256 tokenId) internal view virtual returns (uint256) { return _tokenPresets[tokenId] == 0 ? tokenId : _tokenPresets[tokenId]; } function _set( string calldata key, string calldata value, uint256 tokenId ) internal { uint256 keyHash = uint256(keccak256(abi.encodePacked(key))); _addKey(keyHash, key); _set(keyHash, key, value, tokenId); } function _setMany( string[] calldata keys, string[] calldata values, uint256 tokenId ) internal { for (uint256 i = 0; i < keys.length; i++) { _set(keys[i], values[i], tokenId); } } function _setByHash( uint256 keyHash, string calldata value, uint256 tokenId ) internal { require(_existsKey(keyHash), 'RecordStorage: KEY_NOT_FOUND'); _set(keyHash, getKey(keyHash), value, tokenId); } function _setManyByHash( uint256[] calldata keyHashes, string[] calldata values, uint256 tokenId ) internal { for (uint256 i = 0; i < keyHashes.length; i++) { _setByHash(keyHashes[i], values[i], tokenId); } } function _reconfigure( string[] calldata keys, string[] calldata values, uint256 tokenId ) internal { _reset(tokenId); _setMany(keys, values, tokenId); } function _reset(uint256 tokenId) internal { _tokenPresets[tokenId] = uint256(keccak256(abi.encodePacked(_presetOf(tokenId)))); emit ResetRecords(tokenId); } function _get(string memory key, uint256 tokenId) private view returns (string memory) { return _get(uint256(keccak256(abi.encodePacked(key))), tokenId); } function _getByHash(uint256 keyHash, uint256 tokenId) private view returns (string memory key, string memory value) { key = getKey(keyHash); value = _get(keyHash, tokenId); } function _get(uint256 keyHash, uint256 tokenId) private view returns (string memory) { return _records[_presetOf(tokenId)][keyHash]; } function _set( uint256 keyHash, string memory key, string memory value, uint256 tokenId ) private { if (bytes(_records[_presetOf(tokenId)][keyHash]).length == 0) { emit NewKey(tokenId, key, key); } _records[_presetOf(tokenId)][keyHash] = value; emit Set(tokenId, key, value, key, value); } } // @author Unstoppable Domains, Inc. // @date December 20th, 2021 pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol'; import './IRootRegistry.sol'; import './@maticnetwork/IRootChainManager.sol'; import './@maticnetwork/RootChainManagerStorage.sol'; abstract contract RootRegistry is ERC721Upgradeable, IRootRegistry { // This is the keccak-256 hash of "uns.polygon.root_chain_manager" subtracted by 1 bytes32 internal constant _ROOT_CHAIN_MANAGER_SLOT = 0xbe2bb46ac0377341a1ec5c3116d70fd5029d704bd46292e58f6265dd177ebafe; modifier onlyPredicate() { require(_msgSender() == _getPredicate(), 'Registry: INSUFFICIENT_PERMISSIONS'); _; } function setRootChainManager(address rootChainManager) external override { require( StorageSlotUpgradeable.getAddressSlot(_ROOT_CHAIN_MANAGER_SLOT).value == address(0), 'Registry: ROOT_CHAIN_MANEGER_NOT_EMPTY' ); StorageSlotUpgradeable.getAddressSlot(_ROOT_CHAIN_MANAGER_SLOT).value = rootChainManager; } function _deposit(address to, uint256 tokenId) internal { address predicate = _getPredicate(); _approve(predicate, tokenId); address manager = StorageSlotUpgradeable.getAddressSlot(_ROOT_CHAIN_MANAGER_SLOT).value; IRootChainManager(manager).depositFor(to, address(this), abi.encode(tokenId)); } function _withdraw(bytes calldata inputData) internal { address manager = StorageSlotUpgradeable.getAddressSlot(_ROOT_CHAIN_MANAGER_SLOT).value; IRootChainManager(manager).exit(inputData); } function _getPredicate() internal view returns(address predicate) { address manager = StorageSlotUpgradeable.getAddressSlot(_ROOT_CHAIN_MANAGER_SLOT).value; bytes32 tokenType = RootChainManagerStorage(manager).tokenToType(address(this)); predicate = RootChainManagerStorage(manager).typeToPredicate(tokenType); } } // @author Unstoppable Domains, Inc. // @date June 16th, 2021 pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; /** * @dev https://eips.ethereum.org/EIPS/eip-2771[EIP 2771] is a standard for native meta transactions. * * A base contract to be inherited by any contract that want to receive forwarded transactions. * The contract designed to be stateless, it supports a scenario when a inherited contract is * TrustedForwarder and Recipient at the same time. * * The contract supports token based nonce, that is why standard calldata extended by tokenId. * * Forwarded calldata layout: {bytes:data}{address:from}{uint256:tokenId} */ abstract contract ERC2771RegistryContext is Initializable, ContextUpgradeable { // solhint-disable-next-line func-name-mixedcase function __ERC2771RegistryContext_init() internal initializer { __Context_init_unchained(); __ERC2771RegistryContext_init_unchained(); } // solhint-disable-next-line func-name-mixedcase function __ERC2771RegistryContext_init_unchained() internal initializer {} /** * @dev Return bool whether provided address is the trusted forwarder. */ function isTrustedForwarder(address forwarder) public view virtual returns (bool) { return forwarder == address(this); } /** * @dev Return the tokenId of this call. * If the call came through our trusted forwarder, return the original tokenId. * otherwise, return zero tokenId. */ function _msgToken() internal view virtual returns (uint256 tokenId) { if (isTrustedForwarder(msg.sender)) { assembly { tokenId := calldataload(sub(calldatasize(), 32)) } } } /** * @dev Return the sender of this call. * If the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * Should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal view virtual override returns (address sender) { if (isTrustedForwarder(msg.sender)) { // The assembly code is more direct than the Solidity version using `abi.decode`. assembly { sender := shr(96, calldataload(sub(calldatasize(), 52))) } } else { return super._msgSender(); } } /** * @dev Return the data of this call. * If the call came through our trusted forwarder, return the original data. * otherwise, return `msg.data`. * Should be used in the contract anywhere instead of msg.data */ function _msgData() internal view virtual override returns (bytes calldata) { if (isTrustedForwarder(msg.sender)) { return msg.data[:msg.data.length - 52]; } else { return super._msgData(); } } uint256[50] private __gap; } // @author Unstoppable Domains, Inc. // @date June 16th, 2021 pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; import './BaseForwarder.sol'; abstract contract EIP712UpgradeableGap { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private _HASHED_VERSION; uint256[50] private __gap; /* solhint-enable var-name-mixedcase */ } /** * @dev https://eips.ethereum.org/EIPS/eip-2771[EIP 2771] is a standard for native meta transactions. * * A base contract to be inherited by any contract that want to forward transactions. */ abstract contract UNSRegistryForwarder is Initializable, EIP712UpgradeableGap, BaseForwarder { mapping(uint256 => uint256) private _nonces; // solhint-disable-next-line func-name-mixedcase function __UNSRegistryForwarder_init() internal initializer { __UNSRegistryForwarder_init_unchained(); } // solhint-disable-next-line func-name-mixedcase function __UNSRegistryForwarder_init_unchained() internal initializer {} function nonceOf(uint256 tokenId) public view override returns (uint256) { return _nonces[tokenId]; } function verify(ForwardRequest calldata req, bytes calldata signature) public view override returns (bool) { return _verify(req, address(this), signature); } function execute(ForwardRequest calldata req, bytes calldata signature) public override returns (bytes memory) { uint256 gas = gasleft(); require(verify(req, signature), 'UNSRegistryForwarder: SIGNATURE_INVALID'); return _execute(req.from, address(this), req.tokenId, gas, req.data, signature); } function _invalidateNonce(uint256 tokenId) internal override { _nonces[tokenId] = _nonces[tokenId] + 1; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // @author Unstoppable Domains, Inc. // @date December 21st, 2021 pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol'; import './@maticnetwork/IChildToken.sol'; interface IChildRegistry is IERC721Upgradeable, IChildToken { event WithdrawnBatch(address indexed user, uint256[] tokenIds); /** * @notice called when user wants to withdraw token back to root chain * @dev Should handle withraw by burning user's token. * This transaction will be verified when exiting on root chain * @param tokenId tokenId to withdraw */ function withdraw(uint256 tokenId) external; /** * @notice called when user wants to withdraw multiple tokens back to root chain * @dev Should burn user's tokens. This transaction will be verified when exiting on root chain * @param tokenIds tokenId list to withdraw */ function withdrawBatch(uint256[] calldata tokenIds) external; /** * @notice called when user wants to withdraw token back to root chain with token URI * @dev Should handle withraw by burning user's token. * This transaction will be verified when exiting on root chain * @param tokenId tokenId to withdraw */ function withdrawWithMetadata(uint256 tokenId) external; } pragma solidity ^0.8.0; interface IChildToken { /** * @notice called when token is deposited on root chain * @dev Should be callable only by ChildChainManager * Should handle deposit by minting the required tokenId for user * Make sure minting is done only by this function * @param user user address for whom deposit is being done * @param depositData abi encoded tokenId */ function deposit(address user, bytes calldata depositData) external; } // @author Unstoppable Domains, Inc. // @date December 22nd, 2021 pragma solidity ^0.8.0; interface IERC1967 { /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); } // @author Unstoppable Domains, Inc. // @date June 16th, 2021 pragma solidity ^0.8.0; import './IRecordReader.sol'; interface IRecordStorage is IRecordReader { event Set(uint256 indexed tokenId, string indexed keyIndex, string indexed valueIndex, string key, string value); event NewKey(uint256 indexed tokenId, string indexed keyIndex, string key); event ResetRecords(uint256 indexed tokenId); /** * @dev Set record by key * @param key The key set the value of * @param value The value to set key to * @param tokenId ERC-721 token id to set */ function set( string calldata key, string calldata value, uint256 tokenId ) external; /** * @dev Set records by keys * @param keys The keys set the values of * @param values Records values * @param tokenId ERC-721 token id of the domain */ function setMany( string[] memory keys, string[] memory values, uint256 tokenId ) external; /** * @dev Set record by key hash * @param keyHash The key hash set the value of * @param value The value to set key to * @param tokenId ERC-721 token id to set */ function setByHash( uint256 keyHash, string calldata value, uint256 tokenId ) external; /** * @dev Set records by key hashes * @param keyHashes The key hashes set the values of * @param values Records values * @param tokenId ERC-721 token id of the domain */ function setManyByHash( uint256[] calldata keyHashes, string[] calldata values, uint256 tokenId ) external; /** * @dev Reset all domain records and set new ones * @param keys New record keys * @param values New record values * @param tokenId ERC-721 token id of the domain */ function reconfigure( string[] memory keys, string[] memory values, uint256 tokenId ) external; /** * @dev Function to reset all existing records on a domain. * @param tokenId ERC-721 token id to set. */ function reset(uint256 tokenId) external; } // @author Unstoppable Domains, Inc. // @date December 21st, 2021 pragma solidity ^0.8.0; import './@maticnetwork/IMintableERC721.sol'; interface IRootRegistry is IMintableERC721 { /** * @dev Stores RootChainManager address. * It's one-time operation required to set RootChainManager address. * RootChainManager is a contract responsible for bridging Ethereum * and Polygon networks. * @param rootChainManager address of RootChainManager contract */ function setRootChainManager(address rootChainManager) external; /** * @dev Deposits token to Polygon through RootChainManager contract. * @param tokenId id of token */ function depositToPolygon(uint256 tokenId) external; /** * @dev Exit from Polygon through RootChainManager contract. * It withdraws token with records update. * @param tokenId id of token * @param keys New record keys * @param values New record values */ function withdrawFromPolygon( bytes calldata inputData, uint256 tokenId, string[] calldata keys, string[] calldata values ) external; } // @author Unstoppable Domains, Inc. // @date June 16th, 2021 pragma solidity ^0.8.0; interface IRecordReader { /** * @dev Function to get record. * @param key The key to query the value of. * @param tokenId The token id to fetch. * @return The value string. */ function get(string calldata key, uint256 tokenId) external view returns (string memory); /** * @dev Function to get multiple record. * @param keys The keys to query the value of. * @param tokenId The token id to fetch. * @return The values. */ function getMany(string[] calldata keys, uint256 tokenId) external view returns (string[] memory); /** * @dev Function get value by provied key hash. * @param keyHash The key to query the value of. * @param tokenId The token id to set. */ function getByHash(uint256 keyHash, uint256 tokenId) external view returns (string memory key, string memory value); /** * @dev Function get values by provied key hashes. * @param keyHashes The key to query the value of. * @param tokenId The token id to set. */ function getManyByHash(uint256[] calldata keyHashes, uint256 tokenId) external view returns (string[] memory keys, string[] memory values); } pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol'; interface IMintableERC721 is IERC721Upgradeable { /** * @notice called by predicate contract to mint tokens while withdrawing * @dev Should be callable only by MintableERC721Predicate * Make sure minting is done only by this function * @param user user address for whom token is being minted * @param tokenId tokenId being minted */ function mint(address user, uint256 tokenId) external; /** * @notice called by predicate contract to mint tokens while withdrawing with metadata from L2 * @dev Should be callable only by MintableERC721Predicate * Make sure minting is only done either by this function/ 👆 * @param user user address for whom token is being minted * @param tokenId tokenId being minted * @param metaData Associated token metadata, to be decoded & set using `setTokenMetadata` */ function mint(address user, uint256 tokenId, bytes calldata metaData) external; /** * @notice check if token already exists, return true if it does exist * @dev this check will be used by the predicate to determine if the token needs to be minted or transfered * @param tokenId tokenId being checked */ function exists(uint256 tokenId) external view returns (bool); } // @author Unstoppable Domains, Inc. // @date June 16th, 2021 pragma solidity ^0.8.0; abstract contract KeyStorage { mapping(uint256 => string) private _keys; function getKey(uint256 keyHash) public view returns (string memory) { return _keys[keyHash]; } function getKeys(uint256[] calldata hashes) public view returns (string[] memory values) { values = new string[](hashes.length); for (uint256 i = 0; i < hashes.length; i++) { values[i] = getKey(hashes[i]); } } function addKey(string memory key) external { _addKey(uint256(keccak256(abi.encodePacked(key))), key); } function _existsKey(uint256 keyHash) internal view returns (bool) { return bytes(_keys[keyHash]).length > 0; } function _addKey(uint256 keyHash, string memory key) internal { if (!_existsKey(keyHash)) { _keys[keyHash] = key; } } } pragma solidity ^0.8.0; interface IRootChainManager { event TokenMapped( address indexed rootToken, address indexed childToken, bytes32 indexed tokenType ); event PredicateRegistered( bytes32 indexed tokenType, address indexed predicateAddress ); function registerPredicate(bytes32 tokenType, address predicateAddress) external; function mapToken( address rootToken, address childToken, bytes32 tokenType ) external; function cleanMapToken( address rootToken, address childToken ) external; function remapToken( address rootToken, address childToken, bytes32 tokenType ) external; function depositEtherFor(address user) external payable; function depositFor( address user, address rootToken, bytes calldata depositData ) external; function exit(bytes calldata inputData) external; } pragma solidity ^0.8.0; abstract contract RootChainManagerStorage { mapping(bytes32 => address) public typeToPredicate; mapping(address => bytes32) public tokenToType; } // @author Unstoppable Domains, Inc. // @date August 12th, 2021 pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol'; import './IForwarder.sol'; abstract contract BaseForwarder is IForwarder { using ECDSAUpgradeable for bytes32; function _verify( ForwardRequest memory req, address target, bytes memory signature ) internal view virtual returns (bool) { uint256 nonce = this.nonceOf(req.tokenId); address signer = _recover(keccak256(req.data), target, nonce, signature); return nonce == req.nonce && signer == req.from; } function _recover( bytes32 digest, address target, uint256 nonce, bytes memory signature ) internal pure virtual returns (address signer) { return keccak256(abi.encodePacked(digest, target, nonce)).toEthSignedMessageHash().recover(signature); } function _execute( address from, address to, uint256 tokenId, uint256 gas, bytes memory data, bytes memory signature ) internal virtual returns (bytes memory) { _invalidateNonce(tokenId); (bool success, bytes memory returndata) = to.call{gas: gas}(_buildData(from, tokenId, data, signature)); // Validate that the relayer has sent enough gas for the call. // See https://ronan.eth.link/blog/ethereum-gas-dangers/ assert(gasleft() > gas / 63); return _verifyCallResult(success, returndata, 'BaseForwarder: CALL_FAILED'); } function _invalidateNonce( uint256 /* tokenId */ ) internal virtual {} function _buildData( address from, uint256 tokenId, bytes memory data, bytes memory /* signature */ ) internal view virtual returns (bytes memory) { return abi.encodePacked(data, from, tokenId); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly //solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // @author Unstoppable Domains, Inc. // @date August 11th, 2021 pragma solidity ^0.8.0; interface IForwarder { struct ForwardRequest { address from; uint256 nonce; uint256 tokenId; bytes data; } function nonceOf(uint256 tokenId) external view returns (uint256); function verify(ForwardRequest calldata req, bytes calldata signature) external view returns (bool); function execute(ForwardRequest calldata req, bytes calldata signature) external returns (bytes memory); }
deposit single deposit batch
function deposit(address user, bytes calldata depositData) external override { require( _msgSender() == StorageSlotUpgradeable.getAddressSlot(_CHILD_CHAIN_MANAGER_SLOT).value, 'Registry: INSUFFICIENT_PERMISSIONS' ); if (depositData.length == 32) { uint256 tokenId = abi.decode(depositData, (uint256)); _mint(user, tokenId); uint256[] memory tokenIds = abi.decode(depositData, (uint256[])); uint256 length = tokenIds.length; for (uint256 i; i < length; i++) { _mint(user, tokenIds[i]); } } }
12,199,001
[ 1, 323, 1724, 2202, 443, 1724, 2581, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 2867, 729, 16, 1731, 745, 892, 443, 1724, 751, 13, 3903, 3849, 288, 203, 3639, 2583, 12, 203, 5411, 389, 3576, 12021, 1435, 422, 5235, 8764, 10784, 429, 18, 588, 1887, 8764, 24899, 27043, 67, 1792, 6964, 67, 19402, 67, 55, 1502, 56, 2934, 1132, 16, 203, 5411, 296, 4243, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 23330, 55, 11, 203, 3639, 11272, 203, 203, 3639, 309, 261, 323, 1724, 751, 18, 2469, 422, 3847, 13, 288, 203, 5411, 2254, 5034, 1147, 548, 273, 24126, 18, 3922, 12, 323, 1724, 751, 16, 261, 11890, 5034, 10019, 203, 5411, 389, 81, 474, 12, 1355, 16, 1147, 548, 1769, 203, 203, 5411, 2254, 5034, 8526, 3778, 1147, 2673, 273, 24126, 18, 3922, 12, 323, 1724, 751, 16, 261, 11890, 5034, 63, 5717, 1769, 203, 5411, 2254, 5034, 769, 273, 1147, 2673, 18, 2469, 31, 203, 5411, 364, 261, 11890, 5034, 277, 31, 277, 411, 769, 31, 277, 27245, 288, 203, 7734, 389, 81, 474, 12, 1355, 16, 1147, 2673, 63, 77, 19226, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/56/0xf08065965FEF74e6DE05aDf4343669592f400420/sources/project_/contracts/Four.sol
split the contract balance into halves swap tokens for ETH how much ETH did we just swap into? add liquidity to uniswap
function swapAndLiquify(uint256 tokens) private { uint256 half = tokens.div(2); uint256 otherHalf = tokens.sub(half); uint256 ethBalanceBefore = address(this).balance; uint256 ethBalanceAfter = address(this).balance; uint256 newBalanceETH = ethBalanceAfter.sub(ethBalanceBefore); addLiquidity(half, newBalanceETH); emit SwapAndLiquify(half, newBalanceETH, otherHalf); }
3,225,860
[ 1, 4939, 326, 6835, 11013, 1368, 19514, 3324, 7720, 2430, 364, 512, 2455, 3661, 9816, 512, 2455, 5061, 732, 2537, 7720, 1368, 35, 527, 4501, 372, 24237, 358, 640, 291, 91, 438, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 1876, 48, 18988, 1164, 12, 11890, 5034, 2430, 13, 3238, 288, 203, 3639, 2254, 5034, 8816, 273, 2430, 18, 2892, 12, 22, 1769, 203, 3639, 2254, 5034, 1308, 16168, 273, 2430, 18, 1717, 12, 20222, 1769, 203, 3639, 2254, 5034, 13750, 13937, 4649, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 203, 203, 203, 3639, 2254, 5034, 13750, 13937, 4436, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 203, 3639, 2254, 5034, 394, 13937, 1584, 44, 273, 13750, 13937, 4436, 18, 1717, 12, 546, 13937, 4649, 1769, 203, 203, 3639, 527, 48, 18988, 24237, 12, 20222, 16, 394, 13937, 1584, 44, 1769, 203, 203, 3639, 3626, 12738, 1876, 48, 18988, 1164, 12, 20222, 16, 394, 13937, 1584, 44, 16, 1308, 16168, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; import "zeppelin-solidity/contracts/crowdsale/FinalizableCrowdsale.sol"; import "./TokensCappedCrowdsale.sol"; import "./PausableCrowdsale.sol"; import "./BonusCrowdsale.sol"; import "./PreBOUToken.sol"; /** * @dev Main BoutsPro Crowdsale contract. * Based on references from OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity * */ contract BoutsCrowdsale is MintableToken,FinalizableCrowdsale, TokensCappedCrowdsale(BoutsCrowdsale.CAP), PausableCrowdsale(true), BonusCrowdsale(BoutsCrowdsale.TOKEN_USDCENT_PRICE) { // Constants uint256 public constant DECIMALS = 18; uint256 public constant CAP = 2 * (10**9) * (10**DECIMALS); // 2B BOUT uint256 public constant BOUTSPRO_AMOUNT = 1 * (10**9) * (10**DECIMALS); // 1B BOUT uint256 public constant TOKEN_USDCENT_PRICE = 10; // $0.10 // Variables address public remainingTokensWallet; address public presaleWallet; /** * @dev Sets BOUT to Ether rate. Will be called multiple times durign the crowdsale to adjsut the rate * since BOUT cost is fixed in USD, but USD/ETH rate is changing * @param _rate defines BOUT/ETH rate: 1 ETH = _rate BOUTs */ function setRate(uint256 _rate) external onlyOwner { require(_rate != 0x0); rate = _rate; RateChange(_rate); } /** * @dev Allows to adjust the crowdsale end time */ function setEndTime(uint256 _endTime) external onlyOwner { require(!isFinalized); require(_endTime >= startTime); require(_endTime >= now); endTime = _endTime; } /** * @dev Sets the wallet to forward ETH collected funds */ function setWallet(address _wallet) external onlyOwner { require(_wallet != 0x0); wallet = _wallet; } /** * @dev Sets the wallet to hold unsold tokens at the end of ICO */ function setRemainingTokensWallet(address _remainingTokensWallet) external onlyOwner { require(_remainingTokensWallet != 0x0); remainingTokensWallet = _remainingTokensWallet; } // Events event RateChange(uint256 rate); /** * @dev Contructor * @param _startTime startTime of crowdsale * @param _endTime endTime of crowdsale * @param _rate BOUT / ETH rate * @param _wallet wallet to forward the collected funds * @param _remainingTokensWallet wallet to hold the unsold tokens * @param _boutsProWallet wallet to hold the initial 1B tokens of BoutsPro */ function BoutsCrowdsale( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _remainingTokensWallet, address _boutsProWallet ) public Crowdsale(_startTime, _endTime, _rate, _wallet) { remainingTokensWallet = _remainingTokensWallet; presaleWallet = this; // allocate tokens to BoutsPro mintTokens(_boutsProWallet, BOUTSPRO_AMOUNT); } // Overrided methods /** * @dev Creates token contract for ICO * @return ERC20 contract associated with the crowdsale */ function createTokenContract() internal returns(MintableToken) { PreBOUToken token = new PreBOUToken(); token.pause(); return token; } /** * @dev Finalizes the crowdsale */ function finalization() internal { super.finalization(); // Mint tokens up to CAP if (token.totalSupply() < tokensCap) { uint tokens = tokensCap.sub(token.totalSupply()); token.mint(remainingTokensWallet, tokens); } // disable minting of BOUTs token.finishMinting(); // take onwership over BOUToken contract token.transferOwnership(owner); } // Owner methods /** * @dev Helper to Pause BOUToken */ function pauseTokens() public onlyOwner { PreBOUToken(token).pause(); } /** * @dev Helper to UnPause BOUToken */ function unpauseTokens() public onlyOwner { PreBOUToken(token).unpause(); } /** * @dev Allocates tokens from preSale to a special wallet. Called once as part of crowdsale setup */ function mintPresaleTokens(uint256 tokens) public onlyOwner { mintTokens(presaleWallet, tokens); presaleWallet = 0; } /** * @dev Transfer presaled tokens even on paused token contract */ function transferPresaleTokens(address destination, uint256 amount) public onlyOwner { unpauseTokens(); token.transfer(destination, amount); pauseTokens(); } // /** * @dev Allocates tokens for investors that contributed from website. These include * white listed investors and investors paying with BTC/QTUM/LTC */ function mintTokens(address beneficiary, uint256 tokens) public onlyOwner { require(beneficiary != 0x0); require(tokens > 0); require(now <= endTime); // Crowdsale (without startTime check) require(!isFinalized); // FinalizableCrowdsale require(token.totalSupply().add(tokens) <= tokensCap); // TokensCappedCrowdsale token.mint(beneficiary, tokens); } }
* @dev Finalizes the crowdsale/ Mint tokens up to CAP
function finalization() internal { super.finalization(); if (token.totalSupply() < tokensCap) { uint tokens = tokensCap.sub(token.totalSupply()); token.mint(remainingTokensWallet, tokens); } }
12,685,423
[ 1, 7951, 3128, 326, 276, 492, 2377, 5349, 19, 490, 474, 2430, 731, 358, 29720, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 727, 1588, 1435, 2713, 288, 203, 3639, 2240, 18, 6385, 1588, 5621, 203, 203, 3639, 309, 261, 2316, 18, 4963, 3088, 1283, 1435, 411, 2430, 4664, 13, 288, 203, 5411, 2254, 2430, 273, 2430, 4664, 18, 1717, 12, 2316, 18, 4963, 3088, 1283, 10663, 203, 5411, 1147, 18, 81, 474, 12, 17956, 5157, 16936, 16, 2430, 1769, 203, 3639, 289, 203, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xeC49eFaf47BDfb123022F6D50a11CEc937FF8e89/sources/SecretNote.sol
Convenience method for a pairing check for four pairs.
function pairingProd4( G1Point a1, G2Point a2, G1Point b1, G2Point b2, G1Point c1, G2Point c2, G1Point d1, G2Point d2 ) internal returns (bool) { G1Point[] memory p1 = new G1Point[](4); G2Point[] memory p2 = new G2Point[](4); p1[0] = a1; p1[1] = b1; p1[2] = c1; p1[3] = d1; p2[0] = a2; p2[1] = b2; p2[2] = c2; p2[3] = d2; return pairing(p1, p2); }
8,621,673
[ 1, 14700, 707, 364, 279, 3082, 310, 866, 364, 12792, 5574, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 3082, 310, 30683, 24, 12, 203, 565, 611, 21, 2148, 279, 21, 16, 611, 22, 2148, 279, 22, 16, 203, 565, 611, 21, 2148, 324, 21, 16, 611, 22, 2148, 324, 22, 16, 203, 565, 611, 21, 2148, 276, 21, 16, 611, 22, 2148, 276, 22, 16, 203, 565, 611, 21, 2148, 302, 21, 16, 611, 22, 2148, 302, 22, 203, 225, 262, 2713, 1135, 261, 6430, 13, 288, 203, 565, 611, 21, 2148, 8526, 3778, 293, 21, 273, 394, 611, 21, 2148, 8526, 12, 24, 1769, 203, 565, 611, 22, 2148, 8526, 3778, 293, 22, 273, 394, 611, 22, 2148, 8526, 12, 24, 1769, 203, 565, 293, 21, 63, 20, 65, 273, 279, 21, 31, 203, 565, 293, 21, 63, 21, 65, 273, 324, 21, 31, 203, 565, 293, 21, 63, 22, 65, 273, 276, 21, 31, 203, 565, 293, 21, 63, 23, 65, 273, 302, 21, 31, 203, 565, 293, 22, 63, 20, 65, 273, 279, 22, 31, 203, 565, 293, 22, 63, 21, 65, 273, 324, 22, 31, 203, 565, 293, 22, 63, 22, 65, 273, 276, 22, 31, 203, 565, 293, 22, 63, 23, 65, 273, 302, 22, 31, 203, 565, 327, 3082, 310, 12, 84, 21, 16, 293, 22, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xBf3B3b9368262Ed9BD06B621149CA947984D1B31/sources/contracts/main/TruStakeMATICv2.sol
We override this function as we want to block users from transferring strict allocations and associated rewards. We avoid using the _beforeTokenTransfer hook as we wish to utilise unblocked super._transfer functionality in reward distribution.
function _transfer(address from, address to, uint256 amount) internal override { if (from != address(0) && amount > maxRedeem(from)) { revert ExceedsUnallocatedBalance(); } super._transfer(from, to, amount); }
4,869,175
[ 1, 3218, 3849, 333, 445, 487, 732, 2545, 358, 1203, 3677, 628, 906, 74, 20245, 5490, 23804, 471, 3627, 283, 6397, 18, 1660, 4543, 1450, 326, 389, 5771, 1345, 5912, 3953, 487, 732, 14302, 358, 1709, 784, 640, 23156, 2240, 6315, 13866, 14176, 316, 19890, 7006, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 2713, 3849, 288, 203, 3639, 309, 261, 2080, 480, 1758, 12, 20, 13, 597, 3844, 405, 943, 426, 24903, 12, 2080, 3719, 288, 203, 5411, 15226, 1312, 5288, 87, 984, 28172, 13937, 5621, 203, 3639, 289, 203, 203, 3639, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 3844, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/40/0x5B19bd330A84c049b62D5B0FC2bA120217a18C1C/sources/contracts/NonceContract.sol
outboundNonce = [dstChainId][remoteAddress + localAddress]
contract NonceContract { ILayerZeroEndpoint public immutable endpoint; mapping(uint16 => mapping(bytes => uint64)) public outboundNonce; constructor(address _endpoint) { endpoint = ILayerZeroEndpoint(_endpoint); } function increment(uint16 _chainId, address _ua, bytes calldata _path) external returns (uint64) { require( endpoint.getSendLibraryAddress(_ua) == msg.sender, "NonceContract: msg.sender is not valid sendlibrary" ); return ++outboundNonce[_chainId][_path]; } }
9,547,455
[ 1, 659, 3653, 13611, 273, 306, 11057, 3893, 548, 6362, 7222, 1887, 397, 1191, 1887, 65, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 25261, 8924, 288, 203, 565, 467, 4576, 7170, 3293, 1071, 11732, 2494, 31, 203, 565, 2874, 12, 11890, 2313, 516, 2874, 12, 3890, 516, 2254, 1105, 3719, 1071, 11663, 13611, 31, 203, 203, 203, 565, 3885, 12, 2867, 389, 8003, 13, 288, 203, 3639, 2494, 273, 467, 4576, 7170, 3293, 24899, 8003, 1769, 203, 565, 289, 203, 203, 565, 445, 5504, 12, 11890, 2313, 389, 5639, 548, 16, 1758, 389, 11886, 16, 1731, 745, 892, 389, 803, 13, 3903, 1135, 261, 11890, 1105, 13, 288, 203, 3639, 2583, 12, 203, 5411, 2494, 18, 588, 3826, 9313, 1887, 24899, 11886, 13, 422, 1234, 18, 15330, 16, 203, 5411, 315, 13611, 8924, 30, 1234, 18, 15330, 353, 486, 923, 1366, 12083, 6, 203, 3639, 11272, 203, 3639, 327, 965, 659, 3653, 13611, 63, 67, 5639, 548, 6362, 67, 803, 15533, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xBEbB92Ed09688e64DC38c240B600D0B1d504EE56/sources/lib/aera-contracts/contracts/v1/AeraVaultV1.sol
Decrease managed balance and increase cash balance of pool i.e. Move amounts from managed balance to cash balance
updatePoolBalance(newBalances, IBVault.PoolBalanceOpKind.DEPOSIT);
3,080,249
[ 1, 23326, 448, 7016, 11013, 471, 10929, 276, 961, 11013, 434, 2845, 277, 18, 73, 18, 9933, 30980, 628, 7016, 11013, 358, 276, 961, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1089, 2864, 13937, 12, 2704, 38, 26488, 16, 23450, 12003, 18, 2864, 13937, 3817, 5677, 18, 1639, 28284, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x15B8C75c024acba8c114C21F42eb515A762c0014/sources/src/BobVault.sol
small non-withdrawable yield to account for possible rounding issues
uint96 dust;
3,757,682
[ 1, 12019, 1661, 17, 1918, 9446, 429, 2824, 358, 2236, 364, 3323, 13885, 8296, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 10525, 302, 641, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 /* Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6; pragma experimental ABIEncoderV2; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../../vendor/IERC1155Token.sol"; import "../../vendor/IERC721Token.sol"; import "../../vendor/IPropertyValidator.sol"; /// @dev A library for common NFT order operations. library LibNFTOrder { enum OrderStatus { INVALID, FILLABLE, UNFILLABLE, EXPIRED } enum TradeDirection { SELL_NFT, BUY_NFT } struct Property { IPropertyValidator propertyValidator; bytes propertyData; } struct Fee { address recipient; uint256 amount; bytes feeData; } // "Base struct" for ERC721Order and ERC1155, used // by the abstract contract `NFTOrders`. struct NFTOrder { TradeDirection direction; address maker; address taker; uint256 expiry; uint256 nonce; IERC20TokenV06 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address nft; uint256 nftId; Property[] nftProperties; } // All fields align with those of NFTOrder struct ERC721Order { TradeDirection direction; address maker; address taker; uint256 expiry; uint256 nonce; IERC20TokenV06 erc20Token; uint256 erc20TokenAmount; Fee[] fees; IERC721Token erc721Token; uint256 erc721TokenId; Property[] erc721TokenProperties; } // All fields except `erc1155TokenAmount` align // with those of NFTOrder struct ERC1155Order { TradeDirection direction; address maker; address taker; uint256 expiry; uint256 nonce; IERC20TokenV06 erc20Token; uint256 erc20TokenAmount; Fee[] fees; IERC1155Token erc1155Token; uint256 erc1155TokenId; Property[] erc1155TokenProperties; // End of fields shared with NFTOrder uint128 erc1155TokenAmount; } struct OrderInfo { bytes32 orderHash; OrderStatus status; // `orderAmount` is 1 for all ERC721Orders, and // `erc1155TokenAmount` for ERC1155Orders. uint128 orderAmount; // The remaining amount of the ERC721/ERC1155 asset // that can be filled for the order. uint128 remainingAmount; } // The type hash for ERC721 orders, which is: // keccak256(abi.encodePacked( // "ERC721Order(", // "uint8 direction,", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address erc721Token,", // "uint256 erc721TokenId,", // "Property[] erc721TokenProperties", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")", // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _ERC_721_ORDER_TYPEHASH = 0x2de32b2b090da7d8ab83ca4c85ba2eb6957bc7f6c50cb4ae1995e87560d808ed; // The type hash for ERC1155 orders, which is: // keccak256(abi.encodePacked( // "ERC1155Order(", // "uint8 direction,", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address erc1155Token,", // "uint256 erc1155TokenId,", // "Property[] erc1155TokenProperties,", // "uint128 erc1155TokenAmount", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")", // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _ERC_1155_ORDER_TYPEHASH = 0x930490b1bcedd2e5139e22c761fafd52e533960197c2283f3922c7fd8c880be9; // keccak256(abi.encodePacked( // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")" // )) uint256 private constant _FEE_TYPEHASH = 0xe68c29f1b4e8cce0bbcac76eb1334bdc1dc1f293a517c90e9e532340e1e94115; // keccak256(abi.encodePacked( // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _PROPERTY_TYPEHASH = 0x6292cf854241cb36887e639065eca63b3af9f7f70270cebeda4c29b6d3bc65e8; // keccak256(""); bytes32 private constant _EMPTY_ARRAY_KECCAK256 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // keccak256(abi.encodePacked(keccak256(abi.encode( // _PROPERTY_TYPEHASH, // address(0), // keccak256("") // )))); bytes32 private constant _NULL_PROPERTY_STRUCT_HASH = 0x720ee400a9024f6a49768142c339bf09d2dd9056ab52d20fbe7165faba6e142d; uint256 private constant ADDRESS_MASK = (1 << 160) - 1; // ERC721Order and NFTOrder fields are aligned, so // we can safely cast an ERC721Order to an NFTOrder. function asNFTOrder(ERC721Order memory erc721Order) internal pure returns (NFTOrder memory nftOrder) { assembly { nftOrder := erc721Order } } // ERC1155Order and NFTOrder fields are aligned with // the exception of the last field `erc1155TokenAmount` // in ERC1155Order, so we can safely cast an ERC1155Order // to an NFTOrder. function asNFTOrder(ERC1155Order memory erc1155Order) internal pure returns (NFTOrder memory nftOrder) { assembly { nftOrder := erc1155Order } } // ERC721Order and NFTOrder fields are aligned, so // we can safely cast an MFTOrder to an ERC721Order. function asERC721Order(NFTOrder memory nftOrder) internal pure returns (ERC721Order memory erc721Order) { assembly { erc721Order := nftOrder } } // NOTE: This is only safe if `nftOrder` was previously // cast from an `ERC1155Order` and the original // `erc1155TokenAmount` memory word has not been corrupted! function asERC1155Order( NFTOrder memory nftOrder ) internal pure returns (ERC1155Order memory erc1155Order) { assembly { erc1155Order := nftOrder } } /// @dev Get the struct hash of an ERC721 order. /// @param order The ERC721 order. /// @return structHash The struct hash of the order. function getERC721OrderStructHash(ERC721Order memory order) internal pure returns (bytes32 structHash) { bytes32 propertiesHash = _propertiesHash(order.erc721TokenProperties); bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _ERC_721_ORDER_TYPEHASH, // order.direction, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.erc721Token, // order.erc721TokenId, // propertiesHash // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 224) // order + (32 * 7) let propertiesHashPos := add(order, 320) // order + (32 * 10) let typeHashMemBefore := mload(typeHashPos) let feeHashMemBefore := mload(feesHashPos) let propertiesHashMemBefore := mload(propertiesHashPos) mstore(typeHashPos, _ERC_721_ORDER_TYPEHASH) mstore(feesHashPos, feesHash) mstore(propertiesHashPos, propertiesHash) structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feeHashMemBefore) mstore(propertiesHashPos, propertiesHashMemBefore) } return structHash; } /// @dev Get the struct hash of an ERC1155 order. /// @param order The ERC1155 order. /// @return structHash The struct hash of the order. function getERC1155OrderStructHash(ERC1155Order memory order) internal pure returns (bytes32 structHash) { bytes32 propertiesHash = _propertiesHash(order.erc1155TokenProperties); bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _ERC_1155_ORDER_TYPEHASH, // order.direction, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.erc1155Token, // order.erc1155TokenId, // propertiesHash, // order.erc1155TokenAmount // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 224) // order + (32 * 7) let propertiesHashPos := add(order, 320) // order + (32 * 10) let typeHashMemBefore := mload(typeHashPos) let feesHashMemBefore := mload(feesHashPos) let propertiesHashMemBefore := mload(propertiesHashPos) mstore(typeHashPos, _ERC_1155_ORDER_TYPEHASH) mstore(feesHashPos, feesHash) mstore(propertiesHashPos, propertiesHash) structHash := keccak256(typeHashPos, 416 /* 32 * 12 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feesHashMemBefore) mstore(propertiesHashPos, propertiesHashMemBefore) } return structHash; } // Hashes the `properties` array as part of computing the // EIP-712 hash of an `ERC721Order` or `ERC1155Order`. function _propertiesHash(Property[] memory properties) private pure returns (bytes32 propertiesHash) { uint256 numProperties = properties.length; // We give `properties.length == 0` and `properties.length == 1` // special treatment because we expect these to be the most common. if (numProperties == 0) { propertiesHash = _EMPTY_ARRAY_KECCAK256; } else if (numProperties == 1) { Property memory property = properties[0]; if ( address(property.propertyValidator) == address(0) && property.propertyData.length == 0 ) { propertiesHash = _NULL_PROPERTY_STRUCT_HASH; } else { // propertiesHash = keccak256(abi.encodePacked(keccak256(abi.encode( // _PROPERTY_TYPEHASH, // properties[0].propertyValidator, // keccak256(properties[0].propertyData) // )))); bytes32 dataHash = keccak256(property.propertyData); assembly { // Load free memory pointer let mem := mload(64) mstore(mem, _PROPERTY_TYPEHASH) // property.propertyValidator mstore(add(mem, 32), and(ADDRESS_MASK, mload(property))) // keccak256(property.propertyData) mstore(add(mem, 64), dataHash) mstore(mem, keccak256(mem, 96)) propertiesHash := keccak256(mem, 32) } } } else { bytes32[] memory propertyStructHashArray = new bytes32[](numProperties); for (uint256 i = 0; i < numProperties; i++) { propertyStructHashArray[i] = keccak256(abi.encode( _PROPERTY_TYPEHASH, properties[i].propertyValidator, keccak256(properties[i].propertyData) )); } assembly { propertiesHash := keccak256(add(propertyStructHashArray, 32), mul(numProperties, 32)) } } } // Hashes the `fees` array as part of computing the // EIP-712 hash of an `ERC721Order` or `ERC1155Order`. function _feesHash(Fee[] memory fees) private pure returns (bytes32 feesHash) { uint256 numFees = fees.length; // We give `fees.length == 0` and `fees.length == 1` // special treatment because we expect these to be the most common. if (numFees == 0) { feesHash = _EMPTY_ARRAY_KECCAK256; } else if (numFees == 1) { // feesHash = keccak256(abi.encodePacked(keccak256(abi.encode( // _FEE_TYPEHASH, // fees[0].recipient, // fees[0].amount, // keccak256(fees[0].feeData) // )))); Fee memory fee = fees[0]; bytes32 dataHash = keccak256(fee.feeData); assembly { // Load free memory pointer let mem := mload(64) mstore(mem, _FEE_TYPEHASH) // fee.recipient mstore(add(mem, 32), and(ADDRESS_MASK, mload(fee))) // fee.amount mstore(add(mem, 64), mload(add(fee, 32))) // keccak256(fee.feeData) mstore(add(mem, 96), dataHash) mstore(mem, keccak256(mem, 128)) feesHash := keccak256(mem, 32) } } else { bytes32[] memory feeStructHashArray = new bytes32[](numFees); for (uint256 i = 0; i < numFees; i++) { feeStructHashArray[i] = keccak256(abi.encode( _FEE_TYPEHASH, fees[i].recipient, fees[i].amount, keccak256(fees[i].feeData) )); } assembly { feesHash := keccak256(add(feeStructHashArray, 32), mul(numFees, 32)) } } } }
`orderAmount` is 1 for all ERC721Orders, and `erc1155TokenAmount` for ERC1155Orders. The remaining amount of the ERC721/ERC1155 asset that can be filled for the order.
struct OrderInfo { bytes32 orderHash; OrderStatus status; uint128 orderAmount; uint128 remainingAmount; } 0x2de32b2b090da7d8ab83ca4c85ba2eb6957bc7f6c50cb4ae1995e87560d808ed; 0x930490b1bcedd2e5139e22c761fafd52e533960197c2283f3922c7fd8c880be9; 0xe68c29f1b4e8cce0bbcac76eb1334bdc1dc1f293a517c90e9e532340e1e94115; 0x6292cf854241cb36887e639065eca63b3af9f7f70270cebeda4c29b6d3bc65e8; 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; 0x720ee400a9024f6a49768142c339bf09d2dd9056ab52d20fbe7165faba6e142d; uint256 private constant ADDRESS_MASK = (1 << 160) - 1;
7,213,331
[ 1, 68, 1019, 6275, 68, 353, 404, 364, 777, 4232, 39, 27, 5340, 16528, 16, 471, 1375, 12610, 2499, 2539, 1345, 6275, 68, 364, 4232, 39, 2499, 2539, 16528, 18, 1021, 4463, 3844, 434, 326, 4232, 39, 27, 5340, 19, 654, 39, 2499, 2539, 3310, 716, 848, 506, 6300, 364, 326, 1353, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 4347, 966, 288, 203, 3639, 1731, 1578, 1353, 2310, 31, 203, 3639, 4347, 1482, 1267, 31, 203, 3639, 2254, 10392, 1353, 6275, 31, 203, 3639, 2254, 10392, 4463, 6275, 31, 203, 565, 289, 203, 203, 3639, 374, 92, 22, 323, 1578, 70, 22, 70, 5908, 20, 2414, 27, 72, 28, 378, 10261, 5353, 24, 71, 7140, 12124, 22, 24008, 8148, 10321, 13459, 27, 74, 26, 71, 3361, 7358, 24, 8906, 19818, 25, 73, 11035, 4313, 20, 72, 3672, 28, 329, 31, 203, 203, 3639, 374, 92, 11180, 3028, 9349, 70, 21, 70, 311, 449, 22, 73, 25, 24347, 73, 3787, 71, 6669, 21, 507, 8313, 9401, 73, 25, 3707, 10525, 1611, 10580, 71, 3787, 10261, 74, 5520, 3787, 71, 27, 8313, 28, 71, 28, 3672, 2196, 29, 31, 203, 203, 3639, 374, 6554, 9470, 71, 5540, 74, 21, 70, 24, 73, 28, 71, 311, 20, 9897, 71, 1077, 6669, 24008, 3437, 5026, 70, 7201, 21, 7201, 21, 74, 5540, 23, 69, 25, 4033, 71, 9349, 73, 29, 73, 25, 1578, 5026, 20, 73, 21, 73, 11290, 22062, 31, 203, 203, 3639, 374, 92, 26, 5540, 22, 8522, 28, 6564, 3247, 21, 7358, 5718, 5482, 27, 73, 21607, 7677, 25, 26881, 4449, 70, 23, 1727, 29, 74, 27, 74, 27, 3103, 7301, 311, 2992, 69, 24, 71, 5540, 70, 26, 72, 23, 13459, 9222, 73, 28, 31, 203, 203, 3639, 374, 6511, 25, 72, 3247, 26, 1611, 5292, 74, 9060, 3707, 71, 29, 5324, 73, 27, 1966, 22, 72, 952, 27, 4630, 71, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; interface IStardust { function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); } contract DroidInvaders is ERC721Enumerable, Ownable { string public baseURI; address public proxyRegistryAddress; address public verifier; uint256 public constant PRICE = 250 ether; uint256 public constant MAX_SUPPLY = 7500; mapping(address => bool) public projectProxy; mapping(address => uint256) public mintedByWallet; bool public paused = true; IStardust private stardustContract; constructor( string memory _baseURI, address _proxyRegistryAddress, address _stardustContract ) ERC721("Droid Invaders", "DI") { baseURI = _baseURI; proxyRegistryAddress = _proxyRegistryAddress; stardustContract = IStardust(_stardustContract); } function _recoverWallet( address _wallet, uint256 _amount, bytes memory _signature ) internal pure returns (address) { return ECDSA.recover( ECDSA.toEthSignedMessageHash( keccak256(abi.encodePacked(_wallet, _amount)) ), _signature ); } function setBaseURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } function setVerifier(address _newVerifier) public onlyOwner { verifier = _newVerifier; } function setStardustAddress(address _stardustContract) public onlyOwner { stardustContract = IStardust(_stardustContract); } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "Token does not exist"); return string(abi.encodePacked(baseURI, Strings.toString(_tokenId))); } function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwner { proxyRegistryAddress = _proxyRegistryAddress; } function flipProxyState(address _proxyAddress) public onlyOwner { projectProxy[_proxyAddress] = !projectProxy[_proxyAddress]; } function flipSale() external onlyOwner { paused = !paused; } function mintWithStardust() external { uint256 totalSupply = _owners.length; require(!paused, "Minting paused"); require(totalSupply < MAX_SUPPLY, "Excedes max supply"); stardustContract.transferFrom( _msgSender(), address(stardustContract), PRICE ); _mint(_msgSender(), totalSupply); } function mintWithClaimableStardust(uint256 _count, bytes calldata _signature) external { address signer = _recoverWallet(_msgSender(), _count, _signature); require(signer == verifier, "Unverified transaction"); uint256 totalSupply = _owners.length; require(!paused, "Minting paused"); require(totalSupply < MAX_SUPPLY, "Excedes max supply"); require(mintedByWallet[_msgSender()] < _count, "Invalid mint count"); mintedByWallet[_msgSender()] = _count; _mint(_msgSender(), totalSupply); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function batchTransferFrom( address _from, address _to, uint256[] memory _tokenIds ) public { for (uint256 i; i < _tokenIds.length; i++) { transferFrom(_from, _to, _tokenIds[i]); } } function batchSafeTransferFrom( address _from, address _to, uint256[] memory _tokenIds, bytes memory _data ) public { for (uint256 i; i < _tokenIds.length; i++) { safeTransferFrom(_from, _to, _tokenIds[i], _data); } } function isApprovedForAll(address _owner, address _operator) public view override returns (bool) { OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry( proxyRegistryAddress ); if ( address(proxyRegistry.proxies(_owner)) == _operator || projectProxy[_operator] ) { return true; } return super.isApprovedForAll(_owner, _operator); } function _mint(address _to, uint256 _tokenId) internal virtual override { _owners.push(_to); emit Transfer(address(0), _to, _tokenId); } function withdraw() public onlyOwner { require( payable(owner()).send(address(this).balance), "Withdraw unsuccessful" ); } } // solhint-disable-next-line no-empty-blocks contract OwnableDelegateProxy { } contract OpenSeaProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "./ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account but rips out the core of the gas-wasting processing that comes from OpenZeppelin. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _owners.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < _owners.length, "ERC721Enumerable: global index out of bounds" ); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) { require( index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); uint256 count; for (uint256 i; i < _owners.length; i++) { if (owner == _owners[i]) { if (count == index) return i; else count++; } } revert("ERC721Enumerable: owner index out of bounds"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./Address.sol"; import "hardhat/console.sol"; abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; // Mapping from token ID to owner address address[] internal _owners; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); uint256 count; for (uint256 i; i < _owners.length; ++i) { if (owner == _owners[i]) ++count; } return count; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId < _owners.length && _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); console.log("here %s", getApproved(tokenId) == spender); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners.push(to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @dev Returns whether `spender` is allowed to manage `tokenId`. Requirements: - `tokenId` must exist./
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); console.log("here %s", getApproved(tokenId) == spender); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); }
988,757
[ 1, 1356, 2856, 1375, 87, 1302, 264, 68, 353, 2935, 358, 10680, 1375, 2316, 548, 8338, 29076, 30, 300, 1375, 2316, 548, 68, 1297, 1005, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 291, 31639, 1162, 5541, 12, 2867, 17571, 264, 16, 2254, 5034, 1147, 548, 13, 203, 565, 2713, 203, 565, 1476, 203, 565, 5024, 203, 565, 1135, 261, 6430, 13, 203, 225, 288, 203, 565, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 30, 3726, 843, 364, 1661, 19041, 1147, 8863, 203, 565, 1758, 3410, 273, 4232, 39, 27, 5340, 18, 8443, 951, 12, 2316, 548, 1769, 203, 565, 2983, 18, 1330, 2932, 14852, 738, 87, 3113, 336, 31639, 12, 2316, 548, 13, 422, 17571, 264, 1769, 203, 565, 327, 261, 87, 1302, 264, 422, 3410, 747, 203, 1377, 336, 31639, 12, 2316, 548, 13, 422, 17571, 264, 747, 203, 1377, 353, 31639, 1290, 1595, 12, 8443, 16, 17571, 264, 10019, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; interface IPlanetFarmConfig { /// @dev Return the latest price for ETH-USD function getLatestPrice() external view returns (int); /// @dev Return the amount of Testa wei rewarded if we are activate the progress function function getTestaReward() external view returns (uint256); /// @dev Return the amount of Testa wei to spend upon harvesting reward function getTestaFee(uint256 rewardETH) external view returns (uint256); /// @dev Return the liquidity value required to activate the progres function function getRequiredLiquidity(uint256 startLiquidity) external view returns (uint256); /// @dev Return the current liquidity value. function getLiquidity() external view returns (uint112); /// @dev Return the company's contract address function getCompany() external view returns (address); /// @dev Return the first pay amount value function getPayAmount() external view returns (uint256); /// @dev Return the jTesta amount value function getJTestaAmount() external view returns (uint256); /// @dev Return the (min, max) progress bar values. function getProgressive() external view returns (int, int); /// @dev Return the amount of block required to activate the progress function. function getActivateAtBlock() external view returns (uint256); } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier * available, which can be aplied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } interface ERC20Interface { function balanceOf(address user) external view returns (uint256); } library SafeToken { function myBalance(address token) internal view returns (uint256) { return ERC20Interface(token).balanceOf(address(this)); } function balanceOf(address token, address user) internal view returns (uint256) { return ERC20Interface(token).balanceOf(user); } function safeApprove(address token, address to, uint256 value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "!safeApprove"); } function safeTransfer(address token, address to, uint256 value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "!safeTransfer"); } function safeTransferFrom(address token, address from, address to, uint256 value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "!safeTransferFrom"); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call.value(value)(new bytes(0)); require(success, "!safeTransferETH"); } } contract UniverseFarm is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; using SafeToken for address; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. mapping(uint256 => uint256) accReward; // Accumulated reward since position opened mapping(uint256 => uint256) startIndex; // Start ETH index } address public merkleDistributor; IERC20 public jTesta; IERC20 public testa; IPlanetFarmConfig public config; uint112 public startLiquidity; uint112 public currentLiquidity; uint256 public startBlock; uint256 public initStartBlock; int public progressive = 0; uint256[] public accETHReward; uint256 public activationCount; uint256 public totalStake; uint256 public prevRoundETHReward; uint256 public round; uint256 public profit; // Info of each user that stakes LP tokens. mapping (address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Harvest(address indexed user, uint256 amount); event HarvestAndWithdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); constructor( uint256 _profit, uint256 _startBlock, IERC20 _testa, IERC20 _jTesta, IPlanetFarmConfig _config, address _merkleDistributor ) public { profit = _profit; startBlock = _startBlock; initStartBlock = _startBlock; testa = _testa; jTesta = _jTesta; config = _config; startLiquidity = _config.getLiquidity(); accETHReward.push(0); merkleDistributor = _merkleDistributor; } /// @dev Require that the caller must be an EOA account to avoid flash loans. modifier onlyEOA() { require(msg.sender == tx.origin, "Not EOA"); _; } receive() external payable {} function setConfig(IPlanetFarmConfig _config) public onlyOwner { config = _config; } function setMerkleDistributor(address _merkleDistributor) public onlyOwner { merkleDistributor = _merkleDistributor; } function setProfit(uint256 _profit) public onlyOwner { profit = _profit; } function setToken(IERC20 _testa, IERC20 _jTesta) public onlyOwner { testa = _testa; jTesta = _jTesta; } function harvestAndWithdraw(uint256 _amount) public nonReentrant { UserInfo storage user = userInfo[msg.sender]; uint256 jTestaSupply = jTesta.balanceOf(address(this)); ( , int maxProgressive) = config.getProgressive(); require(getBlockPass() <= config.getActivateAtBlock()); require((progressive == maxProgressive) && (jTestaSupply != 0), "Must have jTestaSupply and reach maxProgressive to harvest"); require(user.amount >= _amount, "No JTesta cannot withdraw"); uint256 rewardAmount = getUserReward(msg.sender); uint256 userProfit = rewardAmount.mul(profit).div(10000); uint256 _harvestFee = config.getTestaFee(userProfit); require(testa.balanceOf(msg.sender) > _harvestFee, "Must have enough testa before harvest"); testa.safeTransferFrom(msg.sender, config.getCompany(), _harvestFee); removeReward(msg.sender, rewardAmount); SafeToken.safeTransferETH(merkleDistributor, rewardAmount.sub(userProfit)); SafeToken.safeTransferETH(msg.sender, userProfit); if(_amount > 0) { user.amount = user.amount.sub(_amount); jTesta.safeTransfer(msg.sender, _amount); totalStake = totalStake.sub(_amount); } emit HarvestAndWithdraw(msg.sender, _amount); } function harvest() public nonReentrant { UserInfo storage user = userInfo[msg.sender]; uint256 jTestaSupply = jTesta.balanceOf(address(this)); ( , int maxProgressive) = config.getProgressive(); require(getBlockPass() <= config.getActivateAtBlock()); require((progressive == maxProgressive) && (jTestaSupply != 0), "Must have jTestaSupply and reach maxProgressive to harvest"); require(user.amount > 0, "No JTesta cannot withdraw"); uint256 rewardAmount = getUserReward(msg.sender); uint256 userProfit = rewardAmount.mul(profit).div(10000); uint256 _harvestFee = config.getTestaFee(userProfit); require(testa.balanceOf(msg.sender) > _harvestFee, "Must have enough testa before harvest"); testa.safeTransferFrom(msg.sender, config.getCompany(), _harvestFee); removeReward(msg.sender, rewardAmount); SafeToken.safeTransferETH(merkleDistributor, rewardAmount.sub(userProfit)); SafeToken.safeTransferETH(msg.sender, userProfit); emit Harvest(msg.sender, rewardAmount); } function firstActivate() public onlyEOA nonReentrant { require(jTesta.balanceOf(msg.sender) >= config.getJTestaAmount(), "Insufficient jTesta amount"); require(initStartBlock == startBlock); require(block.number >= initStartBlock, "Cannot activate until the specific block time arrive"); currentLiquidity = config.getLiquidity(); startBlock = block.number; startLiquidity = currentLiquidity; // send Testa to user who press activate button safeTestaTransfer(msg.sender, config.getTestaReward()); } function activate() public onlyEOA nonReentrant { require(jTesta.balanceOf(msg.sender) >= config.getJTestaAmount(), "Insufficient jTesta amount"); require(startBlock != initStartBlock && startBlock > initStartBlock); require(getBlockPass() >= config.getActivateAtBlock(), "Cannot activate until specific amount of blocks pass"); (int minProgressive, int maxProgressive) = config.getProgressive(); currentLiquidity = config.getLiquidity(); accETHReward.push(accETHReward[activationCount] + (address(this).balance).sub(prevRoundETHReward).mul(1e12).div(totalStake)); prevRoundETHReward = address(this).balance; activationCount++; uint256 requiredLiquidity = config.getRequiredLiquidity(startLiquidity); if(currentLiquidity > requiredLiquidity){ progressive++; }else{ progressive--; } if(progressive <= minProgressive){ progressive = minProgressive; uint256 totalReward = address(this).balance; resetGlobalReward(); SafeToken.safeTransferETH(config.getCompany(), totalReward); }else if(progressive >= maxProgressive){ progressive = maxProgressive; } startBlock = block.number; startLiquidity = currentLiquidity; // send Testa to user who press activate button safeTestaTransfer(msg.sender, config.getTestaReward()); } function updateUserReward(address userAddress) internal { UserInfo storage user = userInfo[userAddress]; if (user.startIndex[round] != activationCount) { uint256 userReward = getUserReward(userAddress); user.accReward[round] = userReward; user.startIndex[round] = activationCount; } } function removeReward(address userAddress,uint256 rewardAmount) internal { UserInfo storage user = userInfo[userAddress]; user.accReward[round] = 0; user.startIndex[round] = activationCount; prevRoundETHReward = prevRoundETHReward.sub(rewardAmount); } function resetGlobalReward() internal { delete accETHReward; accETHReward.push(0); activationCount = 0; prevRoundETHReward = 0; round++; } function getUserReward(address userAddress) public view returns(uint256) { UserInfo storage user = userInfo[userAddress]; uint256 prevReward = accETHReward[activationCount] - accETHReward[user.startIndex[round]]; uint256 total = user.accReward[round].add(user.amount.mul(prevReward).div(1e12)); return total; } function getUserAccReward(address userAddress) public view returns(uint256) { UserInfo storage user = userInfo[userAddress]; return user.accReward[round]; } function getUserStartIndex(address userAddress) public view returns(uint256) { UserInfo storage user = userInfo[userAddress]; return user.startIndex[round]; } function getTestaPoolBalance() public view returns (uint256){ return testa.balanceOf(address(this)); } function getProgressive() public view returns (int){ return progressive; } function getLatestBlock() public view returns (uint256) { return block.number; } function getBlockPass() public view returns (uint256){ return block.number.sub(startBlock); } function getStartedBlock() public view returns (uint256) { return startBlock; } function totalETH() public view returns (uint256) { return address(this).balance; } // Deposit LP tokens to TestaFarm for Testa allocation. function deposit(uint256 amount) public { require(amount > 0 , "invalid amount"); UserInfo storage user = userInfo[msg.sender]; updateUserReward(msg.sender); jTesta.safeTransferFrom(msg.sender, address(this), amount); user.amount = user.amount.add(amount); totalStake = totalStake.add(amount); emit Deposit(msg.sender, amount); } // Withdraw LP tokens from TestaFarm. function withdraw(uint256 _amount) public { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "Not enought token to withdraw"); if(_amount > 0) { uint256 rewardAmount = getUserReward(msg.sender); removeReward(msg.sender, rewardAmount); SafeToken.safeTransferETH(config.getCompany(), rewardAmount); user.amount = user.amount.sub(_amount); jTesta.safeTransfer(msg.sender, _amount); totalStake = totalStake.sub(_amount); } emit Withdraw(msg.sender, _amount); } function emergencyWithdraw(uint256 amount) public onlyOwner{ uint256 totalETHBal = address(this).balance; if(amount > totalETHBal){ SafeToken.safeTransferETH(msg.sender, totalETHBal); }else{ SafeToken.safeTransferETH(msg.sender, amount); } } // Safe testa transfer function, just in case if rounding error causes pool to not have enough Testa. function safeTestaTransfer(address _to, uint256 _amount) internal { uint256 testaBal = testa.balanceOf(address(this)); if (_amount > testaBal) { testa.safeTransfer(_to, testaBal); } else { testa.safeTransfer(_to, _amount); } } }
send Testa to user who press activate button
safeTestaTransfer(msg.sender, config.getTestaReward());
386,757
[ 1, 4661, 7766, 69, 358, 729, 10354, 11779, 10235, 3568, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 4183, 4709, 69, 5912, 12, 3576, 18, 15330, 16, 642, 18, 588, 4709, 69, 17631, 1060, 10663, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xeBBcAd9330131EB000e3b2ff27c5BAdab1732da8/sources/project_/contracts/laCollection-Anna-Ridler-Static-reversible.sol
We keep the 16 MSb from nonce because it has better randomness Applying the mutation color via a mask Generating the next nonce using MMIX LGC parameters by Donald Knuth (used in RISC architecture) emit DbgPrint("iWord", iWord); emit DbgPrint("pixelIndex", pixelIndex); emit DbgPrint("byteIndex", byteIndex); emit DbgPrint("nullMask", uint256(nullMask)); emit DbgPrint("valueMask", uint256(valueMask)); emit DbgPrint( "after", uint256((image[iWord] & nullMask) | valueMask) );
function mutateBloom(uint32 nMutations) private { unchecked { uint64 nonce = random(); for ( uint32 nMutationsLeft = nMutations; nMutationsLeft > 0; --nMutationsLeft ) { uint16 iWord = uint16((nonce >> 48) % matrixSizeWords); uint8 pixelIndex = uint8((nonce >> 32) % 256); bytes32 nullMask = bytes32(~(0x1 << pixelIndex)); mutationMatrix[iWord] = (mutationMatrix[iWord] & nullMask); } emit MutationsOccured(nMutations); lastTransferBlockNumber = block.number; } }
855,535
[ 1, 3218, 3455, 326, 2872, 9238, 70, 628, 7448, 2724, 518, 711, 7844, 2744, 4496, 5534, 310, 326, 11934, 2036, 3970, 279, 3066, 3055, 1776, 326, 1024, 7448, 1450, 490, 7492, 60, 511, 15396, 1472, 635, 7615, 287, 72, 1475, 82, 795, 261, 3668, 316, 534, 45, 2312, 27418, 13, 3626, 8408, 75, 5108, 2932, 77, 3944, 3113, 277, 3944, 1769, 3626, 8408, 75, 5108, 2932, 11743, 1016, 3113, 4957, 1016, 1769, 3626, 8408, 75, 5108, 2932, 7229, 1016, 3113, 1160, 1016, 1769, 3626, 8408, 75, 5108, 2932, 2011, 5796, 3113, 2254, 5034, 12, 2011, 5796, 10019, 3626, 8408, 75, 5108, 2932, 1132, 5796, 3113, 2254, 5034, 12, 1132, 5796, 10019, 3626, 8408, 75, 5108, 12, 377, 315, 5205, 3113, 377, 2254, 5034, 12443, 2730, 63, 77, 3944, 65, 473, 446, 5796, 13, 571, 460, 5796, 13, 11272, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15887, 38, 17810, 12, 11890, 1578, 290, 7420, 1012, 13, 3238, 288, 203, 3639, 22893, 288, 203, 5411, 2254, 1105, 7448, 273, 2744, 5621, 203, 203, 5411, 364, 261, 203, 7734, 2254, 1578, 290, 7420, 1012, 3910, 273, 290, 7420, 1012, 31, 203, 7734, 290, 7420, 1012, 3910, 405, 374, 31, 203, 7734, 1493, 82, 7420, 1012, 3910, 203, 5411, 262, 288, 203, 7734, 2254, 2313, 277, 3944, 273, 2254, 2313, 12443, 12824, 1671, 9934, 13, 738, 3148, 1225, 7363, 1769, 203, 7734, 2254, 28, 4957, 1016, 273, 2254, 28, 12443, 12824, 1671, 3847, 13, 738, 8303, 1769, 203, 203, 7734, 1731, 1578, 446, 5796, 273, 1731, 1578, 12, 98, 12, 20, 92, 21, 2296, 4957, 1016, 10019, 203, 203, 7734, 11934, 4635, 63, 77, 3944, 65, 273, 261, 28868, 4635, 63, 77, 3944, 65, 473, 446, 5796, 1769, 203, 203, 203, 5411, 289, 203, 203, 5411, 3626, 14138, 1012, 24269, 2862, 12, 82, 7420, 1012, 1769, 203, 203, 5411, 1142, 5912, 1768, 1854, 273, 1203, 18, 2696, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* //SPDX-License-Identifier: MIT */ pragma solidity ^0.8.2; import "./ENS.sol"; import "./IERC721.sol"; import "./IERC721Enumerable.sol"; import "./Ownable.sol"; import "./Strings.sol"; interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } contract KoteEnsMapper is Ownable { using Strings for uint256; ENS private ens; IERC721Enumerable public nft; bytes32 public domainHash; mapping(bytes32 => mapping(string => string)) public texts; mapping(address => uint256) public nextRegisterTimestamp; string public domainLabel = "kote"; string public nftImageBaseUri = "https://ipfs.io/ipfs/QmbQTvwHbZjciMHLpPFYb8NFBzAjEftdAm3i9PBjwZ7NzN/"; bool public useEIP155 = true; mapping(bytes32 => uint256) public hashToIdMap; mapping(uint256 => bytes32) public tokenHashmap; mapping(bytes32 => string) public hashToDomainMap; uint256 public reset_period = 7257600; //12 weeks bool public publicClaimOpen = false; mapping(address => bool) public address_whitelist; event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); event RegisterSubdomain(address indexed registrar, uint256 indexed token_id, string indexed label); constructor(){ ens = ENS(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e); nft = IERC721Enumerable(0x32A322C7C77840c383961B8aB503c9f45440c81f); domainHash = getDomainHash(); } //<interface-functions> function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == 0x3b3b57de //addr || interfaceID == 0x59d1d43c //text || interfaceID == 0x691f3431 //name || interfaceID == 0x01ffc9a7; //supportsInterface << [inception] } function text(bytes32 node, string calldata key) external view returns (string memory) { uint256 token_id = hashToIdMap[node]; require(token_id > 0 && tokenHashmap[token_id] != 0x0, "Invalid address"); if(keccak256(abi.encodePacked(key)) == keccak256("avatar")){ //eip155 string did not seem to work in any supported dapps during testing despite the returned string being properly //formatted. So the toggle was added so that we can direct link the image using http:// if this still does not work on //mainnet return useEIP155 ? string(abi.encodePacked("eip155:1/erc721:", addressToString(address(nft)), "/", token_id.toString())) : string(abi.encodePacked(nftImageBaseUri, token_id.toString(),".png")); } else{ return texts[node][key]; } } function addr(bytes32 nodeID) public view returns (address) { uint256 token_id = hashToIdMap[nodeID]; require(token_id > 0 && tokenHashmap[token_id] != 0x0, "Invalid address"); return nft.ownerOf(token_id); } function name(bytes32 node) view public returns (string memory){ return (hashToIdMap[node] == 0) ? "" : string(abi.encodePacked(hashToDomainMap[node], ".", domainLabel, ".eth")); } //</interface-functions> //--------------------------------------------------------------------------------------------// //<read-functions> function domainMap(string calldata label) public view returns(bytes32){ bytes32 encoded_label = keccak256(abi.encodePacked(label)); bytes32 big_hash = keccak256(abi.encodePacked(domainHash, encoded_label)); return hashToIdMap[big_hash] > 0 ? big_hash : bytes32(0x0); } function getClaimableIdsForAddress(address addy) public view returns(uint256[] memory){ if(((address_whitelist[addy] || publicClaimOpen) && block.timestamp > nextRegisterTimestamp[addy]) || owner() == addy){ return getAllIds(addy); } else{ return new uint256[](0); } } function getAllIds(address addy) private view returns(uint256[] memory){ uint256 balance = nft.balanceOf(addy); uint256[] memory ids = new uint256[](balance); uint256 count; for(uint256 i; i < balance; i++){ uint256 id = nft.tokenOfOwnerByIndex(addy, i); if(tokenHashmap[id] == 0x0){ ids[count++] = id; } } uint256[] memory trim_ids = new uint256[](count); for(uint256 i; i < count; i++){ trim_ids[i] = ids[i]; } return trim_ids; } function getTokenDomain(uint256 token_id) private view returns(string memory uri){ require(tokenHashmap[token_id] != 0x0, "Token does not have an ENS register"); uri = string(abi.encodePacked(hashToDomainMap[tokenHashmap[token_id]] ,"." ,domainLabel, ".eth")); } function getTokensDomains(uint256[] memory token_ids) public view returns(string[] memory){ string[] memory uris = new string[](token_ids.length); for(uint256 i; i < token_ids.length; i++){ uris[i] = getTokenDomain(token_ids[i]); } return uris; } function getAllCatsWithDomains(address addy) public view returns(uint256[] memory){ uint256 balance = nft.balanceOf(addy); uint256[] memory ids = new uint256[](balance); uint256 count; for(uint256 i; i < balance; i++){ uint256 id = nft.tokenOfOwnerByIndex(addy, i); if(tokenHashmap[id] != 0x0){ ids[count++] = id; } } uint256[] memory trim_ids = new uint256[](count); for(uint256 i; i < count; i++){ trim_ids[i] = ids[i]; } return trim_ids; } //</read-functions> //--------------------------------------------------------------------------------------------// //<helper-functions> function addressToString(address _addr) private pure returns(string memory) { bytes32 value = bytes32(uint256(uint160(_addr))); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(51); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < 20; i++) { str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))]; str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))]; } return string(str); } //this is the correct method for creating a 2 level ENS namehash function getDomainHash() private view returns (bytes32 namehash) { namehash = 0x0; namehash = keccak256(abi.encodePacked(namehash, keccak256(abi.encodePacked('eth')))); namehash = keccak256(abi.encodePacked(namehash, keccak256(abi.encodePacked(domainLabel)))); } //</helper-functions> //--------------------------------------------------------------------------------------------// //<authorised-functions> function setDomain(string calldata label, uint256 token_id) public isAuthorised(token_id) { require(tokenHashmap[token_id] == 0x0, "Token has already been set"); require(address_whitelist[msg.sender] || publicClaimOpen || owner() == msg.sender, "Not authorised"); require(block.timestamp > nextRegisterTimestamp[msg.sender], "Wallet must wait more time to register"); bytes32 encoded_label = keccak256(abi.encodePacked(label)); bytes32 big_hash = keccak256(abi.encodePacked(domainHash, encoded_label)); //contract owner can update / overwrite records. << this may be changed in the future with an updated method but as this is still //an experiment we'd like to retain some level of control over the sub-domains // //ens.recordExists seems to not be reliable (tested removing records through ENS control panel and this still returns true) require(!ens.recordExists(big_hash) || msg.sender == owner(), "sub-domain already exists"); ens.setSubnodeRecord(domainHash, encoded_label, owner(), address(this), 0); hashToIdMap[big_hash] = token_id; tokenHashmap[token_id] = big_hash; hashToDomainMap[big_hash] = label; if (owner() != msg.sender){ nextRegisterTimestamp[msg.sender] = block.timestamp + reset_period; //if user is on whitelist then remove if (address_whitelist[msg.sender]){ address_whitelist[msg.sender] = false; } } emit RegisterSubdomain(nft.ownerOf(token_id), token_id, label); } function setText(bytes32 node, string calldata key, string calldata value) external isAuthorised(hashToIdMap[node]) { uint256 token_id = hashToIdMap[node]; require(token_id > 0 && tokenHashmap[token_id] != 0x0, "Invalid address"); require(keccak256(abi.encodePacked(key)) != keccak256("avatar"), "cannot set avatar"); texts[node][key] = value; emit TextChanged(node, key, key); } function resetHash(uint256 token_id) public isAuthorised(token_id) { bytes32 domain = tokenHashmap[token_id]; require(ens.recordExists(domain), "Sub-domain does not exist"); //reset domain mappings hashToDomainMap[domain] = ""; hashToIdMap[domain] = 0; tokenHashmap[token_id] = 0x0; //allow sender to reclaim (if public == true) if(nextRegisterTimestamp[msg.sender] > block.timestamp && msg.sender != owner()){ nextRegisterTimestamp[msg.sender] = block.timestamp + (60 * 30); //30 minute cooldown } } //</authorised-functions> //--------------------------------------------------------------------------------------------// // <owner-functions> function addAddressWhitelist(address[] calldata addresses) public onlyOwner { for(uint256 i; i < addresses.length; i++){ address_whitelist[addresses[i]] = true; } } function setDomainLabel(string calldata label) public onlyOwner { domainLabel = label; domainHash = getDomainHash(); } function setNftAddress(address addy) public onlyOwner{ nft = IERC721Enumerable(addy); } function toggleNftImageLink() public onlyOwner{ useEIP155 = !useEIP155; } function setNftImageBaseUri(string memory _uri) public onlyOwner{ nftImageBaseUri = _uri; } function setEnsAddress(address addy) public onlyOwner { ens = ENS(addy); } function resetAddressForClaim(address addy) public onlyOwner { nextRegisterTimestamp[addy] = 0; } function togglePublicClaim() public onlyOwner { publicClaimOpen = !publicClaimOpen; } function updateResetPeriod(uint256 time) public onlyOwner { reset_period = time; } function renounceOwnership() public override onlyOwner { require(false, "ENS is responsibility. You cannot renounce ownership."); super.renounceOwnership(); } //just never know.. do you. function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawTokens(IERC20 token) public onlyOwner { require(address(token) != address(0)); uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } //</owner-functions> modifier isAuthorised(uint256 tokenId) { require(owner() == msg.sender || nft.ownerOf(tokenId) == msg.sender, "Not authorised"); _; } }
<authorised-functions>contract owner can update / overwrite records. << this may be changed in the future with an updated method but as this is stillan experiment we'd like to retain some level of control over the sub-domainsens.recordExists seems to not be reliable (tested removing records through ENS control panel and this still returns true)if user is on whitelist then remove
function setDomain(string calldata label, uint256 token_id) public isAuthorised(token_id) { require(tokenHashmap[token_id] == 0x0, "Token has already been set"); require(address_whitelist[msg.sender] || publicClaimOpen || owner() == msg.sender, "Not authorised"); require(block.timestamp > nextRegisterTimestamp[msg.sender], "Wallet must wait more time to register"); bytes32 encoded_label = keccak256(abi.encodePacked(label)); bytes32 big_hash = keccak256(abi.encodePacked(domainHash, encoded_label)); require(!ens.recordExists(big_hash) || msg.sender == owner(), "sub-domain already exists"); ens.setSubnodeRecord(domainHash, encoded_label, owner(), address(this), 0); hashToIdMap[big_hash] = token_id; tokenHashmap[token_id] = big_hash; hashToDomainMap[big_hash] = label; if (owner() != msg.sender){ nextRegisterTimestamp[msg.sender] = block.timestamp + reset_period; if (address_whitelist[msg.sender]){ address_whitelist[msg.sender] = false; } } emit RegisterSubdomain(nft.ownerOf(token_id), token_id, label); }
1,448,652
[ 1, 32, 4161, 5918, 17, 10722, 34, 16351, 3410, 848, 1089, 342, 6156, 3853, 18, 2296, 333, 2026, 506, 3550, 316, 326, 3563, 598, 392, 3526, 707, 1496, 487, 333, 353, 4859, 304, 8724, 732, 14271, 3007, 358, 15096, 2690, 1801, 434, 3325, 1879, 326, 720, 17, 14180, 773, 18, 3366, 4002, 12001, 358, 486, 506, 31024, 261, 88, 3149, 9427, 3853, 3059, 512, 3156, 3325, 6594, 471, 333, 4859, 1135, 638, 13, 430, 729, 353, 603, 10734, 1508, 1206, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 3748, 12, 1080, 745, 892, 1433, 16, 2254, 5034, 1147, 67, 350, 13, 1071, 353, 3594, 5918, 12, 2316, 67, 350, 13, 288, 1377, 203, 3639, 2583, 12, 2316, 2310, 1458, 63, 2316, 67, 350, 65, 422, 374, 92, 20, 16, 315, 1345, 711, 1818, 2118, 444, 8863, 203, 3639, 2583, 12, 2867, 67, 20409, 63, 3576, 18, 15330, 65, 747, 1071, 9762, 3678, 747, 3410, 1435, 422, 1234, 18, 15330, 16, 315, 1248, 2869, 5918, 8863, 203, 3639, 2583, 12, 2629, 18, 5508, 405, 1024, 3996, 4921, 63, 3576, 18, 15330, 6487, 315, 16936, 1297, 2529, 1898, 813, 358, 1744, 8863, 203, 5411, 203, 3639, 1731, 1578, 3749, 67, 1925, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 1925, 10019, 203, 3639, 1731, 1578, 5446, 67, 2816, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 4308, 2310, 16, 3749, 67, 1925, 10019, 203, 203, 3639, 2583, 12, 5, 773, 18, 3366, 4002, 12, 14002, 67, 2816, 13, 747, 1234, 18, 15330, 422, 3410, 9334, 315, 1717, 17, 4308, 1818, 1704, 8863, 203, 540, 203, 3639, 19670, 18, 542, 1676, 2159, 2115, 12, 4308, 2310, 16, 3749, 67, 1925, 16, 3410, 9334, 1758, 12, 2211, 3631, 374, 1769, 203, 203, 3639, 1651, 774, 548, 863, 63, 14002, 67, 2816, 65, 273, 1147, 67, 350, 31, 540, 203, 3639, 1147, 2310, 1458, 63, 2316, 67, 350, 65, 273, 5446, 67, 2816, 31, 203, 3639, 1651, 774, 3748, 863, 63, 14002, 67, 2816, 65, 273, 2 ]
./partial_match/4/0x9E7e753b6edDCcC4042A3dc77bbbCae091CcBDfa/sources/FEGToken.sol
@dev Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with GSN meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./
abstract contract Context { pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { return msg.data; } }
8,562,936
[ 1, 17727, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 611, 13653, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1772, 288, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 2138, 31, 203, 5666, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 2316, 19, 654, 39, 3462, 19, 654, 39, 3462, 18, 18281, 14432, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x4F669B0D2D72e19ede7CCFFDC2299AEee83D64C0/sources/RefNetwork.sol
* init a node, attach or re-attach to parent node/
function attach(address parent) external { nodes[msg.sender].attach(parent); while (parent != address(0x0)) { require(parent != msg.sender, "circular reference"); parent = nodes[parent].parent; } }
5,214,960
[ 1, 2738, 279, 756, 16, 3306, 578, 283, 17, 7331, 358, 982, 756, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3306, 12, 2867, 982, 13, 3903, 288, 203, 3639, 2199, 63, 3576, 18, 15330, 8009, 7331, 12, 2938, 1769, 203, 203, 3639, 1323, 261, 2938, 480, 1758, 12, 20, 92, 20, 3719, 288, 203, 5411, 2583, 12, 2938, 480, 1234, 18, 15330, 16, 315, 11614, 9559, 2114, 8863, 203, 5411, 982, 273, 2199, 63, 2938, 8009, 2938, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only /* Bounty.sol - SKALE Manager Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./delegation/DelegationController.sol"; import "./delegation/PartialDifferences.sol"; import "./delegation/TimeHelpers.sol"; import "./delegation/ValidatorService.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; contract BountyV2 is Permissions { using PartialDifferences for PartialDifferences.Value; using PartialDifferences for PartialDifferences.Sequence; struct BountyHistory { uint month; uint bountyPaid; } uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant EPOCHS_PER_YEAR = 12; uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY; uint private _nextEpoch; uint private _epochPool; uint private _bountyWasPaidInCurrentEpoch; bool public bountyReduction; uint public nodeCreationWindowSeconds; PartialDifferences.Value private _effectiveDelegatedSum; // validatorId amount of nodes mapping (uint => uint) public nodesByValidator; // deprecated // validatorId => BountyHistory mapping (uint => BountyHistory) private _bountyHistory; function calculateBounty(uint nodeIndex) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); require( _getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now, "Transaction is sent too early" ); uint validatorId = nodes.getValidatorId(nodeIndex); if (nodesByValidator[validatorId] > 0) { delete nodesByValidator[validatorId]; } uint currentMonth = timeHelpers.getCurrentMonth(); _refillEpochPool(currentMonth, timeHelpers, constantsHolder); _prepareBountyHistory(validatorId, currentMonth); uint bounty = _calculateMaximumBountyAmount( _epochPool, _effectiveDelegatedSum.getAndUpdateValue(currentMonth), _bountyWasPaidInCurrentEpoch, nodeIndex, _bountyHistory[validatorId].bountyPaid, delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getAndUpdateDelegatedToValidatorNow(validatorId), constantsHolder, nodes ); _bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty); bounty = _reduceBounty( bounty, nodeIndex, nodes, constantsHolder ); _epochPool = _epochPool.sub(bounty); _bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty); return bounty; } function enableBountyReduction() external onlyOwner { bountyReduction = true; } function disableBountyReduction() external onlyOwner { bountyReduction = false; } function setNodeCreationWindowSeconds(uint window) external allow("Nodes") { nodeCreationWindowSeconds = window; } function handleDelegationAdd( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.addToValue(amount, month); } function handleDelegationRemoving( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.subtractFromValue(amount, month); } function populate() external onlyOwner { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); TimeHelpers timeHelpers = TimeHelpers(contractManager.getTimeHelpers()); uint currentMonth = timeHelpers.getCurrentMonth(); // clean existing data for ( uint i = _effectiveDelegatedSum.firstUnprocessedMonth; i < _effectiveDelegatedSum.lastChangedMonth.add(1); ++i ) { delete _effectiveDelegatedSum.addDiff[i]; delete _effectiveDelegatedSum.subtractDiff[i]; } delete _effectiveDelegatedSum.value; delete _effectiveDelegatedSum.lastChangedMonth; _effectiveDelegatedSum.firstUnprocessedMonth = currentMonth; uint[] memory validators = validatorService.getTrustedValidators(); for (uint i = 0; i < validators.length; ++i) { uint validatorId = validators[i]; uint currentEffectiveDelegated = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth); uint[] memory effectiveDelegated = delegationController.getEffectiveDelegatedValuesByValidator(validatorId); if (effectiveDelegated.length > 0) { assert(currentEffectiveDelegated == effectiveDelegated[0]); } uint added = 0; for (uint j = 0; j < effectiveDelegated.length; ++j) { if (effectiveDelegated[j] != added) { if (effectiveDelegated[j] > added) { _effectiveDelegatedSum.addToValue(effectiveDelegated[j].sub(added), currentMonth + j); } else { _effectiveDelegatedSum.subtractFromValue(added.sub(effectiveDelegated[j]), currentMonth + j); } added = effectiveDelegated[j]; } } delete effectiveDelegated; } } function estimateBounty(uint nodeIndex) external view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint currentMonth = timeHelpers.getCurrentMonth(); uint validatorId = nodes.getValidatorId(nodeIndex); uint stagePoolSize; (stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, _effectiveDelegatedSum.getValue(currentMonth), _nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0, nodeIndex, _getBountyPaid(validatorId, currentMonth), delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getDelegatedToValidator(validatorId, currentMonth), constantsHolder, nodes ); } function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) { return _getNextRewardTimestamp( nodeIndex, Nodes(contractManager.getContract("Nodes")), TimeHelpers(contractManager.getContract("TimeHelpers")) ); } function getEffectiveDelegatedSum() external view returns (uint[] memory) { return _effectiveDelegatedSum.getValues(); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextEpoch = 0; _epochPool = 0; _bountyWasPaidInCurrentEpoch = 0; bountyReduction = false; nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY; } // private function _calculateMaximumBountyAmount( uint epochPoolSize, uint effectiveDelegatedSum, uint bountyWasPaidInCurrentEpoch, uint nodeIndex, uint bountyPaidToTheValidator, uint effectiveDelegated, uint delegated, ConstantsHolder constantsHolder, Nodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } if (effectiveDelegatedSum == 0) { // no delegations in the system return 0; } if (constantsHolder.msr() == 0) { return 0; } uint bounty = _calculateBountyShare( epochPoolSize.add(bountyWasPaidInCurrentEpoch), effectiveDelegated, effectiveDelegatedSum, delegated.div(constantsHolder.msr()), bountyPaidToTheValidator ); return bounty; } function _calculateBountyShare( uint monthBounty, uint effectiveDelegated, uint effectiveDelegatedSum, uint maxNodesAmount, uint paidToValidator ) private pure returns (uint) { if (maxNodesAmount > 0) { uint totalBountyShare = monthBounty .mul(effectiveDelegated) .div(effectiveDelegatedSum); return _min( totalBountyShare.div(maxNodesAmount), totalBountyShare.sub(paidToValidator) ); } else { return 0; } } function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) { return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp()); } function _getEpochPool( uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint epochPool, uint nextEpoch) { epochPool = _epochPool; for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) { epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder)); } } function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private { uint epochPool; uint nextEpoch; (epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); if (_nextEpoch < nextEpoch) { (_epochPool, _nextEpoch) = (epochPool, nextEpoch); _bountyWasPaidInCurrentEpoch = 0; } } function _getEpochReward( uint epoch, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint) { uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder); if (epoch < firstEpoch) { return 0; } uint epochIndex = epoch.sub(firstEpoch); uint year = epochIndex.div(EPOCHS_PER_YEAR); if (year >= 6) { uint power = year.sub(6).div(3).add(1); if (power < 256) { return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR); } else { return 0; } } else { uint[6] memory customBounties = [ YEAR1_BOUNTY, YEAR2_BOUNTY, YEAR3_BOUNTY, YEAR4_BOUNTY, YEAR5_BOUNTY, YEAR6_BOUNTY ]; return customBounties[year].div(EPOCHS_PER_YEAR); } } function _reduceBounty( uint bounty, uint nodeIndex, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = bounty; if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _prepareBountyHistory(uint validatorId, uint currentMonth) private { if (_bountyHistory[validatorId].month < currentMonth) { _bountyHistory[validatorId].month = currentMonth; delete _bountyHistory[validatorId].bountyPaid; } } function _getBountyPaid(uint validatorId, uint month) private view returns (uint) { require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid"); if (_bountyHistory[validatorId].month == month) { return _bountyHistory[validatorId].bountyPaid; } else { return 0; } } function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) { uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex); uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp); uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth); uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart); uint currentMonth = timeHelpers.getCurrentMonth(); assert(lastRewardMonth <= currentMonth); if (lastRewardMonth == currentMonth) { uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1)); uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2)); if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) { return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS); } else { return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS)); } } else if (lastRewardMonth.add(1) == currentMonth) { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1)); return _min( currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)), currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS) ); } else { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); return currentMonthStart.add(nodeCreationWindowSeconds); } } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } function _max(uint a, uint b) private pure returns (uint) { if (a < b) { return b; } else { return a; } } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationController.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../BountyV2.sol"; import "../Nodes.sol"; import "../Permissions.sol"; import "../utils/FractionUtils.sol"; import "../utils/MathUtils.sol"; import "./DelegationPeriodManager.sol"; import "./PartialDifferences.sol"; import "./Punisher.sol"; import "./TokenState.sol"; import "./ValidatorService.sol"; /** * @title Delegation Controller * @dev This contract performs all delegation functions including delegation * requests, and undelegation, etc. * * Delegators and validators may both perform delegations. Validators who perform * delegations to themselves are effectively self-delegating or self-bonding. * * IMPORTANT: Undelegation may be requested at any time, but undelegation is only * performed at the completion of the current delegation period. * * Delegated tokens may be in one of several states: * * - PROPOSED: token holder proposes tokens to delegate to a validator. * - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation. * - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator. * - REJECTED: token proposal expires at the UTC start of the next month. * - DELEGATED: accepted delegations are delegated at the UTC start of the month. * - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator. * - COMPLETED: undelegation request is completed at the end of the delegation period. */ contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } /** * @dev Update and return a validator's delegations. */ function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } /** * @dev Update and return the amount delegated. */ function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } /** * @dev Update and return the effective amount delegated (minus slash) for * the given month. */ function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * Emits a {DelegationProposed} event. * * Requirements: * * - Holder must have sufficient delegatable tokens. * - Delegation must be above the validator's minimum delegation amount. * - Delegation period must be allowed. * - Validator must be authorized if trusted list is enabled. * - Validator must be accepting new delegation requests. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { require( _getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); _getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender); uint forbiddenForDelegation = TokenState(contractManager.getTokenState()) .getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows token holder to cancel a delegation proposal. * * Emits a {DelegationRequestCanceledByUser} event. * * Requirements: * * - `msg.sender` must be the token holder of the delegation proposal. * - Delegation state must be PROPOSED. */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a {DelegationAccepted} event. * * Requirements: * * - Validator must be recipient of proposal. * - Delegation state must be PROPOSED. */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require( _getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _accept(delegationId); } /** * @dev Allows delegator to undelegate a specific delegation. * * Emits UndelegationRequested event. * * Requirements: * * - `msg.sender` must be the delegator. * - Delegation state must be DELEGATED. */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = _getValidatorService(); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); require( now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS) < _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished), "Undelegation requests must be sent 3 days before the end of delegation period" ); _subtractFromAllStatistics(delegationId); emit UndelegationRequested(delegationId); } /** * @dev Allows Punisher contract to slash an `amount` of stake from * a validator. This slashes an amount of delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manager to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } } /** * @dev Allows Distributor contract to return and update the effective * amount delegated (minus slash) to a validator for a given month. */ function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } /** * @dev Return and update the amount delegated to a validator for the * current month. */ function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) { return _effectiveDelegatedToValidator[validatorId].getValuesInSequence(); } function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month); } function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _delegatedToValidator[validatorId].getValue(month); } /** * @dev Return Delegation struct. */ function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } /** * @dev Returns the first delegation month. */ function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } /** * @dev Returns a validator's total number of delegations. */ function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } /** * @dev Returns a holder's total number of delegations. */ function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } /** * @dev Process slashes up to the given limit. */ function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } /** * @dev Process all slashes. */ function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } /** * @dev Returns the amount of tokens in PENDING delegation state. */ function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } /** * @dev Checks whether there are any unprocessed slashes. */ function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private /** * @dev Allows Nodes contract to get and update the amount delegated * to validator for a given month. */ function _getAndUpdateDelegatedToValidator(uint validatorId, uint month) private returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } /** * @dev Adds a new delegation proposal. */ function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } /** * @dev Returns the month when a delegation ends. */ function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { return _getTimeHelpers().getCurrentMonth(); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } /** * @dev Checks whether the holder has performed a delegation. */ function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } /** * @dev Returns the delegated amount after a slashing event. */ function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getPunisher()); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _subtractFromAllStatistics(uint delegationId) private { uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _getBounty().handleDelegationRemoving( effectiveAmount, delegations[delegationId].finished); } /** * @dev Checks whether delegation to a validator is allowed. * * Requirements: * * - Delegator must not have reached the validator limit. * - Delegation must be made in or after the first delegation month. */ function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) { return DelegationPeriodManager(contractManager.getDelegationPeriodManager()); } function _getBounty() private view returns (BountyV2) { return BountyV2(contractManager.getBounty()); } function _getValidatorService() private view returns (ValidatorService) { return ValidatorService(contractManager.getValidatorService()); } function _getTimeHelpers() private view returns (TimeHelpers) { return TimeHelpers(contractManager.getTimeHelpers()); } function _getConstantsHolder() private view returns (ConstantsHolder) { return ConstantsHolder(contractManager.getConstantsHolder()); } function _accept(uint delegationId) private { _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); uint amount = delegations[delegationId].amount; uint effectiveAmount = amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod) ); _getBounty().handleDelegationAdd( effectiveAmount, delegations[delegationId].started ); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferences.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; import "../utils/FractionUtils.sol"; /** * @title Partial Differences Library * @dev This library contains functions to manage Partial Differences data * structure. Partial Differences is an array of value differences over time. * * For example: assuming an array [3, 6, 3, 1, 2], partial differences can * represent this array as [_, 3, -3, -2, 1]. * * This data structure allows adding values on an open interval with O(1) * complexity. * * For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3), * instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows * performing [_, 3, -3+5, -2, 1]. The original array can be restored by * adding values from partial differences. */ library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value[month]; } } function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value != value) { sequence.value = value; } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function getValue(Value storage sequence, uint month) internal view returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value; } } function getValues(Value storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpers.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol"; /** * @title TimeHelpers * @dev The contract performs time operations. * * These functions are used to calculate monthly and Proof of Use epochs. */ contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ValidatorService.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title ValidatorService * @dev This contract handles all validator operations including registration, * node management, validator-specific delegation parameters, and more. * * TIP: For more information see our main instructions * https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ]. * * Validators register an address, and use this address to accept delegations and * register nodes. */ contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator ID that includes a validator name, description, * commission or fee rate, and a minimum delegation amount accepted by the validator. * * Emits a {ValidatorRegistered} event. * * Requirements: * * - Sender must not already have registered a validator ID. * - Fee rate must be between 0 - 1000‰. Note: in per mille. */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate <= 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } /** * @dev Allows Admin to enable a validator by adding their ID to the * trusted list. * * Emits a {ValidatorWasEnabled} event. * * Requirements: * * - Validator must not already be enabled. */ function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } /** * @dev Allows Admin to disable a validator by removing their ID from * the trusted list. * * Emits a {ValidatorWasDisabled} event. * * Requirements: * * - Validator must not already be disabled. */ function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the trusted validator list. Once turned off, the * trusted list cannot be re-enabled. */ function disableWhitelist() external onlyOwner { useWhitelist = false; } /** * @dev Allows `msg.sender` to request a new address. * * Requirements: * * - `msg.sender` must already be a validator. * - New address must not be null. * - New address must not be already registered as a validator. */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } /** * @dev Allows msg.sender to confirm an address change. * * Emits a {ValidatorAddressChanged} event. * * Requirements: * * - Must be owner of new address. */ function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a node address to validator ID. Validator must present * the node signature of the validator ID. * * Requirements: * * - Signature must be valid. * - Address must not be assigned to a validator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a node address from a validator. * * Emits a {NodeAddressWasRemoved} event. */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); this.removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } /** * @dev Allows a validator to set a minimum delegation amount. */ function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - Must not have already enabled accepting new requests. */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - Must not have already stopped accepting new requests. */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } /** * @dev Returns the amount of validator bond (self-delegation). */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } /** * @dev Returns node addresses linked to the msg.sender. */ function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns the list of trusted validators. */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } /** * @dev Checks whether the validator ID is linked to the validator address. */ function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } /** * @dev Returns the validator ID linked to a node address. * * Requirements: * * - Node address must be linked to a validator. */ function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view { require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); require( validators[validatorId].minimumDelegationAmount <= amount, "Amount does not meet the validator's minimum delegation amount" ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } /** * @dev Returns a validator's node addresses. */ function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } /** * @dev Checks whether validator ID exists. */ function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } /** * @dev Checks whether validator address exists. */ function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } /** * @dev Checks whether validator address exists. */ function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator address does not exist"); } /** * @dev Returns the Validator struct. */ function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } /** * @dev Returns the validator ID for the given validator address. */ function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } /** * @dev Checks whether the validator is currently accepting new delegation requests. */ function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } // private /** * @dev Links a validator address to a validator ID. * * Requirements: * * - Address is not already in use by another validator. */ function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } /** * @dev Links a node address to a validator ID. * * Requirements: * * - Node address must not be already linked to a validator. */ function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } // SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; uint public constant ALRIGHT_DELTA = 54640; uint public constant BROADCAST_DELTA = 122660; uint public constant COMPLAINT_BAD_DATA_DELTA = 40720; uint public constant PRE_RESPONSE_DELTA = 67780; uint public constant COMPLAINT_DELTA = 67100; uint public constant RESPONSE_DELTA = 215000; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimelimit; /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ function setCheckTime(uint newCheckTime) external onlyOwner { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external onlyOwner { require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyOwner { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyOwner { minimalSchainLifetime = lifetime; } function setComplaintTimelimit(uint timelimit) external onlyOwner { complaintTimelimit = timelimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimelimit = 1800; } } // SPDX-License-Identifier: AGPL-3.0-only /* Nodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol"; import "./delegation/DelegationController.sol"; import "./delegation/ValidatorService.sol"; import "./utils/Random.sol"; import "./utils/SegmentTree.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./Permissions.sol"; /** * @title Nodes * @dev This contract contains all logic to manage SKALE Network nodes states, * space availability, stake requirement checks, and exit functions. * * Nodes may be in one of several states: * * - Active: Node is registered and is in network operation. * - Leaving: Node has begun exiting from the network. * - Left: Node has left the network. * - In_Maintenance: Node is temporarily offline or undergoing infrastructure * maintenance * * Note: Online nodes contain both Active and Leaving states. */ contract Nodes is Permissions { using Random for Random.RandomGenerator; using SafeCast for uint; using SegmentTree for SegmentTree.Tree; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; mapping (uint => string) public domainNames; mapping (uint => bool) private _invisible; SegmentTree.Tree private _nodesAmountBySpace; /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName, uint time, uint gasSpend ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { _checkNodeIndex(nodeIndex); _; } modifier onlyNodeOrAdmin(uint nodeIndex) { _checkNodeOrAdmin(nodeIndex, msg.sender); _; } function initializeSegmentTreeAndInvisibleNodes() external onlyOwner { for (uint i = 0; i < nodes.length; i++) { if (nodes[i].status != NodeStatus.Active && nodes[i].status != NodeStatus.Left) { _invisible[i] = true; _removeNodeFromSpaceToNodes(i, spaceOfNodes[i].freeSpace); } } uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE(); _nodesAmountBySpace.create(totalSpace); for (uint8 i = 1; i <= totalSpace; i++) { if (spaceToNodes[i].length > 0) _nodesAmountBySpace.addToPlace(i, spaceToNodes[i].length); } } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("Schains", "NodeRotation") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered"); require(params.port > 0, "Port is zero"); require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE(); nodes.push(Node({ name: params.name, ip: params.ip, publicIP: params.publicIp, port: params.port, publicKey: params.publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); uint nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(params.name)); nodesIPCheck[params.ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; domainNames[nodeIndex] = params.domainName; spaceOfNodes.push(SpaceManaging({ freeSpace: totalSpace, indexInSpaceMap: spaceToNodes[totalSpace].length })); _setNodeActive(nodeIndex); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, params.domainName, block.timestamp, gasleft()); } /** * @dev Allows SkaleManager contract to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); emit ExitInitialized( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); require( _checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length), "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); return _checkValidatorPositionToMaintainNode(validatorId, position); } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); _setNodeInMaintenance(nodeIndex); } /** * @dev Allows Node to remove In_Maintenance status. * * Requirements: * * - Node must already be In Maintenance. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); _setNodeActive(nodeIndex); } function setDomainName(uint nodeIndex, string memory domainName) external onlyNodeOrAdmin(nodeIndex) { domainNames[nodeIndex] = domainName; } function makeNodeVisible(uint nodeIndex) external allow("SchainsInternal") { _makeNodeVisible(nodeIndex); } function makeNodeInvisible(uint nodeIndex) external allow("SchainsInternal") { _makeNodeInvisible(nodeIndex); } function getRandomNodeWithFreeSpace( uint8 freeSpace, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast( freeSpace == 0 ? 1 : freeSpace, randomGenerator ).toUint8(); require(place > 0, "Node not found"); return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)]; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns domain name of a given node. * * Requirements: * * - Node must exist. */ function getNodeDomainName(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (string memory) { return domainNames[nodeIndex]; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } /** * @dev Returns an address of a given node. */ function getNodeAddress(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (address) { return _publicKeyToAddress(nodes[nodeIndex].publicKey); } /** * @dev Returns the finish exit time of a given node. */ function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count) { if (freeSpace == 0) { return _nodesAmountBySpace.sumFromPlaceToLast(1); } return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace); } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; _nodesAmountBySpace.create(128); } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal { uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; uint len = spaceToNodes[space].length.sub(1); if (indexInArray < len) { uint shiftedIndex = spaceToNodes[space][len]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; } spaceToNodes[space].pop(); delete spaceOfNodes[nodeIndex].indexInSpaceMap; } function _getNodesAmountBySpace() internal view returns (SegmentTree.Tree storage) { return _nodesAmountBySpace; } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromTree(space); _addNodeToTree(newSpace); _removeNodeFromSpaceToNodes(nodeIndex, space); _addNodeToSpaceToNodes(nodeIndex, newSpace); } spaceOfNodes[nodeIndex].freeSpace = newSpace; } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); if (_invisible[nodeIndex]) { _makeNodeVisible(nodeIndex); } else { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); } } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); _makeNodeInvisible(nodeIndex); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; delete spaceOfNodes[nodeIndex].freeSpace; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; _makeNodeInvisible(nodeIndex); } function _makeNodeInvisible(uint nodeIndex) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromSpaceToNodes(nodeIndex, space); _removeNodeFromTree(space); _invisible[nodeIndex] = true; } } function _makeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); delete _invisible[nodeIndex]; } } function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private { spaceToNodes[space].push(nodeIndex); spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length.sub(1); } function _addNodeToTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.addToPlace(space, 1); } } function _removeNodeFromTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.removeFromPlace(space, 1); } } function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getConstantsHolder()).msr(); return position.add(1).mul(msr) <= delegationsTotal; } function _checkNodeIndex(uint nodeIndex) private view { require(nodeIndex < nodes.length, "Node with such index does not exist"); } function _checkNodeOrAdmin(uint nodeIndex, address sender) private view { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require( isNodeExist(sender, nodeIndex) || _isAdmin(sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(sender), "Sender is not permitted to call this function" ); } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "./ContractManager.sol"; /** * @title Permissions * @dev Contract is connected module for Upgradeable approach, knows ContractManager */ contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: AGPL-3.0-only /* FractionUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } // numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1 function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } // SPDX-License-Identifier: AGPL-3.0-only /* MathUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library MathUtils { uint constant private _EPS = 1e6; event UnderflowError( uint a, uint b ); function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationPeriodManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; /** * @title Delegation Period Manager * @dev This contract handles all delegation offerings. Delegations are held for * a specified period (months), and different durations can have different * returns or `stakeMultiplier`. Currently, only delegation periods can be added. */ contract DelegationPeriodManager is Permissions { mapping (uint => uint) public stakeMultipliers; /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); /** * @dev Allows the Owner to create a new available delegation period and * stake multiplier in the network. * * Emits a {DelegationPeriodWasSet} event. */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner { require(stakeMultipliers[monthsCount] == 0, "Delegation perios is already set"); stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[2] = 100; // 2 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } // SPDX-License-Identifier: AGPL-3.0-only /* Punisher.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ILocker.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; /** * @title Punisher * @dev This contract handles all slashing and forgiving operations. */ contract Punisher is Permissions, ILocker { // holder => tokens mapping (address => uint) private _locked; /** * @dev Emitted upon slashing condition. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted upon forgive condition. */ event Forgive( address wallet, uint amount ); /** * @dev Allows SkaleDKG contract to execute slashing on a validator and * validator's delegations by an `amount` of tokens. * * Emits a {Slash} event. * * Requirements: * * - Validator must exist. */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Admin to forgive a slashing condition. * * Emits a {Forgive} event. * * Requirements: * * - All slashes must have been processed. */ function forgive(address holder, uint amount) external onlyAdmin { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows DelegationController contract to execute slashing of * delegations. */ function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } // SPDX-License-Identifier: AGPL-3.0-only /* TokenState.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../interfaces/delegation/ILocker.sol"; import "../Permissions.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title Token State * @dev This contract manages lockers to control token transferability. * * The SKALE Network has three types of locked tokens: * * - Tokens that are transferrable but are currently locked into delegation with * a validator. * * - Tokens that are not transferable from one address to another, but may be * delegated to a validator `getAndUpdateLockedAmount`. This lock enforces * Proof-of-Use requirements. * * - Tokens that are neither transferable nor delegatable * `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing. */ contract TokenState is Permissions, ILocker { string[] private _lockers; DelegationController private _delegationController; /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { if (address(_delegationController) == address(0)) { _delegationController = DelegationController(contractManager.getContract("DelegationController")); } uint locked = 0; if (_delegationController.getDelegationsByHolderLength(holder) > 0) { // the holder ever delegated for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } } return locked; } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a {LockerWasRemoved} event. */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "./utils/StringUtils.sol"; /** * @title ContractManager * @dev Contract contains the actual current mapping from contract IDs * (in the form of human-readable strings) to addresses. */ contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; string public constant BOUNTY = "Bounty"; string public constant CONSTANTS_HOLDER = "ConstantsHolder"; string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager"; string public constant PUNISHER = "Punisher"; string public constant SKALE_TOKEN = "SkaleToken"; string public constant TIME_HELPERS = "TimeHelpers"; string public constant TOKEN_STATE = "TokenState"; string public constant VALIDATOR_SERVICE = "ValidatorService"; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows the Owner to add contract to mapping of contract addresses. * * Emits a {ContractUpgraded} event. * * Requirements: * * - New address is non-zero. * - Contract is not already added. * - Contract address contains code. */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contract address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns contract address. * * Requirements: * * - Contract must exist. */ function getDelegationPeriodManager() external view returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); } function getBounty() external view returns (address) { return getContract(BOUNTY); } function getValidatorService() external view returns (address) { return getContract(VALIDATOR_SERVICE); } function getTimeHelpers() external view returns (address) { return getContract(TIME_HELPERS); } function getConstantsHolder() external view returns (address) { return getContract(CONSTANTS_HOLDER); } function getSkaleToken() external view returns (address) { return getContract(SKALE_TOKEN); } function getTokenState() external view returns (address) { return getContract(TOKEN_STATE); } function getPunisher() external view returns (address) { return getContract(PUNISHER); } function getContract(string memory name) public view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; if (contractAddress == address(0)) { revert(name.strConcat(" contract has not been found")); } } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title Random * @dev The library for generating of pseudo random numbers */ library Random { using SafeMath for uint; struct RandomGenerator { uint seed; } /** * @dev Create an instance of RandomGenerator */ function create(uint seed) internal pure returns (RandomGenerator memory) { return RandomGenerator({seed: seed}); } function createFromEntropy(bytes memory entropy) internal pure returns (RandomGenerator memory) { return create(uint(keccak256(entropy))); } /** * @dev Generates random value */ function random(RandomGenerator memory self) internal pure returns (uint) { self.seed = uint(sha256(abi.encodePacked(self.seed))); return self.seed; } /** * @dev Generates random value in range [0, max) */ function random(RandomGenerator memory self, uint max) internal pure returns (uint) { assert(max > 0); uint maxRand = uint(-1).sub(uint(-1).mod(max)); if (uint(-1).sub(maxRand) == max.sub(1)) { return random(self).mod(max); } else { uint rand = random(self); while (rand >= maxRand) { rand = random(self); } return rand.mod(max); } } /** * @dev Generates random value in range [min, max) */ function random(RandomGenerator memory self, uint min, uint max) internal pure returns (uint) { assert(min < max); return min.add(random(self, max.sub(min))); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Random.sol"; /** * @title SegmentTree * @dev This library implements segment tree data structure * * Segment tree allows effectively calculate sum of elements in sub arrays * by storing some amount of additional data. * * IMPORTANT: Provided implementation assumes that arrays is indexed from 1 to n. * Size of initial array always must be power of 2 * * Example: * * Array: * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * Segment tree structure: * +-------------------------------+ * | 36 | * +---------------+---------------+ * | 10 | 26 | * +-------+-------+-------+-------+ * | 3 | 7 | 11 | 15 | * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * How the segment tree is stored in an array: * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ * | 36 | 10 | 26 | 3 | 7 | 11 | 15 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ */ library SegmentTree { using Random for Random.RandomGenerator; using SafeMath for uint; struct Tree { uint[] tree; } /** * @dev Allocates storage for segment tree of `size` elements * * Requirements: * * - `size` must be greater than 0 * - `size` must be power of 2 */ function create(Tree storage segmentTree, uint size) external { require(size > 0, "Size can't be 0"); require(size & size.sub(1) == 0, "Size is not power of 2"); segmentTree.tree = new uint[](size.mul(2).sub(1)); } /** * @dev Adds `delta` to element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] */ function addToPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].add(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Subtracts `delta` from element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] * - initial value of target element must be not less than `delta` */ function removeFromPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].sub(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].sub(delta); } } /** * @dev Adds `delta` to element of segment tree at `toPlace` * and subtracts `delta` from element at `fromPlace` * * Requirements: * * - `fromPlace` must be in range [1, size] * - `toPlace` must be in range [1, size] * - initial value of element at `fromPlace` must be not less than `delta` */ function moveFromPlaceToPlace( Tree storage self, uint fromPlace, uint toPlace, uint delta ) external { require(_correctPlace(self, fromPlace) && _correctPlace(self, toPlace), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; uint middle = leftBound.add(rightBound).div(2); uint fromPlaceMove = fromPlace > toPlace ? toPlace : fromPlace; uint toPlaceMove = fromPlace > toPlace ? fromPlace : toPlace; while (toPlaceMove <= middle || middle < fromPlaceMove) { if (middle < fromPlaceMove) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } middle = leftBound.add(rightBound).div(2); } uint leftBoundMove = leftBound; uint rightBoundMove = rightBound; uint stepMove = step; while(leftBoundMove < rightBoundMove && leftBound < rightBound) { uint middleMove = leftBoundMove.add(rightBoundMove).div(2); if (fromPlace > middleMove) { leftBoundMove = middleMove.add(1); stepMove = stepMove.add(stepMove).add(1); } else { rightBoundMove = middleMove; stepMove = stepMove.add(stepMove); } self.tree[stepMove.sub(1)] = self.tree[stepMove.sub(1)].sub(delta); middle = leftBound.add(rightBound).div(2); if (toPlace > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Returns random position in range [`place`, size] * with probability proportional to value stored at this position. * If all element in range are 0 returns 0 * * Requirements: * * - `place` must be in range [1, size] */ function getRandomNonZeroElementFromPlaceToLast( Tree storage self, uint place, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { require(_correctPlace(self, place), "Incorrect place"); uint vertex = 1; uint leftBound = 0; uint rightBound = getSize(self); uint currentFrom = place.sub(1); uint currentSum = sumFromPlaceToLast(self, place); if (currentSum == 0) { return 0; } while(leftBound.add(1) < rightBound) { if (_middle(leftBound, rightBound) <= currentFrom) { vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); } else { uint rightSum = self.tree[_right(vertex).sub(1)]; uint leftSum = currentSum.sub(rightSum); if (Random.random(randomGenerator, currentSum) < leftSum) { // go left vertex = _left(vertex); rightBound = _middle(leftBound, rightBound); currentSum = leftSum; } else { // go right vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); currentFrom = leftBound; currentSum = rightSum; } } } return leftBound.add(1); } /** * @dev Returns sum of elements in range [`place`, size] * * Requirements: * * - `place` must be in range [1, size] */ function sumFromPlaceToLast(Tree storage self, uint place) public view returns (uint sum) { require(_correctPlace(self, place), "Incorrect place"); if (place == 1) { return self.tree[0]; } uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); sum = sum.add(self.tree[step]); } } sum = sum.add(self.tree[step.sub(1)]); } /** * @dev Returns amount of elements in segment tree */ function getSize(Tree storage segmentTree) internal view returns (uint) { if (segmentTree.tree.length > 0) { return segmentTree.tree.length.div(2).add(1); } else { return 0; } } /** * @dev Checks if `place` is valid position in segment tree */ function _correctPlace(Tree storage self, uint place) private view returns (bool) { return place >= 1 && place <= getSize(self); } /** * @dev Calculates index of left child of the vertex */ function _left(uint vertex) private pure returns (uint) { return vertex.mul(2); } /** * @dev Calculates index of right child of the vertex */ function _right(uint vertex) private pure returns (uint) { return vertex.mul(2).add(1); } /** * @dev Calculates arithmetical mean of 2 numbers */ function _middle(uint left, uint right) private pure returns (uint) { return left.add(right).div(2); } } // SPDX-License-Identifier: AGPL-3.0-only /* ILocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the Locker functions. */ interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* NodesMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../BountyV2.sol"; import "../Permissions.sol"; contract NodesMock is Permissions { uint public nodesCount = 0; uint public nodesLeft = 0; // nodeId => timestamp mapping (uint => uint) public lastRewardDate; // nodeId => left mapping (uint => bool) public nodeLeft; // nodeId => validatorId mapping (uint => uint) public owner; function registerNodes(uint amount, uint validatorId) external { for (uint nodeId = nodesCount; nodeId < nodesCount + amount; ++nodeId) { lastRewardDate[nodeId] = now; owner[nodeId] = validatorId; } nodesCount += amount; } function removeNode(uint nodeId) external { ++nodesLeft; nodeLeft[nodeId] = true; } function changeNodeLastRewardDate(uint nodeId) external { lastRewardDate[nodeId] = now; } function getNodeLastRewardDate(uint nodeIndex) external view returns (uint) { require(nodeIndex < nodesCount, "Node does not exist"); return lastRewardDate[nodeIndex]; } function isNodeLeft(uint nodeId) external view returns (bool) { return nodeLeft[nodeId]; } function getNumberOnlineNodes() external view returns (uint) { return nodesCount.sub(nodesLeft); } function checkPossibilityToMaintainNode(uint /* validatorId */, uint /* nodeIndex */) external pure returns (bool) { return true; } function getValidatorId(uint nodeId) external view returns (uint) { return owner[nodeId]; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleManagerMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../interfaces/IMintableToken.sol"; import "../Permissions.sol"; contract SkaleManagerMock is Permissions, IERC777Recipient { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); constructor (address contractManagerAddress) public { Permissions.initialize(contractManagerAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } function payBounty(uint validatorId, uint amount) external { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); require(IMintableToken(address(skaleToken)).mint(address(this), amount, "", ""), "Token was not minted"); require( IMintableToken(address(skaleToken)) .mint(contractManager.getContract("Distributor"), amount, abi.encode(validatorId), ""), "Token was not minted" ); } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } } pragma solidity ^0.6.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: AGPL-3.0-only /* IMintableToken.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; interface IMintableToken { function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleToken.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./thirdparty/openzeppelin/ERC777.sol"; import "./Permissions.sol"; import "./interfaces/delegation/IDelegatableToken.sol"; import "./interfaces/IMintableToken.sol"; import "./delegation/Punisher.sol"; import "./delegation/TokenState.sol"; /** * @title SkaleToken * @dev Contract defines the SKALE token and is based on ERC777 token * implementation. */ contract SkaleToken is ERC777, Permissions, ReentrancyGuard, IDelegatableToken, IMintableToken { using SafeMath for uint; string public constant NAME = "SKALE"; string public constant SYMBOL = "SKL"; uint public constant DECIMALS = 18; uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created constructor(address contractsAddress, address[] memory defOps) public ERC777("SKALE", "SKL", defOps) { Permissions.initialize(contractsAddress); } /** * @dev Allows Owner or SkaleManager to mint an amount of tokens and * transfer minted tokens to a specified address. * * Returns whether the operation is successful. * * Requirements: * * - Mint must not exceed the total supply. */ function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleManager") //onlyAuthorized returns (bool) { require(amount <= CAP.sub(totalSupply()), "Amount is too big"); _mint( account, amount, userData, operatorData ); return true; } /** * @dev See {IDelegatableToken-getAndUpdateDelegatedAmount}. */ function getAndUpdateDelegatedAmount(address wallet) external override returns (uint) { return DelegationController(contractManager.getContract("DelegationController")) .getAndUpdateDelegatedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateSlashedAmount}. */ function getAndUpdateSlashedAmount(address wallet) external override returns (uint) { return Punisher(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) public override returns (uint) { return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet); } // internal function _beforeTokenTransfer( address, // operator address from, address, // to uint256 tokenId) internal override { uint locked = getAndUpdateLockedAmount(from); if (locked > 0) { require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring"); } } function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal override nonReentrant { super._callTokensToSend(operator, from, to, amount, userData, operatorData); } function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal override nonReentrant { super._callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } // we have to override _msgData() and _msgSender() functions because of collision in Context and ContextUpgradeSafe function _msgData() internal view override(Context, ContextUpgradeSafe) returns (bytes memory) { return Context._msgData(); } function _msgSender() internal view override(Context, ContextUpgradeSafe) returns (address payable) { return Context._msgSender(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; Removed by SKALE // import "@openzeppelin/contracts/utils/Address.sol"; Removed by SKALE import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; /* Added by SKALE */ import "../../Permissions.sol"; /* End of added by SKALE */ /** * @dev Implementation of the {IERC777} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name, string memory symbol, address[] memory defaultOperators ) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); /* Chaged by SKALE: we swapped these lines to prevent delegation of burning tokens */ _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); /* End of changed by SKALE */ // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve(address holder, address spender, uint256 value) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - when `from` is zero, `tokenId` will be minted for `to`. * - when `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address operator, address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-only /* IDelegatableToken.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the SkaleToken contract. */ interface IDelegatableToken { /** * @dev Returns and updates the amount of locked tokens of a given account `wallet`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the amount of delegated tokens of a given account `wallet`. */ function getAndUpdateDelegatedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the amount of slashed tokens of a given account `wallet`. */ function getAndUpdateSlashedAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleTokenInternalTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../SkaleToken.sol"; contract SkaleTokenInternalTester is SkaleToken { constructor(address contractManagerAddress, address[] memory defOps) public SkaleToken(contractManagerAddress, defOps) // solhint-disable-next-line no-empty-blocks { } function getMsgData() external view returns (bytes memory) { return _msgData(); } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpersWithDebug.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "../delegation/TimeHelpers.sol"; contract TimeHelpersWithDebug is TimeHelpers, OwnableUpgradeSafe { struct TimeShift { uint pointInTime; uint shift; } TimeShift[] private _timeShift; function skipTime(uint sec) external onlyOwner { if (_timeShift.length > 0) { _timeShift.push(TimeShift({pointInTime: now, shift: _timeShift[_timeShift.length.sub(1)].shift.add(sec)})); } else { _timeShift.push(TimeShift({pointInTime: now, shift: sec})); } } function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } function timestampToMonth(uint timestamp) public view override returns (uint) { return super.timestampToMonth(timestamp.add(_getTimeShift(timestamp))); } function monthToTimestamp(uint month) public view override returns (uint) { uint shiftedTimestamp = super.monthToTimestamp(month); if (_timeShift.length > 0) { return _findTimeBeforeTimeShift(shiftedTimestamp); } else { return shiftedTimestamp; } } // private function _getTimeShift(uint timestamp) private view returns (uint) { if (_timeShift.length > 0) { if (timestamp < _timeShift[0].pointInTime) { return 0; } else if (timestamp >= _timeShift[_timeShift.length.sub(1)].pointInTime) { return _timeShift[_timeShift.length.sub(1)].shift; } else { uint left = 0; uint right = _timeShift.length.sub(1); while (left + 1 < right) { uint middle = left.add(right).div(2); if (timestamp < _timeShift[middle].pointInTime) { right = middle; } else { left = middle; } } return _timeShift[left].shift; } } else { return 0; } } function _findTimeBeforeTimeShift(uint shiftedTimestamp) private view returns (uint) { uint lastTimeShiftIndex = _timeShift.length.sub(1); if (_timeShift[lastTimeShiftIndex].pointInTime.add(_timeShift[lastTimeShiftIndex].shift) < shiftedTimestamp) { return shiftedTimestamp.sub(_timeShift[lastTimeShiftIndex].shift); } else { if (shiftedTimestamp <= _timeShift[0].pointInTime.add(_timeShift[0].shift)) { if (shiftedTimestamp < _timeShift[0].pointInTime) { return shiftedTimestamp; } else { return _timeShift[0].pointInTime; } } else { uint left = 0; uint right = lastTimeShiftIndex; while (left + 1 < right) { uint middle = left.add(right).div(2); if (_timeShift[middle].pointInTime.add(_timeShift[middle].shift) < shiftedTimestamp) { left = middle; } else { right = middle; } } if (shiftedTimestamp < _timeShift[right].pointInTime.add(_timeShift[left].shift)) { return shiftedTimestamp.sub(_timeShift[left].shift); } else { return _timeShift[right].pointInTime; } } } } } // SPDX-License-Identifier: AGPL-3.0-only /* SafeMock.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; contract SafeMock is OwnableUpgradeSafe { constructor() public { OwnableUpgradeSafe.__Ownable_init(); multiSend(""); // this is needed to remove slither warning } function transferProxyAdminOwnership(OwnableUpgradeSafe proxyAdmin, address newOwner) external onlyOwner { proxyAdmin.transferOwnership(newOwner); } function destroy() external onlyOwner { selfdestruct(msg.sender); } /// @dev Sends multiple transactions and reverts all if one fails. /// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of /// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte), /// to as a address (=> 20 bytes), /// value as a uint256 (=> 32 bytes), /// data length as a uint256 (=> 32 bytes), /// data as bytes. /// see abi.encodePacked for more information on packed encoding function multiSend(bytes memory transactions) public { // solhint-disable-next-line no-inline-assembly assembly { let length := mload(transactions) let i := 0x20 // solhint-disable-next-line no-empty-blocks for { } lt(i, length) { } { // First byte of the data is the operation. // We shift by 248 bits (256 - 8 [operation byte]) it right // since mload will always load 32 bytes (a word). // This will also zero out unused data. let operation := shr(0xf8, mload(add(transactions, i))) // We offset the load address by 1 byte (operation byte) // We shift it right by 96 bits (256 - 160 [20 address bytes]) // to right-align the data and zero out unused data. let to := shr(0x60, mload(add(transactions, add(i, 0x01)))) // We offset the load address by 21 byte (operation byte + 20 address bytes) let value := mload(add(transactions, add(i, 0x15))) // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes) let dataLength := mload(add(transactions, add(i, 0x35))) // We offset the load address by 85 byte // (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes) let data := add(transactions, add(i, 0x55)) let success := 0 switch operation case 0 { success := call(gas(), to, value, data, dataLength, 0, 0) } case 1 { success := delegatecall(gas(), to, data, dataLength, 0, 0) } if eq(success, 0) { revert(0, 0) } // Next entry starts at 85 byte + data length i := add(i, add(0x55, dataLength)) } } } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgAlright.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../ContractManager.sol"; import "../Wallets.sol"; import "../KeyStorage.sol"; /** * @title SkaleDkgAlright * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgAlright { event AllDataReceived(bytes32 indexed schainId, uint nodeIndex); event SuccessfulDKG(bytes32 indexed schainId); function alright( bytes32 schainId, uint fromNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage lastSuccesfulDKG ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); (uint index, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, fromNodeIndex, true); uint numberOfParticipant = channels[schainId].n; require(numberOfParticipant == dkgProcess[schainId].numberOfBroadcasted, "Still Broadcasting phase"); require( complaints[schainId].fromNodeToComplaint != fromNodeIndex || (fromNodeIndex == 0 && complaints[schainId].startComplaintBlockTimestamp == 0), "Node has already sent complaint" ); require(!dkgProcess[schainId].completed[index], "Node is already alright"); dkgProcess[schainId].completed[index] = true; dkgProcess[schainId].numberOfCompleted++; emit AllDataReceived(schainId, fromNodeIndex); if (dkgProcess[schainId].numberOfCompleted == numberOfParticipant) { lastSuccesfulDKG[schainId] = now; channels[schainId].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainId); emit SuccessfulDKG(schainId); } } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDKG.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./delegation/Punisher.sol"; import "./SlashingTable.sol"; import "./Schains.sol"; import "./SchainsInternal.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./KeyStorage.sol"; import "./interfaces/ISkaleDKG.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./Wallets.sol"; import "./dkg/SkaleDkgAlright.sol"; import "./dkg/SkaleDkgBroadcast.sol"; import "./dkg/SkaleDkgComplaint.sol"; import "./dkg/SkaleDkgPreResponse.sol"; import "./dkg/SkaleDkgResponse.sol"; /** * @title SkaleDKG * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ contract SkaleDKG is Permissions, ISkaleDKG { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; enum DkgFunction {Broadcast, Alright, ComplaintBadData, PreResponse, Complaint, Response} struct Channel { bool active; uint n; uint startedBlockTimestamp; uint startedBlock; } struct ProcessDKG { uint numberOfBroadcasted; uint numberOfCompleted; bool[] broadcasted; bool[] completed; } struct ComplaintData { uint nodeToComplaint; uint fromNodeToComplaint; uint startComplaintBlockTimestamp; bool isResponse; bytes32 keyShare; G2Operations.G2Point sumOfVerVec; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } struct Context { bool isDebt; uint delta; DkgFunction dkgFunction; } uint public constant COMPLAINT_TIMELIMIT = 1800; mapping(bytes32 => Channel) public channels; mapping(bytes32 => uint) public lastSuccesfulDKG; mapping(bytes32 => ProcessDKG) public dkgProcess; mapping(bytes32 => ComplaintData) public complaints; mapping(bytes32 => uint) public startAlrightTimestamp; mapping(bytes32 => mapping(uint => bytes32)) public hashedData; mapping(bytes32 => uint) private _badNodes; /** * @dev Emitted when a channel is opened. */ event ChannelOpened(bytes32 schainId); /** * @dev Emitted when a channel is closed. */ event ChannelClosed(bytes32 schainId); /** * @dev Emitted when a node broadcasts keyshare. */ event BroadcastAndKeyShare( bytes32 indexed schainId, uint indexed fromNode, G2Operations.G2Point[] verificationVector, KeyShare[] secretKeyContribution ); /** * @dev Emitted when all group data is received by node. */ event AllDataReceived(bytes32 indexed schainId, uint nodeIndex); /** * @dev Emitted when DKG is successful. */ event SuccessfulDKG(bytes32 indexed schainId); /** * @dev Emitted when a complaint against a node is verified. */ event BadGuy(uint nodeIndex); /** * @dev Emitted when DKG failed. */ event FailedDKG(bytes32 indexed schainId); /** * @dev Emitted when a new node is rotated in. */ event NewGuy(uint nodeIndex); /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent( bytes32 indexed schainId, uint indexed fromNodeIndex, uint indexed toNodeIndex); modifier correctGroup(bytes32 schainId) { require(channels[schainId].active, "Group is not created"); _; } modifier correctGroupWithoutRevert(bytes32 schainId) { if (!channels[schainId].active) { emit ComplaintError("Group is not created"); } else { _; } } modifier correctNode(bytes32 schainId, uint nodeIndex) { (uint index, ) = checkAndReturnIndexInGroup(schainId, nodeIndex, true); _; } modifier correctNodeWithoutRevert(bytes32 schainId, uint nodeIndex) { (, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); if (!check) { emit ComplaintError("Node is not in this group"); } else { _; } } modifier onlyNodeOwner(uint nodeIndex) { _checkMsgSenderIsNodeOwner(nodeIndex); _; } modifier refundGasBySchain(bytes32 schainId, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainId, gasTotal, context); } modifier refundGasByValidatorToSchain(bytes32 schainId, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainId, gasTotal, context); _refundGasByValidatorToSchain(schainId); } function alright(bytes32 schainId, uint fromNodeIndex) external refundGasBySchain(schainId, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).ALRIGHT_DELTA(), dkgFunction: DkgFunction.Alright })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgAlright.alright( schainId, fromNodeIndex, contractManager, channels, dkgProcess, complaints, lastSuccesfulDKG ); } function broadcast( bytes32 schainId, uint nodeIndex, G2Operations.G2Point[] memory verificationVector, KeyShare[] memory secretKeyContribution ) external refundGasBySchain(schainId, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).BROADCAST_DELTA(), dkgFunction: DkgFunction.Broadcast })) correctGroup(schainId) onlyNodeOwner(nodeIndex) { SkaleDkgBroadcast.broadcast( schainId, nodeIndex, verificationVector, secretKeyContribution, contractManager, channels, dkgProcess, hashedData ); } function complaintBadData(bytes32 schainId, uint fromNodeIndex, uint toNodeIndex) external refundGasBySchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_BAD_DATA_DELTA(), dkgFunction: DkgFunction.ComplaintBadData })) correctGroupWithoutRevert(schainId) correctNode(schainId, fromNodeIndex) correctNodeWithoutRevert(schainId, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaintBadData( schainId, fromNodeIndex, toNodeIndex, contractManager, complaints ); } function preResponse( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, KeyShare[] memory secretKeyContribution ) external refundGasBySchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).PRE_RESPONSE_DELTA(), dkgFunction: DkgFunction.PreResponse })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgPreResponse.preResponse( schainId, fromNodeIndex, verificationVector, verificationVectorMult, secretKeyContribution, contractManager, complaints, hashedData ); } function complaint(bytes32 schainId, uint fromNodeIndex, uint toNodeIndex) external refundGasByValidatorToSchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_DELTA(), dkgFunction: DkgFunction.Complaint })) correctGroupWithoutRevert(schainId) correctNode(schainId, fromNodeIndex) correctNodeWithoutRevert(schainId, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaint( schainId, fromNodeIndex, toNodeIndex, contractManager, channels, complaints, startAlrightTimestamp ); } function response( bytes32 schainId, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point memory multipliedShare ) external refundGasByValidatorToSchain( schainId, Context({isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).RESPONSE_DELTA(), dkgFunction: DkgFunction.Response })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgResponse.response( schainId, fromNodeIndex, secretNumber, multipliedShare, contractManager, channels, complaints ); } /** * @dev Allows Schains and NodeRotation contracts to open a channel. * * Emits a {ChannelOpened} event. * * Requirements: * * - Channel is not already created. */ function openChannel(bytes32 schainId) external override allowTwo("Schains","NodeRotation") { _openChannel(schainId); } /** * @dev Allows SchainsInternal contract to delete a channel. * * Requirements: * * - Channel must exist. */ function deleteChannel(bytes32 schainId) external override allow("SchainsInternal") { delete channels[schainId]; delete dkgProcess[schainId]; delete complaints[schainId]; KeyStorage(contractManager.getContract("KeyStorage")).deleteKey(schainId); } function setStartAlrightTimestamp(bytes32 schainId) external allow("SkaleDKG") { startAlrightTimestamp[schainId] = now; } function setBadNode(bytes32 schainId, uint nodeIndex) external allow("SkaleDKG") { _badNodes[schainId] = nodeIndex; } function finalizeSlashing(bytes32 schainId, uint badNode) external allow("SkaleDKG") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); emit BadGuy(badNode); emit FailedDKG(schainId); schainsInternal.makeSchainNodesInvisible(schainId); if (schainsInternal.isAnyFreeNode(schainId)) { uint newNode = nodeRotation.rotateNode( badNode, schainId, false, true ); emit NewGuy(newNode); } else { _openChannel(schainId); schainsInternal.removeNodeFromSchain( badNode, schainId ); channels[schainId].active = false; } schainsInternal.makeSchainNodesVisible(schainId); Punisher(contractManager.getPunisher()).slash( Nodes(contractManager.getContract("Nodes")).getValidatorId(badNode), SlashingTable(contractManager.getContract("SlashingTable")).getPenalty("FailedDKG") ); } function getChannelStartedTime(bytes32 schainId) external view returns (uint) { return channels[schainId].startedBlockTimestamp; } function getChannelStartedBlock(bytes32 schainId) external view returns (uint) { return channels[schainId].startedBlock; } function getNumberOfBroadcasted(bytes32 schainId) external view returns (uint) { return dkgProcess[schainId].numberOfBroadcasted; } function getNumberOfCompleted(bytes32 schainId) external view returns (uint) { return dkgProcess[schainId].numberOfCompleted; } function getTimeOfLastSuccessfulDKG(bytes32 schainId) external view returns (uint) { return lastSuccesfulDKG[schainId]; } function getComplaintData(bytes32 schainId) external view returns (uint, uint) { return (complaints[schainId].fromNodeToComplaint, complaints[schainId].nodeToComplaint); } function getComplaintStartedTime(bytes32 schainId) external view returns (uint) { return complaints[schainId].startComplaintBlockTimestamp; } function getAlrightStartedTime(bytes32 schainId) external view returns (uint) { return startAlrightTimestamp[schainId]; } /** * @dev Checks whether channel is opened. */ function isChannelOpened(bytes32 schainId) external override view returns (bool) { return channels[schainId].active; } function isLastDKGSuccessful(bytes32 schainId) external override view returns (bool) { return channels[schainId].startedBlockTimestamp <= lastSuccesfulDKG[schainId]; } /** * @dev Checks whether broadcast is possible. */ function isBroadcastPossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && !dkgProcess[schainId].broadcasted[index]; } /** * @dev Checks whether complaint is possible. */ function isComplaintPossible( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex ) external view returns (bool) { (uint indexFrom, bool checkFrom) = checkAndReturnIndexInGroup(schainId, fromNodeIndex, false); (uint indexTo, bool checkTo) = checkAndReturnIndexInGroup(schainId, toNodeIndex, false); if (!checkFrom || !checkTo) return false; bool complaintSending = ( complaints[schainId].nodeToComplaint == uint(-1) && dkgProcess[schainId].broadcasted[indexTo] && !dkgProcess[schainId].completed[indexFrom] ) || ( dkgProcess[schainId].broadcasted[indexTo] && complaints[schainId].startComplaintBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp && complaints[schainId].nodeToComplaint == toNodeIndex ) || ( !dkgProcess[schainId].broadcasted[indexTo] && complaints[schainId].nodeToComplaint == uint(-1) && channels[schainId].startedBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp ) || ( complaints[schainId].nodeToComplaint == uint(-1) && isEveryoneBroadcasted(schainId) && dkgProcess[schainId].completed[indexFrom] && !dkgProcess[schainId].completed[indexTo] && startAlrightTimestamp[schainId].add(_getComplaintTimelimit()) <= block.timestamp ); return channels[schainId].active && dkgProcess[schainId].broadcasted[indexFrom] && _isNodeOwnedByMessageSender(fromNodeIndex, msg.sender) && complaintSending; } /** * @dev Checks whether sending Alright response is possible. */ function isAlrightPossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && channels[schainId].n == dkgProcess[schainId].numberOfBroadcasted && (complaints[schainId].fromNodeToComplaint != nodeIndex || (nodeIndex == 0 && complaints[schainId].startComplaintBlockTimestamp == 0)) && !dkgProcess[schainId].completed[index]; } /** * @dev Checks whether sending a pre-response is possible. */ function isPreResponsePossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainId].nodeToComplaint == nodeIndex && !complaints[schainId].isResponse; } /** * @dev Checks whether sending a response is possible. */ function isResponsePossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainId].nodeToComplaint == nodeIndex && complaints[schainId].isResponse; } function isNodeBroadcasted(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return check && dkgProcess[schainId].broadcasted[index]; } /** * @dev Checks whether all data has been received by node. */ function isAllDataReceived(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return check && dkgProcess[schainId].completed[index]; } function hashData( KeyShare[] memory secretKeyContribution, G2Operations.G2Point[] memory verificationVector ) external pure returns (bytes32) { bytes memory data; for (uint i = 0; i < secretKeyContribution.length; i++) { data = abi.encodePacked(data, secretKeyContribution[i].publicKey, secretKeyContribution[i].share); } for (uint i = 0; i < verificationVector.length; i++) { data = abi.encodePacked( data, verificationVector[i].x.a, verificationVector[i].x.b, verificationVector[i].y.a, verificationVector[i].y.b ); } return keccak256(data); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function checkAndReturnIndexInGroup( bytes32 schainId, uint nodeIndex, bool revertCheck ) public view returns (uint, bool) { uint index = SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainId, nodeIndex); if (index >= channels[schainId].n && revertCheck) { revert("Node is not in this group"); } return (index, index < channels[schainId].n); } function _refundGasBySchain(bytes32 schainId, uint gasTotal, Context memory context) private { Wallets wallets = Wallets(payable(contractManager.getContract("Wallets"))); bool isLastNode = channels[schainId].n == dkgProcess[schainId].numberOfCompleted; if (context.dkgFunction == DkgFunction.Alright && isLastNode) { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(74800), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 2e6) { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(640000), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 1e6) { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(270000), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Response){ wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).sub(context.delta), context.isDebt ); } else { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta), context.isDebt ); } } function _refundGasByValidatorToSchain(bytes32 schainId) private { uint validatorId = Nodes(contractManager.getContract("Nodes")) .getValidatorId(_badNodes[schainId]); Wallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidatorToSchain(validatorId, schainId); delete _badNodes[schainId]; } function _openChannel(bytes32 schainId) private { SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); uint len = schainsInternal.getNumberOfNodesInGroup(schainId); channels[schainId].active = true; channels[schainId].n = len; delete dkgProcess[schainId].completed; delete dkgProcess[schainId].broadcasted; dkgProcess[schainId].broadcasted = new bool[](len); dkgProcess[schainId].completed = new bool[](len); complaints[schainId].fromNodeToComplaint = uint(-1); complaints[schainId].nodeToComplaint = uint(-1); delete complaints[schainId].startComplaintBlockTimestamp; delete dkgProcess[schainId].numberOfBroadcasted; delete dkgProcess[schainId].numberOfCompleted; channels[schainId].startedBlockTimestamp = now; channels[schainId].startedBlock = block.number; KeyStorage(contractManager.getContract("KeyStorage")).initPublicKeyInProgress(schainId); emit ChannelOpened(schainId); } function isEveryoneBroadcasted(bytes32 schainId) public view returns (bool) { return channels[schainId].n == dkgProcess[schainId].numberOfBroadcasted; } function _isNodeOwnedByMessageSender(uint nodeIndex, address from) private view returns (bool) { return Nodes(contractManager.getContract("Nodes")).isNodeExist(from, nodeIndex); } function _checkMsgSenderIsNodeOwner(uint nodeIndex) private view { require(_isNodeOwnedByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender"); } function _getComplaintTimelimit() private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit(); } } // SPDX-License-Identifier: AGPL-3.0-only /* Wallets.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; import "./delegation/ValidatorService.sol"; import "./SchainsInternal.sol"; import "./Nodes.sol"; /** * @title Wallets * @dev Contract contains logic to perform automatic self-recharging ether for nodes */ contract Wallets is Permissions { mapping (uint => uint) private _validatorWallets; mapping (bytes32 => uint) private _schainWallets; mapping (bytes32 => uint) private _schainDebts; /** * @dev Emitted when the validator wallet was funded */ event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId); /** * @dev Emitted when the schain wallet was funded */ event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainId); /** * @dev Emitted when the node received a refund from validator to its wallet */ event NodeRefundedByValidator(address node, uint validatorId, uint amount); /** * @dev Emitted when the node received a refund from schain to its wallet */ event NodeRefundedBySchain(address node, bytes32 schainId, uint amount); /** * @dev Is executed on a call to the contract with empty calldata. * This is the function that is executed on plain Ether transfers, * so validator or schain owner can use usual transfer ether to recharge wallet. */ receive() external payable { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schainIds = schainsInternal.getSchainIdsByAddress(msg.sender); if (schainIds.length == 1) { rechargeSchainWallet(schainIds[0]); } else { uint validatorId = validatorService.getValidatorId(msg.sender); rechargeValidatorWallet(validatorId); } } /** * @dev Reimburse gas for node by validator wallet. If validator wallet has not enough funds * the node will receive the entire remaining amount in the validator's wallet. * `validatorId` - validator that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * * Emits a {NodeRefundedByValidator} event. * * Requirements: * - Given validator should exist */ function refundGasByValidator( uint validatorId, address payable spender, uint spentGas ) external allowTwo("SkaleManager", "SkaleDKG") { require(validatorId != 0, "ValidatorId could not be zero"); uint amount = tx.gasprice * spentGas; if (amount <= _validatorWallets[validatorId]) { _validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount); emit NodeRefundedByValidator(spender, validatorId, amount); spender.transfer(amount); } else { uint wholeAmount = _validatorWallets[validatorId]; // solhint-disable-next-line reentrancy delete _validatorWallets[validatorId]; emit NodeRefundedByValidator(spender, validatorId, wholeAmount); spender.transfer(wholeAmount); } } /** * @dev Returns the amount owed to the owner of the chain by the validator, * if the validator does not have enough funds, then everything * that the validator has will be returned to the owner of the chain. */ function refundGasByValidatorToSchain(uint validatorId, bytes32 schainId) external allow("SkaleDKG") { uint debtAmount = _schainDebts[schainId]; uint validatorWallet = _validatorWallets[validatorId]; if (debtAmount <= validatorWallet) { _validatorWallets[validatorId] = validatorWallet.sub(debtAmount); } else { debtAmount = validatorWallet; delete _validatorWallets[validatorId]; } _schainWallets[schainId] = _schainWallets[schainId].add(debtAmount); delete _schainDebts[schainId]; } /** * @dev Reimburse gas for node by schain wallet. If schain wallet has not enough funds * than transaction will be reverted. * `schainId` - schain that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * `isDebt` - parameter that indicates whether this amount should be recorded as debt for the validator * * Emits a {NodeRefundedBySchain} event. * * Requirements: * - Given schain should exist * - Schain wallet should have enough funds */ function refundGasBySchain( bytes32 schainId, address payable spender, uint spentGas, bool isDebt ) external allowTwo("SkaleDKG", "MessageProxyForMainnet") { uint amount = tx.gasprice * spentGas; if (isDebt) { amount += (_schainDebts[schainId] == 0 ? 21000 : 6000) * tx.gasprice; _schainDebts[schainId] = _schainDebts[schainId].add(amount); } require(schainId != bytes32(0), "SchainId cannot be null"); require(amount <= _schainWallets[schainId], "Schain wallet has not enough funds"); _schainWallets[schainId] = _schainWallets[schainId].sub(amount); emit NodeRefundedBySchain(spender, schainId, amount); spender.transfer(amount); } /** * @dev Withdraws money from schain wallet. Possible to execute only after deleting schain. * `schainOwner` - address of schain owner that will receive rest of the schain balance * `schainId` - schain wallet from which money is withdrawn * * Requirements: * - Executable only after initing delete schain */ function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainId) external allow("Schains") { uint amount = _schainWallets[schainId]; delete _schainWallets[schainId]; schainOwner.transfer(amount); } /** * @dev Withdraws money from vaildator wallet. * `amount` - the amount of money in wei * * Requirements: * - Validator must have sufficient withdrawal amount */ function withdrawFundsFromValidatorWallet(uint amount) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = validatorService.getValidatorId(msg.sender); require(amount <= _validatorWallets[validatorId], "Balance is too low"); _validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount); msg.sender.transfer(amount); } function getSchainBalance(bytes32 schainId) external view returns (uint) { return _schainWallets[schainId]; } function getValidatorBalance(uint validatorId) external view returns (uint) { return _validatorWallets[validatorId]; } /** * @dev Recharge the validator wallet by id. * `validatorId` - id of existing validator. * * Emits a {ValidatorWalletRecharged} event. * * Requirements: * - Given validator must exist */ function rechargeValidatorWallet(uint validatorId) public payable { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator does not exists"); _validatorWallets[validatorId] = _validatorWallets[validatorId].add(msg.value); emit ValidatorWalletRecharged(msg.sender, msg.value, validatorId); } /** * @dev Recharge the schain wallet by schainId (hash of schain name). * `schainId` - id of existing schain. * * Emits a {SchainWalletRecharged} event. * * Requirements: * - Given schain must be created */ function rechargeSchainWallet(bytes32 schainId) public payable { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainActive(schainId), "Schain should be active for recharging"); _schainWallets[schainId] = _schainWallets[schainId].add(msg.value); emit SchainWalletRecharged(msg.sender, msg.value, schainId); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* KeyStorage.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Decryption.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 schainId) external allow("SkaleDKG") { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); delete _schainsPublicKeys[schainId]; delete _data[schainId][0]; delete _schainsNodesPublicKeys[schainId]; } function initPublicKeyInProgress(bytes32 schainId) external allow("SkaleDKG") { _publicKeysInProgress[schainId] = G2Operations.getG2Zero(); } function adding(bytes32 schainId, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[schainId] = value.addG2(_publicKeysInProgress[schainId]); } function finalizePublicKey(bytes32 schainId) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(schainId)) { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); } _schainsPublicKeys[schainId] = _publicKeysInProgress[schainId]; delete _publicKeysInProgress[schainId]; } function getCommonPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[schainId]; } function getPreviousPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[schainId].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[schainId][length - 1]; } function getAllPreviousPublicKeys(bytes32 schainId) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[schainId]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) { return _schainsPublicKeys[schainId].x.a == 0 && _schainsPublicKeys[schainId].x.b == 0 && _schainsPublicKeys[schainId].y.a == 0 && _schainsPublicKeys[schainId].y.b == 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* SlashingTable.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title Slashing Table * @dev This contract manages slashing conditions and penalties. */ contract SlashingTable is Permissions { mapping (uint => uint) private _penalties; /** * @dev Allows the Owner to set a slashing penalty in SKL tokens for a * given offense. */ function setPenalty(string calldata offense, uint penalty) external onlyOwner { _penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty; } /** * @dev Returns the penalty in SKL tokens for a given offense. */ function getPenalty(string calldata offense) external view returns (uint) { uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))]; return penalty; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* Schains.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./ConstantsHolder.sol"; import "./KeyStorage.sol"; import "./SkaleVerifier.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./interfaces/ISkaleDKG.sol"; import "./Wallets.sol"; /** * @title Schains * @dev Contains functions to manage Schains such as Schain creation, * deletion, and rotation. */ contract Schains is Permissions { struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainId, uint time, uint gasSpend ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainId ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainId, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainId, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainId, uint[] nodesInGroup, uint time, uint gasSpend ); /** * @dev Allows SkaleManager contract to create an Schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type is valid. * - There is sufficient deposit to create type of schain. */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } /** * @dev Allows the foundation to create an Schain without tokens. * * Emits an {SchainCreated} event. * * Requirements: * * - sender is granted with SCHAIN_CREATOR_ROLE * - Schain type is valid. */ function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name, address schainOwner ) external payable { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); address _schainOwner; if (schainOwner != address(0)) { _schainOwner = schainOwner; } else { _schainOwner = msg.sender; } _addSchain(_schainOwner, 0, schainParameters); bytes32 schainId = keccak256(abi.encodePacked(name)); Wallets(payable(contractManager.getContract("Wallets"))).rechargeSchainWallet{value: msg.value}(schainId); } /** * @dev Allows SkaleManager to remove an schain from the network. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Executed by schain owner. */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not the owner of the Schain" ); _deleteSchain(name, schainsInternal); } /** * @dev Allows SkaleManager to delete any Schain. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Schain exists. */ function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { _deleteSchain(name, SchainsInternal(contractManager.getContract("SchainsInternal"))); } /** * @dev Allows SkaleManager contract to restart schain creation by forming a * new schain group. Executed when DKG procedure fails and becomes stuck. * * Emits a {NodeAdded} event. * * Requirements: * * - Previous DKG procedure must have failed. * - DKG failure got stuck because there were no free nodes to rotate in. * - A free node must be released in the network. */ function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccessful(schainId), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes for new group formation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId); skaleDKG.openChannel(schainId); emit NodeAdded(schainId, newNodeIndex); } /** * @dev addSpace - return occupied space to Node * nodeIndex - index of Node at common array of Nodes * partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev Checks whether schain group signature is valid. */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Returns the current price in SKL tokens for given Schain type and lifetime. */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (divisor, numberOfNodes) = schainsInternal.getSchainType(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev Initializes an schain in the SchainsInternal contract. * * Requirements: * * - Schain name is not already in use. */ function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime, SchainsInternal schainsInternal ) private { require(schainsInternal.isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain schainsInternal.initializeSchain(name, from, lifetime, deposit); schainsInternal.setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev Converts data from bytes to normal schain parameters of lifetime, * type, nonce, and name. */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev Allows creation of node group for Schain. * * Emits an {SchainNodes} event. */ function _createGroupForSchain( string memory schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode, SchainsInternal schainsInternal ) private { uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId); emit SchainNodes( schainName, schainId, nodesInGroup, block.timestamp, gasleft()); } /** * @dev Creates an schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type must be valid. */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime, schainsInternal ); // create a group for Schain uint numberOfNodes; uint8 partOfNode; (partOfNode, numberOfNodes) = schainsInternal.getSchainType(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode, schainsInternal ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } function _deleteSchain(string calldata name, SchainsInternal schainsInternal) private { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); this.addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainId); address from = schainsInternal.getSchainOwner(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); Wallets(payable(contractManager.getContract("Wallets"))).withdrawFundsFromSchainWallet(payable(from), schainId); emit SchainDeleted(from, name, schainId); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternal.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./interfaces/ISkaleDKG.sol"; import "./utils/Random.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol"; /** * @title SchainsInternal * @dev Contract contains all functionality logic to internally manage Schains. */ contract SchainsInternal is Permissions { using Random for Random.RandomGenerator; using EnumerableSet for EnumerableSet.UintSet; struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; mapping (uint => SchainType) public schainTypes; uint public numberOfSchainTypes; // schain hash => node index => index of place // index of place is a number from 1 to max number of slots on node(128) mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode; mapping (uint => bytes32[]) private _nodeToLockedSchains; mapping (bytes32 => uint[]) private _schainToExceptionNodes; EnumerableSet.UintSet private _keysOfSchainTypes; /** * @dev Allows Schain contract to initialize an schain. */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = block.timestamp; schains[schainId].startBlock = block.number; schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; isSchainActive[schainId] = true; numberOfSchains++; schainsAtSystem.push(schainId); usedSchainNames[schainId] = true; } /** * @dev Allows Schain contract to create a node group for an schain. */ function createGroupForSchain( bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainId, numberOfNodes); } /** * @dev Allows Schains contract to set index in owner list. */ function setSchainIndex(bytes32 schainId, address from) external allow("Schains") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev Allows Schains contract to change the Schain lifetime through * an additional SKL token deposit. */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") { schains[schainId].deposit = schains[schainId].deposit.add(deposit); schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime); } /** * @dev Allows Schains contract to remove an schain from the network. * Generally schains are not removed from the system; instead they are * simply allowed to expire. */ function removeSchain(bytes32 schainId, address from) external allow("Schains") { isSchainActive[schainId] = false; uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainId = schainIndexes[from][length.sub(1)]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainId]; numberOfSchains--; } /** * @dev Allows Schains and SkaleDKG contracts to remove a node from an * schain for node rotation or DKG failure. */ function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external allowThree("NodeRotation", "SkaleDKG", "Schains") { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length.sub(1); if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash); removeSchainForNode(nodeIndex, schainIndexOnNode); delete placeOfSchainOnNode[schainHash][nodeIndex]; } /** * @dev Allows Schains contract to delete a group of schains */ function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; skaleDKG.deleteChannel(schainId); } /** * @dev Allows Schain and NodeRotation contracts to set a Node like * exception for a given schain and nodeIndex. */ function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _setException(schainId, nodeIndex); } /** * @dev Allows Schains and NodeRotation contracts to add node to an schain * group. */ function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainId].length == 0) { schainsGroups[schainId].push(nodeIndex); } else { schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainId].length; i++) { if (min > holesForSchains[schainId][i]) { min = holesForSchains[schainId][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainId]; } else { holesForSchains[schainId][0] = min; holesForSchains[schainId][index] = holesForSchains[schainId][holesForSchains[schainId].length - 1]; holesForSchains[schainId].pop(); } } } /** * @dev Allows Schains contract to remove holes for schains */ function removeHolesForSchain(bytes32 schainHash) external allow("Schains") { delete holesForSchains[schainHash]; } /** * @dev Allows Admin to add schain type */ function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlyAdmin { require(_keysOfSchainTypes.add(numberOfSchainTypes + 1), "Schain type is already added"); schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode; schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes; numberOfSchainTypes++; } /** * @dev Allows Admin to remove schain type */ function removeSchainType(uint typeOfSchain) external onlyAdmin { require(_keysOfSchainTypes.remove(typeOfSchain), "Schain type is already removed"); delete schainTypes[typeOfSchain].partOfNode; delete schainTypes[typeOfSchain].numberOfNodes; } /** * @dev Allows Admin to set number of schain types */ function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlyAdmin { numberOfSchainTypes = newNumberOfSchainTypes; } /** * @dev Allows Admin to move schain to placeOfSchainOnNode map */ function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyAdmin { for (uint i = 0; i < schainsGroups[schainHash].length; i++) { uint nodeIndex = schainsGroups[schainHash][i]; for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) { if (schainsForNodes[nodeIndex][j] == schainHash) { placeOfSchainOnNode[schainHash][nodeIndex] = j + 1; } } } } function removeNodeFromAllExceptionSchains(uint nodeIndex) external allow("SkaleManager") { uint len = _nodeToLockedSchains[nodeIndex].length; if (len > 0) { for (uint i = len; i > 0; i--) { removeNodeFromExceptions(_nodeToLockedSchains[nodeIndex][i - 1], nodeIndex); } } } function makeSchainNodesInvisible(bytes32 schainId) external allowTwo("NodeRotation", "SkaleDKG") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainId].length; i++) { nodes.makeNodeInvisible(_schainToExceptionNodes[schainId][i]); } } function makeSchainNodesVisible(bytes32 schainId) external allowTwo("NodeRotation", "SkaleDKG") { _makeSchainNodesVisible(schainId); } /** * @dev Returns all Schains in the network. */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev Returns all occupied resources on one node for an Schain. */ function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) { return schains[schainId].partOfNode; } /** * @dev Returns number of schains by schain owner. */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns the owner of an schain. */ function getSchainOwner(bytes32 schainId) external view returns (address) { return schains[schainId].owner; } /** * @dev Checks whether schain name is available. * TODO Need to delete - copy of web3.utils.soliditySha3 */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0) && !usedSchainNames[schainId] && keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet")); } /** * @dev Checks whether schain lifetime has expired. */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp; } /** * @dev Checks whether address is owner of schain. */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } /** * @dev Checks whether schain exists. */ function isSchainExist(bytes32 schainId) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked("")); } /** * @dev Returns schain name. */ function getSchainName(bytes32 schainId) external view returns (string memory) { return schains[schainId].name; } /** * @dev Returns last active schain of a node. */ function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } /** * @dev Returns active schains of a node. */ function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev Returns number of nodes in an schain group. */ function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) { return schainsGroups[schainId].length; } /** * @dev Returns nodes in an schain group. */ function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) { return schainsGroups[schainId]; } /** * @dev Checks whether sender is a node address from a given schain group. */ function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < schainsGroups[schainId].length; i++) { if (nodes.getNodeAddress(schainsGroups[schainId][i]) == sender) { return true; } } return false; } /** * @dev Returns node index in schain group. */ function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainId].length; index++) { if (schainsGroups[schainId][index] == nodeId) { return index; } } return schainsGroups[schainId].length; } /** * @dev Checks whether there are any nodes with free resources for given * schain. */ function isAnyFreeNode(bytes32 schainId) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; return nodes.countNodesWithFreeSpace(space) > 0; } /** * @dev Returns whether any exceptions exist for node in a schain group. */ function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainId][nodeIndex]; } function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } /** * @dev Returns number of Schains on a node. */ function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) { return schainsForNodes[nodeIndex].length; } function getSchainType(uint typeOfSchain) external view returns(uint8, uint) { require(_keysOfSchainTypes.contains(typeOfSchain), "Invalid type of schain"); return (schainTypes[typeOfSchain].partOfNode, schainTypes[typeOfSchain].numberOfNodes); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; numberOfSchainTypes = 0; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. */ function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); placeOfSchainOnNode[schainId][nodeIndex] = schainsForNodes[nodeIndex].length; } else { uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; schainsForNodes[nodeIndex][lastHoleOfNode] = schainId; placeOfSchainOnNode[schainId][nodeIndex] = lastHoleOfNode + 1; holesForNodes[nodeIndex].pop(); } } /** * @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an * schain from a node. */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length.sub(1)) { schainsForNodes[nodeIndex].pop(); } else { delete schainsForNodes[nodeIndex][schainIndex]; if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Allows Schains contract to remove node from exceptions */ function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) public allowThree("Schains", "NodeRotation", "SkaleManager") { _exceptionsForGroups[schainHash][nodeIndex] = false; uint len = _nodeToLockedSchains[nodeIndex].length; bool removed = false; if (len > 0 && _nodeToLockedSchains[nodeIndex][len - 1] == schainHash) { _nodeToLockedSchains[nodeIndex].pop(); removed = true; } else { for (uint i = len; i > 0 && !removed; i--) { if (_nodeToLockedSchains[nodeIndex][i - 1] == schainHash) { _nodeToLockedSchains[nodeIndex][i - 1] = _nodeToLockedSchains[nodeIndex][len - 1]; _nodeToLockedSchains[nodeIndex].pop(); removed = true; } } } len = _schainToExceptionNodes[schainHash].length; removed = false; if (len > 0 && _schainToExceptionNodes[schainHash][len - 1] == nodeIndex) { _schainToExceptionNodes[schainHash].pop(); removed = true; } else { for (uint i = len; i > 0 && !removed; i--) { if (_schainToExceptionNodes[schainHash][i - 1] == nodeIndex) { _schainToExceptionNodes[schainHash][i - 1] = _schainToExceptionNodes[schainHash][len - 1]; _schainToExceptionNodes[schainHash].pop(); removed = true; } } } } /** * @dev Returns index of Schain in list of schains for a given node. */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { if (placeOfSchainOnNode[schainId][nodeIndex] == 0) return schainsForNodes[nodeIndex].length; return placeOfSchainOnNode[schainId][nodeIndex] - 1; } function _getNodeToLockedSchains() internal view returns (mapping(uint => bytes32[]) storage) { return _nodeToLockedSchains; } function _getSchainToExceptionNodes() internal view returns (mapping(bytes32 => uint[]) storage) { return _schainToExceptionNodes; } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); require(nodes.countNodesWithFreeSpace(space) >= nodesInGroup.length, "Not enough nodes to create Schain"); Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId) ); for (uint i = 0; i < numberOfNodes; i++) { uint node = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); nodesInGroup[i] = node; _setException(schainId, node); addSchainForNode(node, schainId); nodes.makeNodeInvisible(node); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; _makeSchainNodesVisible(schainId); } function _setException(bytes32 schainId, uint nodeIndex) private { _exceptionsForGroups[schainId][nodeIndex] = true; _nodeToLockedSchains[nodeIndex].push(schainId); _schainToExceptionNodes[schainId].push(nodeIndex); } function _makeSchainNodesVisible(bytes32 schainId) private { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainId].length; i++) { nodes.makeNodeVisible(_schainToExceptionNodes[schainId][i]); } } /** * @dev Returns local index of node in schain group. */ function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainId]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } // SPDX-License-Identifier: AGPL-3.0-only /* FieldOperations.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Precompiled.sol"; library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - subtracted.a, p); } else { difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - subtracted.b, p); } else { difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = (p - addmod(t2, p - t0, p)).mod(p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = (p - mulmod(value.b, t3, p)).mod(p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G1Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return point.a < Fp2Operations.P && point.b < Fp2Operations.P; } function negate(uint y) internal pure returns (uint) { return Fp2Operations.P.sub(y).mod(Fp2Operations.P); } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2Generator() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = (p - sum.y.a).mod(p); sum.y.b = (p - sum.y.b).mod(p); } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = (p - result.y.a).mod(p); result.y.b = (p - result.y.b).mod(p); } } } // SPDX-License-Identifier: AGPL-3.0-only /* NodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./interfaces/ISkaleDKG.sol"; import "./utils/Random.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./Schains.sol"; /** * @title NodeRotation * @dev This contract handles all node rotation functionality. */ contract NodeRotation is Permissions { using Random for Random.RandomGenerator; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool, bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); if (schainId == bytes32(0)) { return (true, false); } _startRotation(schainId, nodeIndex); rotateNode(nodeIndex, schainId, true, false); return (schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false, true); } /** * @dev Allows SkaleManager contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external allow("SkaleManager") { bytes32[] memory schains = SchainsInternal( contractManager.getContract("SchainsInternal") ).getSchainIdsForNode(nodeIndex); for (uint i = 0; i < schains.length; i++) { if (schains[i] != bytes32(0)) { require( ISkaleDKG(contractManager.getContract("SkaleDKG")).isLastDKGSuccessful(schains[i]), "DKG did not finish on Schain" ); if (rotations[schains[i]].freezeUntil < now) { _startWaiting(schains[i], nodeIndex); } else { if (rotations[schains[i]].nodeIndex != nodeIndex) { revert("Occupied by rotation on Schain"); } } } } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainIndex) external onlyOwner { rotations[schainIndex].freezeUntil = now; } /** * @dev Returns rotation details for a given schain. */ function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { return rotations[schainIndex]; } /** * @dev Returns leaving history for a given node. */ function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainIndex) external view returns (bool) { return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an * schain. */ function rotateNode( uint nodeIndex, bytes32 schainId, bool shouldDelay, bool isBadNode ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); if (!isBadNode) { schainsInternal.removeNodeFromExceptions(schainId, nodeIndex); } newNode = selectNodeToGroup(schainId); Nodes(contractManager.getContract("Nodes")).addSpaceToNode( nodeIndex, schainsInternal.getSchainsPartOfNode(schainId) ); _finishRotation(schainId, nodeIndex, newNode, shouldDelay); } /** * @dev Allows SkaleManager, Schains, and SkaleDKG contracts to * pseudo-randomly select a new Node for an Schain. * * Requirements: * * - Schain is active. * - A free node already exists. * - Free space can be allocated from the node. */ function selectNodeToGroup(bytes32 schainId) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint nodeIndex) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainId), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); schainsInternal.makeSchainNodesInvisible(schainId); require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes available for rotation"); Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), schainId) ); nodeIndex = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.makeSchainNodesVisible(schainId); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainIndex, uint nodeIndex) private { rotations[schainIndex].newNodeIndex = nodeIndex; waitForNewNode[schainIndex] = true; } function _startWaiting(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { leavingHistory[nodeIndex].push( LeavingHistory( schainIndex, shouldDelay ? now.add( ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() ) : now ) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } /** * @dev Checks whether a rotation can be performed. * * Requirements: * * - Schain must exist. */ function _checkRotation(bytes32 schainId ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainId); } } // SPDX-License-Identifier: AGPL-3.0-only /* ISkaleDKG.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface to {SkaleDKG}. */ interface ISkaleDKG { /** * @dev See {SkaleDKG-openChannel}. */ function openChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-deleteChannel}. */ function deleteChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-isLastDKGSuccessful}. */ function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool); /** * @dev See {SkaleDKG-isChannelOpened}. */ function isChannelOpened(bytes32 schainId) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later /* Modifications Copyright (C) 2018 SKALE Labs ec.sol by @jbaylina under GPL-3.0 License */ /** @file ECDH.sol * @author Jordi Baylina (@jbaylina) * @date 2016 */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title ECDH * @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to * support the DKG process. */ contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { require(a > 0 && a < _N, "Input is incorrect"); uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; // we use (0 0 1) as zero point, z always equal 1 if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } // we use (0 0 1) as zero point, z always equal 1 if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } // SPDX-License-Identifier: AGPL-3.0-only /* Precompiled.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgBroadcast.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../SkaleDKG.sol"; import "../KeyStorage.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgBroadcast * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgBroadcast { using SafeMath for uint; /** * @dev Emitted when a node broadcasts keyshare. */ event BroadcastAndKeyShare( bytes32 indexed schainId, uint indexed fromNode, G2Operations.G2Point[] verificationVector, SkaleDKG.KeyShare[] secretKeyContribution ); /** * @dev Broadcasts verification vector and secret key contribution to all * other nodes in the group. * * Emits BroadcastAndKeyShare event. * * Requirements: * * - `msg.sender` must have an associated node. * - `verificationVector` must be a certain length. * - `secretKeyContribution` length must be equal to number of nodes in group. */ function broadcast( bytes32 schainId, uint nodeIndex, G2Operations.G2Point[] memory verificationVector, SkaleDKG.KeyShare[] memory secretKeyContribution, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) external { uint n = channels[schainId].n; require(verificationVector.length == getT(n), "Incorrect number of verification vectors"); require( secretKeyContribution.length == n, "Incorrect number of secret key shares" ); (uint index, ) = SkaleDKG(contractManager.getContract("SkaleDKG")).checkAndReturnIndexInGroup( schainId, nodeIndex, true ); require(!dkgProcess[schainId].broadcasted[index], "This node has already broadcasted"); dkgProcess[schainId].broadcasted[index] = true; dkgProcess[schainId].numberOfBroadcasted++; if (dkgProcess[schainId].numberOfBroadcasted == channels[schainId].n) { SkaleDKG(contractManager.getContract("SkaleDKG")).setStartAlrightTimestamp(schainId); } hashedData[schainId][index] = SkaleDKG(contractManager.getContract("SkaleDKG")).hashData( secretKeyContribution, verificationVector ); KeyStorage(contractManager.getContract("KeyStorage")).adding(schainId, verificationVector[0]); emit BroadcastAndKeyShare( schainId, nodeIndex, verificationVector, secretKeyContribution ); } function getT(uint n) public pure returns (uint) { return n.mul(2).add(1).div(3); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgComplaint.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../SkaleDKG.sol"; import "../ConstantsHolder.sol"; import "../Wallets.sol"; import "../Nodes.sol"; /** * @title SkaleDkgComplaint * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgComplaint { using SafeMath for uint; /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent( bytes32 indexed schainId, uint indexed fromNodeIndex, uint indexed toNodeIndex); /** * @dev Creates a complaint from a node (accuser) to a given node. * The accusing node must broadcast additional parameters within 1800 blocks. * * Emits {ComplaintSent} or {ComplaintError} event. * * Requirements: * * - `msg.sender` must have an associated node. */ function complaint( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted"); if (skaleDKG.isNodeBroadcasted(schainId, toNodeIndex)) { _handleComplaintWhenBroadcasted( schainId, fromNodeIndex, toNodeIndex, contractManager, complaints, startAlrightTimestamp ); } else { // not broadcasted in 30 min _handleComplaintWhenNotBroadcasted(schainId, toNodeIndex, contractManager, channels); } skaleDKG.setBadNode(schainId, toNodeIndex); } function complaintBadData( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted"); require(skaleDKG.isNodeBroadcasted(schainId, toNodeIndex), "Accused node has not broadcasted"); require(!skaleDKG.isAllDataReceived(schainId, fromNodeIndex), "Node has already sent alright"); if (complaints[schainId].nodeToComplaint == uint(-1)) { complaints[schainId].nodeToComplaint = toNodeIndex; complaints[schainId].fromNodeToComplaint = fromNodeIndex; complaints[schainId].startComplaintBlockTimestamp = block.timestamp; emit ComplaintSent(schainId, fromNodeIndex, toNodeIndex); } else { emit ComplaintError("First complaint has already been processed"); } } function _handleComplaintWhenBroadcasted( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) private { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); // missing alright if (complaints[schainId].nodeToComplaint == uint(-1)) { if ( skaleDKG.isEveryoneBroadcasted(schainId) && !skaleDKG.isAllDataReceived(schainId, toNodeIndex) && startAlrightTimestamp[schainId].add(_getComplaintTimelimit(contractManager)) <= block.timestamp ) { // missing alright skaleDKG.finalizeSlashing(schainId, toNodeIndex); return; } else if (!skaleDKG.isAllDataReceived(schainId, fromNodeIndex)) { // incorrect data skaleDKG.finalizeSlashing(schainId, fromNodeIndex); return; } emit ComplaintError("Has already sent alright"); return; } else if (complaints[schainId].nodeToComplaint == toNodeIndex) { // 30 min after incorrect data complaint if (complaints[schainId].startComplaintBlockTimestamp.add( _getComplaintTimelimit(contractManager) ) <= block.timestamp) { skaleDKG.finalizeSlashing(schainId, complaints[schainId].nodeToComplaint); return; } emit ComplaintError("The same complaint rejected"); return; } emit ComplaintError("One complaint is already sent"); } function _handleComplaintWhenNotBroadcasted( bytes32 schainId, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels ) private { if (channels[schainId].startedBlockTimestamp.add(_getComplaintTimelimit(contractManager)) <= block.timestamp) { SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainId, toNodeIndex); return; } emit ComplaintError("Complaint sent too early"); } function _getComplaintTimelimit(ContractManager contractManager) private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit(); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgPreResponse.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../Wallets.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgPreResponse * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgPreResponse { using SafeMath for uint; using G2Operations for G2Operations.G2Point; function preResponse( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, SkaleDKG.KeyShare[] memory secretKeyContribution, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); uint index = _preResponseCheck( schainId, fromNodeIndex, verificationVector, verificationVectorMult, secretKeyContribution, skaleDKG, complaints, hashedData ); _processPreResponse(secretKeyContribution[index].share, schainId, verificationVectorMult, complaints); } function _preResponseCheck( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, SkaleDKG.KeyShare[] memory secretKeyContribution, SkaleDKG skaleDKG, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) private view returns (uint index) { (uint indexOnSchain, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, fromNodeIndex, true); require(complaints[schainId].nodeToComplaint == fromNodeIndex, "Not this Node"); require(!complaints[schainId].isResponse, "Already submitted pre response data"); require( hashedData[schainId][indexOnSchain] == skaleDKG.hashData(secretKeyContribution, verificationVector), "Broadcasted Data is not correct" ); require( verificationVector.length == verificationVectorMult.length, "Incorrect length of multiplied verification vector" ); (index, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, complaints[schainId].fromNodeToComplaint, true); require( _checkCorrectVectorMultiplication(index, verificationVector, verificationVectorMult), "Multiplied verification vector is incorrect" ); } function _processPreResponse( bytes32 share, bytes32 schainId, G2Operations.G2Point[] memory verificationVectorMult, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) private { complaints[schainId].keyShare = share; complaints[schainId].sumOfVerVec = _calculateSum(verificationVectorMult); complaints[schainId].isResponse = true; } function _calculateSum(G2Operations.G2Point[] memory verificationVectorMult) private view returns (G2Operations.G2Point memory) { G2Operations.G2Point memory value = G2Operations.getG2Zero(); for (uint i = 0; i < verificationVectorMult.length; i++) { value = value.addG2(verificationVectorMult[i]); } return value; } function _checkCorrectVectorMultiplication( uint indexOnSchain, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult ) private view returns (bool) { Fp2Operations.Fp2Point memory value = G1Operations.getG1Generator(); Fp2Operations.Fp2Point memory tmp = G1Operations.getG1Generator(); for (uint i = 0; i < verificationVector.length; i++) { (tmp.a, tmp.b) = Precompiled.bn256ScalarMul(value.a, value.b, indexOnSchain.add(1) ** i); if (!_checkPairing(tmp, verificationVector[i], verificationVectorMult[i])) { return false; } } return true; } function _checkPairing( Fp2Operations.Fp2Point memory g1Mul, G2Operations.G2Point memory verificationVector, G2Operations.G2Point memory verificationVectorMult ) private view returns (bool) { require(G1Operations.checkRange(g1Mul), "g1Mul is not valid"); g1Mul.b = G1Operations.negate(g1Mul.b); Fp2Operations.Fp2Point memory one = G1Operations.getG1Generator(); return Precompiled.bn256Pairing( one.a, one.b, verificationVectorMult.x.b, verificationVectorMult.x.a, verificationVectorMult.y.b, verificationVectorMult.y.a, g1Mul.a, g1Mul.b, verificationVector.x.b, verificationVector.x.a, verificationVector.y.b, verificationVector.y.a ); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgResponse.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../Wallets.sol"; import "../Decryption.sol"; import "../Nodes.sol"; import "../thirdparty/ECDH.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgResponse * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgResponse { using G2Operations for G2Operations.G2Point; function response( bytes32 schainId, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point memory multipliedShare, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { uint index = SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainId, fromNodeIndex); require(index < channels[schainId].n, "Node is not in this group"); require(complaints[schainId].nodeToComplaint == fromNodeIndex, "Not this Node"); require(complaints[schainId].isResponse, "Have not submitted pre-response data"); uint badNode = _verifyDataAndSlash( schainId, secretNumber, multipliedShare, contractManager, complaints ); SkaleDKG(contractManager.getContract("SkaleDKG")).setBadNode(schainId, badNode); } function _verifyDataAndSlash( bytes32 schainId, uint secretNumber, G2Operations.G2Point memory multipliedShare, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) private returns (uint badNode) { bytes32[2] memory publicKey = Nodes(contractManager.getContract("Nodes")).getNodePublicKey( complaints[schainId].fromNodeToComplaint ); uint256 pkX = uint(publicKey[0]); (pkX, ) = ECDH(contractManager.getContract("ECDH")).deriveKey(secretNumber, pkX, uint(publicKey[1])); bytes32 key = bytes32(pkX); // Decrypt secret key contribution uint secret = Decryption(contractManager.getContract("Decryption")).decrypt( complaints[schainId].keyShare, sha256(abi.encodePacked(key)) ); badNode = ( _checkCorrectMultipliedShare(multipliedShare, secret) && multipliedShare.isEqual(complaints[schainId].sumOfVerVec) ? complaints[schainId].fromNodeToComplaint : complaints[schainId].nodeToComplaint ); SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainId, badNode); } function _checkCorrectMultipliedShare( G2Operations.G2Point memory multipliedShare, uint secret ) private view returns (bool) { if (!multipliedShare.isG2()) { return false; } G2Operations.G2Point memory tmp = multipliedShare; Fp2Operations.Fp2Point memory g1 = G1Operations.getG1Generator(); Fp2Operations.Fp2Point memory share = Fp2Operations.Fp2Point({ a: 0, b: 0 }); (share.a, share.b) = Precompiled.bn256ScalarMul(g1.a, g1.b, secret); require(G1Operations.checkRange(share), "share is not valid"); share.b = G1Operations.negate(share.b); require(G1Operations.isG1(share), "mulShare not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); return Precompiled.bn256Pairing( share.a, share.b, g2.x.b, g2.x.a, g2.y.b, g2.y.a, g1.a, g1.b, tmp.x.b, tmp.x.a, tmp.y.b, tmp.y.a); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleVerifier.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; /** * @title SkaleVerifier * @dev Contains verify function to perform BLS signature verification. */ contract SkaleVerifier is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; /** * @dev Verifies a BLS signature. * * Requirements: * * - Signature is in G1. * - Hash is in G1. * - G2.one in G2. * - Public Key in G2. */ function verify( Fp2Operations.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, G2Operations.G2Point calldata publicKey ) external view returns (bool) { require(G1Operations.checkRange(signature), "Signature is not valid"); if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB = G1Operations.negate(signature.b); require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { if (counter > 100) { return false; } uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord.add(counter)) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } // SPDX-License-Identifier: AGPL-3.0-only /* Decryption.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @title Decryption * @dev This contract performs encryption and decryption functions. * Decrypt is used by SkaleDKG contract to decrypt secret key contribution to * validate complaints during the DKG procedure. */ contract Decryption { /** * @dev Returns an encrypted text given a secret and a key. */ function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { return bytes32(secretNumber) ^ key; } /** * @dev Returns a secret given an encrypted text and a key. */ function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { return uint256(ciphertext ^ key); } } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferencesTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../delegation/PartialDifferences.sol"; contract PartialDifferencesTester { using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using SafeMath for uint; PartialDifferences.Sequence[] private _sequences; // PartialDifferences.Value[] private _values; function createSequence() external { _sequences.push(PartialDifferences.Sequence({firstUnprocessedMonth: 0, lastChangedMonth: 0})); } function addToSequence(uint sequence, uint diff, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); _sequences[sequence].addToSequence(diff, month); } function subtractFromSequence(uint sequence, uint diff, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); _sequences[sequence].subtractFromSequence(diff, month); } function getAndUpdateSequenceItem(uint sequence, uint month) external returns (uint) { require(sequence < _sequences.length, "Sequence does not exist"); return _sequences[sequence].getAndUpdateValueInSequence(month); } function reduceSequence( uint sequence, uint a, uint b, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(a, b); return _sequences[sequence].reduceSequence(reducingCoefficient, month); } function latestSequence() external view returns (uint id) { require(_sequences.length > 0, "There are no _sequences"); return _sequences.length.sub(1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ReentrancyTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../Permissions.sol"; import "../delegation/DelegationController.sol"; contract ReentrancyTester is Permissions, IERC777Recipient, IERC777Sender { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bool private _reentrancyCheck = false; bool private _burningAttack = false; uint private _amount = 0; constructor (address contractManagerAddress) public { Permissions.initialize(contractManagerAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensSender"), address(this)); } function tokensReceived( address /* operator */, address /* from */, address /* to */, uint256 amount, bytes calldata /* userData */, bytes calldata /* operatorData */ ) external override { if (_reentrancyCheck) { IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require( skaleToken.transfer(contractManager.getContract("SkaleToken"), amount), "Transfer is not successful"); } } function tokensToSend( address, // operator address, // from address, // to uint256, // amount bytes calldata, // userData bytes calldata // operatorData ) external override { if (_burningAttack) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.delegate( 1, _amount, 2, "D2 is even"); } } function prepareToReentracyCheck() external { _reentrancyCheck = true; } function prepareToBurningAttack() external { _burningAttack = true; } function burningAttack() external { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); _amount = skaleToken.balanceOf(address(this)); skaleToken.burn(_amount, ""); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "./delegation/Distributor.sol"; import "./delegation/ValidatorService.sol"; import "./interfaces/IMintableToken.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./NodeRotation.sol"; import "./Permissions.sol"; import "./Schains.sol"; import "./Wallets.sol"; /** * @title SkaleManager * @dev Contract contains functions for node registration and exit, bounty * management, and monitoring verdicts. */ contract SkaleManager is IERC777Recipient, Permissions { IERC1820Registry private _erc1820; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); string public version; /** * @dev Emitted when bounty is received. */ event BountyReceived( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent, uint time, uint gasSpend ); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { Schains schains = Schains( contractManager.getContract("Schains")); schains.addSchain(from, value, userData); } } function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name, string calldata domainName ) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); // validators checks inside checkPossibilityCreatingNode nodes.checkPossibilityCreatingNode(msg.sender); Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({ name: name, ip: ip, publicIp: publicIp, port: port, publicKey: publicKey, nonce: nonce, domainName: domainName }); nodes.createNode(msg.sender, params); } function nodeExit(uint nodeIndex) external { uint gasTotal = gasleft(); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint validatorId = nodes.getValidatorId(nodeIndex); bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex)); if (!permitted && validatorService.validatorAddressExists(msg.sender)) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodeRotation.freezeSchains(nodeIndex); if (nodes.isNodeActive(nodeIndex)) { require(nodes.initExit(nodeIndex), "Initialization of node exit is failed"); } require(nodes.isNodeLeaving(nodeIndex), "Node should be Leaving"); (bool completed, bool isSchains) = nodeRotation.exitFromSchain(nodeIndex); if (completed) { SchainsInternal( contractManager.getContract("SchainsInternal") ).removeNodeFromAllExceptionSchains(nodeIndex); require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed"); nodes.changeNodeFinishTime( nodeIndex, now.add( isSchains ? ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() : 0 ) ); nodes.deleteNodeForValidator(validatorId, nodeIndex); } _refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft()); } function deleteSchain(string calldata name) external { Schains schains = Schains(contractManager.getContract("Schains")); // schain owner checks inside deleteSchain schains.deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external onlyAdmin { Schains schains = Schains(contractManager.getContract("Schains")); schains.deleteSchainByRoot(name); } function getBounty(uint nodeIndex) external { uint gasTotal = gasleft(); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(nodes.isTimeForReward(nodeIndex), "Not time for bounty"); require(!nodes.isNodeLeft(nodeIndex), "The node must not be in Left state"); BountyV2 bountyContract = BountyV2(contractManager.getContract("Bounty")); uint bounty = bountyContract.calculateBounty(nodeIndex); nodes.changeNodeLastRewardDate(nodeIndex); uint validatorId = nodes.getValidatorId(nodeIndex); if (bounty > 0) { _payBounty(bounty, validatorId); } emit BountyReceived( nodeIndex, msg.sender, 0, 0, bounty, uint(-1), block.timestamp, gasleft()); _refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft()); } function setVersion(string calldata newVersion) external onlyOwner { version = newVersion; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function _payBounty(uint bounty, uint validatorId) private returns (bool) { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); Distributor distributor = Distributor(contractManager.getContract("Distributor")); require( IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""), "Token was not minted" ); } function _refundGasByValidator(uint validatorId, address payable spender, uint spentGas) private { uint gasCostOfRefundGasByValidator = 29000; Wallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidator(validatorId, spender, spentGas + gasCostOfRefundGasByValidator); } } // SPDX-License-Identifier: AGPL-3.0-only /* Distributor.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "../utils/MathUtils.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; import "./DelegationPeriodManager.sol"; import "./TimeHelpers.sol"; /** * @title Distributor * @dev This contract handles all distribution functions of bounty and fee * payments. */ contract Distributor is Permissions, IERC777Recipient { using MathUtils for uint; /** * @dev Emitted when bounty is withdrawn. */ event WithdrawBounty( address holder, uint validatorId, address destination, uint amount ); /** * @dev Emitted when a validator fee is withdrawn. */ event WithdrawFee( uint validatorId, address destination, uint amount ); /** * @dev Emitted when bounty is distributed. */ event BountyWasPaid( uint validatorId, uint amount ); IERC1820Registry private _erc1820; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _bountyPaid; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _feePaid; // holder => validatorId => month mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth; // validatorId => month mapping (uint => uint) private _firstUnwithdrawnMonthForValidator; /** * @dev Return and update the amount of earned bounty from a validator. */ function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) { return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); } /** * @dev Allows msg.sender to withdraw earned bounty. Bounties are locked * until launchTimestamp and BOUNTY_LOCKUP_MONTHS have both passed. * * Emits a {WithdrawBounty} event. * * Requirements: * * - Bounty must be unlocked. */ function withdrawBounty(uint validatorId, address to) external { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); uint bounty; uint endMonth; (bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); _firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth; IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require(skaleToken.transfer(to, bounty), "Failed to transfer tokens"); emit WithdrawBounty( msg.sender, validatorId, to, bounty ); } /** * @dev Allows `msg.sender` to withdraw earned validator fees. Fees are * locked until launchTimestamp and BOUNTY_LOCKUP_MONTHS both have passed. * * Emits a {WithdrawFee} event. * * Requirements: * * - Fee must be unlocked. */ function withdrawFee(address to) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Fee is locked"); // check Validator Exist inside getValidatorId uint validatorId = validatorService.getValidatorId(msg.sender); uint fee; uint endMonth; (fee, endMonth) = getEarnedFeeAmountOf(validatorId); _firstUnwithdrawnMonthForValidator[validatorId] = endMonth; require(skaleToken.transfer(to, fee), "Failed to transfer tokens"); emit WithdrawFee( validatorId, to, fee ); } function tokensReceived( address, address, address to, uint256 amount, bytes calldata userData, bytes calldata ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); require(userData.length == 32, "Data length is incorrect"); uint validatorId = abi.decode(userData, (uint)); _distributeBounty(amount, validatorId); } /** * @dev Return the amount of earned validator fees of `msg.sender`. */ function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender)); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } /** * @dev Return and update the amount of earned bounties. */ function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId) public returns (uint earned, uint endMonth) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId]; if (startMonth == 0) { startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId); if (startMonth == 0) { return (0, 0); } } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { uint effectiveDelegatedToValidator = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i); if (effectiveDelegatedToValidator.muchGreater(0)) { earned = earned.add( _bountyPaid[validatorId][i].mul( delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i)) .div(effectiveDelegatedToValidator) ); } } } /** * @dev Return the amount of earned fees by validator ID. */ function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId]; if (startMonth == 0) { return (0, 0); } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { earned = earned.add(_feePaid[validatorId][i]); } } // private /** * @dev Distributes bounties to delegators. * * Emits a {BountyWasPaid} event. */ function _distributeBounty(uint amount, uint validatorId) private { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint currentMonth = timeHelpers.getCurrentMonth(); uint feeRate = validatorService.getValidator(validatorId).feeRate; uint fee = amount.mul(feeRate).div(1000); uint bounty = amount.sub(fee); _bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty); _feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee); if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) { _firstUnwithdrawnMonthForValidator[validatorId] = currentMonth; } emit BountyWasPaid(validatorId, amount); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDKGTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; contract SkaleDKGTester is SkaleDKG { function setSuccessfulDKGPublic(bytes32 schainId) external { lastSuccesfulDKG[schainId] = now; channels[schainId].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainId); emit SuccessfulDKG(schainId); } } // SPDX-License-Identifier: AGPL-3.0-only /* NodesTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../Nodes.sol"; contract NodesTester is Nodes { function removeNodeFromSpaceToNodes(uint nodeIndex) external { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromSpaceToNodes(nodeIndex, space); } function removeNodesFromPlace(uint place, uint nodesAmount) external { SegmentTree.Tree storage tree = _getNodesAmountBySpace(); tree.removeFromPlace(place, nodesAmount); } function amountOfNodesFromPlaceInTree(uint place) external view returns (uint) { SegmentTree.Tree storage tree = _getNodesAmountBySpace(); return tree.sumFromPlaceToLast(place); } } // SPDX-License-Identifier: AGPL-3.0-only /* Pricing.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./Nodes.sol"; /** * @title Pricing * @dev Contains pricing operations for SKALE network. */ contract Pricing is Permissions { uint public constant INITIAL_PRICE = 5 * 10**6; uint public price; uint public totalNodes; uint public lastUpdated; function initNodes() external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); totalNodes = nodes.getNumberOnlineNodes(); } /** * @dev Adjust the schain price based on network capacity and demand. * * Requirements: * * - Cooldown time has exceeded. */ function adjustPrice() external { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now > lastUpdated.add(constantsHolder.COOLDOWN_TIME()), "It's not a time to update a price"); checkAllNodes(); uint load = _getTotalLoad(); uint capacity = _getTotalCapacity(); bool networkIsOverloaded = load.mul(100) > constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity); uint loadDiff; if (networkIsOverloaded) { loadDiff = load.mul(100).sub(constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity)); } else { loadDiff = constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity).sub(load.mul(100)); } uint priceChangeSpeedMultipliedByCapacityAndMinPrice = constantsHolder.ADJUSTMENT_SPEED().mul(loadDiff).mul(price); uint timeSkipped = now.sub(lastUpdated); uint priceChange = priceChangeSpeedMultipliedByCapacityAndMinPrice .mul(timeSkipped) .div(constantsHolder.COOLDOWN_TIME()) .div(capacity) .div(constantsHolder.MIN_PRICE()); if (networkIsOverloaded) { assert(priceChange > 0); price = price.add(priceChange); } else { if (priceChange > price) { price = constantsHolder.MIN_PRICE(); } else { price = price.sub(priceChange); if (price < constantsHolder.MIN_PRICE()) { price = constantsHolder.MIN_PRICE(); } } } lastUpdated = now; } /** * @dev Returns the total load percentage. */ function getTotalLoadPercentage() external view returns (uint) { return _getTotalLoad().mul(100).div(_getTotalCapacity()); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); lastUpdated = now; price = INITIAL_PRICE; } function checkAllNodes() public { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint numberOfActiveNodes = nodes.getNumberOnlineNodes(); require(totalNodes != numberOfActiveNodes, "No changes to node supply"); totalNodes = numberOfActiveNodes; } function _getTotalLoad() private view returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint load = 0; uint numberOfSchains = schainsInternal.numberOfSchains(); for (uint i = 0; i < numberOfSchains; i++) { bytes32 schain = schainsInternal.schainsAtSystem(i); uint numberOfNodesInSchain = schainsInternal.getNumberOfNodesInGroup(schain); uint part = schainsInternal.getSchainsPartOfNode(schain); load = load.add( numberOfNodesInSchain.mul(part) ); } return load; } function _getTotalCapacity() private view returns (uint) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes.getNumberOnlineNodes().mul(constantsHolder.TOTAL_SPACE_ON_NODE()); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternalMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SchainsInternal.sol"; contract SchainsInternalMock is SchainsInternal { function removePlaceOfSchainOnNode(bytes32 schainHash, uint nodeIndex) external { delete placeOfSchainOnNode[schainHash][nodeIndex]; } function removeNodeToLocked(uint nodeIndex) external { mapping(uint => bytes32[]) storage nodeToLocked = _getNodeToLockedSchains(); delete nodeToLocked[nodeIndex]; } function removeSchainToExceptionNode(bytes32 schainHash) external { mapping(bytes32 => uint[]) storage schainToException = _getSchainToExceptionNodes(); delete schainToException[schainHash]; } } // SPDX-License-Identifier: AGPL-3.0-only /* LockerMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../interfaces/delegation/ILocker.sol"; contract LockerMock is ILocker { function getAndUpdateLockedAmount(address) external override returns (uint) { return 13; } function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 13; } } // SPDX-License-Identifier: AGPL-3.0-only /* MathUtilsTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; contract MathUtilsTester { using MathUtils for uint; function boundedSub(uint256 a, uint256 b) external returns (uint256) { return a.boundedSub(b); } function boundedSubWithoutEvent(uint256 a, uint256 b) external pure returns (uint256) { return a.boundedSubWithoutEvent(b); } function muchGreater(uint256 a, uint256 b) external pure returns (bool) { return a.muchGreater(b); } function approximatelyEqual(uint256 a, uint256 b) external pure returns (bool) { return a.approximatelyEqual(b); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTreeTester.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../utils/SegmentTree.sol"; contract SegmentTreeTester { using SegmentTree for SegmentTree.Tree; SegmentTree.Tree private _tree; uint[129] private _places; function initTree() external { _tree.create(128); for (uint8 i = 1; i <= 128; i++) { if (_places[i] > 0) _tree.addToPlace(i, _places[i]); } } function addElemInPlaces(uint place, uint elem) external { _places[place] = elem; } function addToLast(uint elem) external { _tree.addToPlace(_tree.getSize(), elem); } function addToPlace(uint place, uint elem) external { _tree.addToPlace(place, elem); } function removeFromPlace(uint place, uint elem) external { _tree.removeFromPlace(place, elem); } function moveFromPlaceToPlace(uint fromPlace, uint toPlace, uint elem) external { _tree.moveFromPlaceToPlace(fromPlace, toPlace, elem); } function sumFromPlaceToLast(uint place) external view returns (uint) { return _tree.sumFromPlaceToLast(place); } function getRandomElem(uint place) external view returns (uint) { Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), place) ); return _tree.getRandomNonZeroElementFromPlaceToLast(place, randomGenerator); } function getElem(uint index) external view returns (uint) { require(index < _tree.tree.length, "Incorrect index"); return _tree.tree[index]; } function getSize() external view returns (uint) { return _tree.getSize(); } }
* @dev See {IDelegatableToken-getAndUpdateLockedAmount}./
function getAndUpdateLockedAmount(address wallet) public override returns (uint) { return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet); }
9,880,067
[ 1, 9704, 288, 734, 13451, 8163, 1345, 17, 588, 1876, 1891, 8966, 6275, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22909, 1891, 8966, 6275, 12, 2867, 9230, 13, 1071, 3849, 1135, 261, 11890, 13, 288, 203, 3639, 327, 3155, 1119, 12, 16351, 1318, 18, 588, 8924, 2932, 1345, 1119, 7923, 2934, 588, 1876, 1891, 8966, 6275, 12, 19177, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* * This file was generated by MyWish Platform (https://mywish.io/) * The complete code could be found at https://github.com/MyWishPlatform/ * Copyright (C) 2018 MyWish * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity ^0.4.23; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract FreezableToken is StandardToken { // freezing chains mapping (bytes32 => uint64) internal chains; // freezing amounts for each chain mapping (bytes32 => uint) internal freezings; // total freezing balance per address mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); /** * @dev Gets the balance of the specified address include freezing tokens. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } /** * @dev Gets the balance of the specified address without freezing tokens. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } /** * @dev gets freezing count * @param _addr Address of freeze tokens owner. */ function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count++; release = chains[toKey(_addr, release)]; } } /** * @dev gets freezing end date and freezing balance for the freezing portion specified by index. * @param _addr Address of freeze tokens owner. * @param _index Freezing portion index. It ordered by release date descending. */ function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } /** * @dev freeze your tokens to the specified address. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token to freeze. * @param _until Release date, must be in future. */ function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Transfer(msg.sender, _to, _amount); emit Freezed(_to, _until, _amount); } /** * @dev release first available freezing tokens. */ function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } emit Released(msg.sender, amount); } /** * @dev release all available for release freezing tokens. Gas usage is not deterministic! * @return how many tokens was released */ function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { // WISH masc to increase entropy result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract FreezableMintableToken is FreezableToken, MintableToken { /** * @dev Mint the specified amount of token to the specified address and freeze it until the specified date. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token to mint and freeze. * @param _until Release date, must be in future. * @return A boolean that indicates if the operation was successful. */ function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Mint(_to, _amount); emit Freezed(_to, _until, _amount); emit Transfer(msg.sender, _to, _amount); return true; } } contract Consts { uint public constant TOKEN_DECIMALS = 18; uint8 public constant TOKEN_DECIMALS_UINT8 = 18; uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string public constant TOKEN_NAME = "Kryptonium"; string public constant TOKEN_SYMBOL = "KRYP"; bool public constant PAUSED = false; address public constant TARGET_USER = 0xEe8E76A3E92cAe6e8215d17d9F7f00890aC089e9; bool public constant CONTINUE_MINTING = false; } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable { event Initialized(); bool public initialized = false; constructor() public { init(); transferOwnership(TARGET_USER); } function name() public pure returns (string _name) { return TOKEN_NAME; } function symbol() public pure returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() public pure returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } function init() private { require(!initialized); initialized = true; if (PAUSED) { pause(); } address[1] memory addresses = [address(0xee8e76a3e92cae6e8215d17d9f7f00890ac089e9)]; uint[1] memory amounts = [uint(177700000000000000000000000)]; uint64[1] memory freezes = [uint64(0)]; for (uint i = 0; i < addresses.length; i++) { if (freezes[i] == 0) { mint(addresses[i], amounts[i]); } else { mintAndFreeze(addresses[i], amounts[i], freezes[i]); } } if (!CONTINUE_MINTING) { finishMinting(); } emit Initialized(); } }
* @title SafeMath @dev Math operations with safety checks that throw on error/
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
13,465,744
[ 1, 9890, 10477, 225, 2361, 5295, 598, 24179, 4271, 716, 604, 603, 555, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 288, 203, 203, 915, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 276, 13, 288, 203, 430, 261, 69, 422, 374, 13, 288, 203, 2463, 374, 31, 203, 97, 203, 203, 71, 273, 279, 380, 324, 31, 203, 11231, 12, 71, 342, 279, 422, 324, 1769, 203, 2463, 276, 31, 203, 97, 203, 203, 915, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 276, 13, 288, 203, 430, 261, 69, 422, 374, 13, 288, 203, 2463, 374, 31, 203, 97, 203, 203, 71, 273, 279, 380, 324, 31, 203, 11231, 12, 71, 342, 279, 422, 324, 1769, 203, 2463, 276, 31, 203, 97, 203, 203, 915, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 2463, 279, 342, 324, 31, 203, 97, 203, 203, 915, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 11231, 12, 70, 1648, 279, 1769, 203, 2463, 279, 300, 324, 31, 203, 97, 203, 203, 915, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 276, 13, 288, 203, 71, 273, 279, 397, 324, 31, 203, 11231, 12, 71, 1545, 279, 1769, 203, 2463, 276, 31, 203, 97, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.4; //SPDX-License-Identifier: MIT import {ERC721, ERC721TokenReceiver} from "@rari-capital/solmate/src/tokens/ERC721.sol"; import {ERC1155, ERC1155TokenReceiver} from "@rari-capital/solmate/src/tokens/ERC1155.sol"; import {SafeTransferLib, ERC20} from "@rari-capital/solmate/src/utils/SafeTransferLib.sol"; import {Strings} from "@openzeppelin/contracts/utils/Strings.sol"; import {IERC2981, IERC165} from "@openzeppelin/contracts/interfaces/IERC2981.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {Base64} from 'base64-sol/base64.sol'; import {CloneList} from "./CloneList.sol"; import {TimeCurve} from "./TimeCurve.sol"; /** * @title NFT derivative exchange inspired by the SALSA concept. * @author calvbore * @notice A user may self assess the price of an NFT and purchase a token representing * the right to ownership when it is sold via this contract. Anybody may buy the * token for a higher price and force a transfer from the previous owner to the new buyer. */ contract DittoMachine is ERC721, ERC721TokenReceiver, ERC1155TokenReceiver, CloneList { /** * @notice Insufficient bid for purchasing a clone. * @dev thrown when the number of erc20 tokens sent is lower than * the number of tokens required to purchase a clone. */ error AmountInvalid(); error AmountInvalidMin(); error InvalidFloorId(); error CloneNotFound(); error FromInvalid(); error IndexInvalid(); error NFTNotReceived(); error NotAuthorized(); ////////////// CONSTANT VARIABLES ////////////// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; uint256 public constant FLOOR_ID = uint256(0xfddc260aecba8a66725ee58da4ea3cbfcf4ab6c6ad656c48345a575ca18c45c9); // ensure that CloneShape can always be casted to int128. // change the type to ensure this? uint256 public constant BASE_TERM = 2**18; uint256 public constant MIN_FEE = 32; uint256 public constant DNOM = 2**16 - 1; uint256 public constant MIN_AMOUNT_FOR_NEW_CLONE = BASE_TERM + (BASE_TERM * MIN_FEE / DNOM); ////////////// STATE VARIABLES ////////////// // variables essential to calculating auction/price information for each cloneId struct CloneShape { uint256 tokenId; uint256 worth; address ERC721Contract; address ERC20Contract; uint8 heat; bool floor; uint256 term; } // tracks balance of subsidy for a specific cloneId mapping(uint256 => uint256) public cloneIdToSubsidy; // protoId cumulative price for TWAP mapping(uint256 => uint256) public protoIdToCumulativePrice; // lat timestamp recorded for protoId TWAP mapping(uint256 => uint256) public protoIdToTimestampLast; // hash protoId with the index placement to get cloneId mapping(uint256 => CloneShape) public cloneIdToShape; constructor() ERC721("Ditto", "DTO") { } /////////////////////////////////////////// ////////////// URI FUNCTIONS ////////////// /////////////////////////////////////////// function tokenURI(uint256 id) public view override returns (string memory) { CloneShape memory cloneShape = cloneIdToShape[id]; if (!cloneShape.floor) { // if clone is not a floor return underlying token uri try ERC721(cloneShape.ERC721Contract).tokenURI(cloneShape.tokenId) returns (string memory uri) { return uri; } catch { return ERC1155(cloneShape.ERC721Contract).uri(cloneShape.tokenId); } } else { string memory _name = string(abi.encodePacked('Ditto Floor #', Strings.toString(id))); string memory description = string(abi.encodePacked( 'This Ditto represents the floor price of tokens at ', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20) )); string memory image = Base64.encode(bytes(generateSVGofTokenById(id))); return string(abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', _name, '", "description":"', description, '", "attributes": [{"trait_type": "Underlying NFT", "value": "', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20), '"},{"trait_type": "tokenId", "value": ', Strings.toString(cloneShape.tokenId), '}], "owner":"', Strings.toHexString(uint160(ownerOf[id]), 20), '", "image": "', 'data:image/svg+xml;base64,', image, '"}' ) ) ) )); } } function generateSVGofTokenById(uint256 _tokenId) internal pure returns (string memory) { string memory svg = string(abi.encodePacked( '<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">', renderTokenById(_tokenId), '</svg>' )); return svg; } // Visibility is `public` to enable it being called by other contracts for composition. function renderTokenById(uint256 _tokenId) public pure returns (string memory) { string memory hexColor = toHexString(uint24(_tokenId), 3); return string(abi.encodePacked( '<rect width="100" height="100" rx="15" style="fill:#', hexColor, '" />', '<g id="face" transform="matrix(0.531033,0,0,0.531033,-279.283,-398.06)">', '<g transform="matrix(0.673529,0,0,0.673529,201.831,282.644)">', '<circle cx="568.403" cy="815.132" r="3.15"/>', '</g>', '<g transform="matrix(0.673529,0,0,0.673529,272.214,282.644)">', '<circle cx="568.403" cy="815.132" r="3.15"/>', '</g>', '<g transform="matrix(1,0,0,1,0.0641825,0)">', '<path d="M572.927,854.4C604.319,859.15 635.71,859.166 667.102,854.4" style="fill:none;stroke:black;stroke-width:0.98px;"/>', '</g>', '</g>' )); } // same as inspired from @openzeppelin/contracts/utils/Strings.sol except that it doesn't add "0x" as prefix. function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length); for (uint256 i = 2 * length; i > 0; --i) { buffer[i - 1] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } ///////////////////////////////////////////////// //////////////// CLONE FUNCTIONS //////////////// ///////////////////////////////////////////////// /** * @notice open or buy out a future on a particular NFT or floor perp. * @notice fees will be taken from purchases and set aside as a subsidy to encourage sellers. * @param _ERC721Contract address of selected NFT smart contract. * @param _tokenId selected NFT token id. * @param _ERC20Contract address of the ERC20 contract used for purchase. * @param _amount address of ERC20 tokens used for purchase. * @param floor selector determining if the purchase is for a floor perp. * @dev creates an ERC721 representing the specified future or floor perp, reffered to as clone. * @dev a clone id is calculated by hashing ERC721Contract, _tokenId, _ERC20Contract, and floor params. * @dev if floor == true, FLOOR_ID will replace _tokenId in cloneId calculation. */ function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, uint256 index // index at which to mint the clone ) external returns ( uint256, // cloneId uint256 // protoId ) { // ensure enough funds to do some math on if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } // calculate protoId by hashing identifiying information, precursor to cloneId uint256 protoId = uint256(keccak256(abi.encodePacked( _ERC721Contract, _tokenId, _ERC20Contract, floor ))); // hash protoId and index to get cloneId uint256 cloneId = uint256(keccak256(abi.encodePacked(protoId, index))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { // check that index references have been set if (!validIndex(protoId, index)) { // if references have not been set by a previous clone this clone cannot be minted revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 subsidy = _amount * MIN_FEE / DNOM; // with current constants subsidy <= _amount uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { // check price of floor clone to get price floor uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (index != protoIdToIndexHead[protoId]) { // check cloneId at prior index // prev <- index uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); // check value is less than clone closer to the index head } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; SafeTransferLib.safeTransferFrom( // EXTERNAL CALL ERC20(_ERC20Contract), msg.sender, address(this), _amount ); } else { CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); // calculate subsidy and worth values uint256 subsidy = minAmount * (MIN_FEE * (1 + heat)) / DNOM; // scoping to prevent "stack too deep" errors { uint256 value = _amount - subsidy; // will be applied to cloneShape.worth if (index != protoIdToIndexHead[protoId]) { // check cloneId at prior index // prev <- index uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } // reduce heat relative to amount of time elapsed by auction if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 elapsed = block.timestamp - (cloneShape.term - termLength); // current time - time when the current term started // add 1 to current heat so heat is not stuck at low value with anything but extreme demand for a clone uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); } else { heat = 1; } // calculate new clone term values cloneIdToShape[cloneId].worth = value; cloneIdToShape[cloneId].heat = uint8(heat); // does not inherit heat of floor id cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } // paying required funds to this contract SafeTransferLib.safeTransferFrom( // EXTERNAL CALL ERC20(_ERC20Contract), msg.sender, address(this), _amount ); // buying out the previous clone owner address curOwner = ownerOf[cloneId]; uint256 subsidyDiv2 = subsidy >> 1; // half of fee goes into subsidy pool, half to previous clone owner cloneIdToSubsidy[cloneId] += subsidyDiv2; SafeTransferLib.safeTransfer( // EXTERNAL CALL ERC20(_ERC20Contract), curOwner, (cloneShape.worth + subsidyDiv2 + (subsidy & 1)) // previous clone value + half of subsidy sent to prior clone owner ); // force transfer from current owner to new highest bidder forceTransferFrom(curOwner, msg.sender, cloneId); // EXTERNAL CALL } return (cloneId, protoId); } /** * @notice unwind a position in a clone. * @param protoId specifies the clone to be burned. * @dev will refund funds held in a position, subsidy will remain for sellers in the future. */ function dissolve(uint256 protoId, uint256 index) external { uint256 cloneId = uint256(keccak256(abi.encodePacked(protoId, index))); if (!(msg.sender == ownerOf[cloneId] || msg.sender == getApproved[cloneId] || isApprovedForAll[ownerOf[cloneId]][msg.sender])) { revert NotAuthorized(); } // move its subsidy to the next clone in the linked list even if it's not minted yet. uint256 nextCloneId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToAfter[protoId][index]))); // invariant: cloneId != nextCloneId cloneIdToSubsidy[nextCloneId] += cloneIdToSubsidy[cloneId]; delete cloneIdToSubsidy[cloneId]; CloneShape memory cloneShape = cloneIdToShape[cloneId]; _updatePrice(protoId); popListIndex(protoId, index); address owner = ownerOf[cloneId]; delete cloneIdToShape[cloneId]; _burn(cloneId); SafeTransferLib.safeTransfer( // EXTERNAL CALL ERC20(cloneShape.ERC20Contract), owner, cloneShape.worth ); } function getMinAmountForCloneTransfer(uint256 cloneId) external view returns (uint256) { if(ownerOf[cloneId] == address(0)) { return MIN_AMOUNT_FOR_NEW_CLONE; } CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 _minAmount = _getMinAmount(cloneShape); return _minAmount + (_minAmount * MIN_FEE * (1 + cloneShape.heat) / DNOM); } /** * @notice computes the minimum amount required to buy a clone. * @notice it does not take into account the protocol fee or the subsidy. * @param cloneShape clone for which to compute the minimum amount. * @dev only use it for a minted clone. */ function _getMinAmount(CloneShape memory cloneShape) internal view returns (uint256) { uint256 floorId = uint256(keccak256(abi.encodePacked( cloneShape.ERC721Contract, FLOOR_ID, cloneShape.ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, protoIdToIndexHead[floorId]))); uint256 floorPrice = cloneIdToShape[floorId].worth; uint256 timeLeft = 0; unchecked { if (cloneShape.term > block.timestamp) { timeLeft = cloneShape.term - block.timestamp; } } uint256 termLength = BASE_TERM + TimeCurve.calc(cloneShape.heat); uint256 clonePrice = cloneShape.worth + (cloneShape.worth * timeLeft / termLength); // return floor price if greater than clone auction price return floorPrice > clonePrice ? floorPrice : clonePrice; } //////////////////////////////////////////////// ////////////// RECEIVER FUNCTIONS ////////////// //////////////////////////////////////////////// function onTokenReceived( address from, address tokenContract, uint256 id, address ERC20Contract, bool floor, bool isERC1155 ) private { uint256 protoId = uint256(keccak256(abi.encodePacked( tokenContract, // ERC721 or ERC1155 Contract address id, ERC20Contract, false ))); uint256 cloneId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexHead[protoId]))); uint256 flotoId = uint256(keccak256(abi.encodePacked( // floorId + protoId = flotoId tokenContract, FLOOR_ID, ERC20Contract, true ))); uint256 floorId = uint256(keccak256(abi.encodePacked(flotoId, protoIdToIndexHead[flotoId]))); if ( floor || ownerOf[cloneId] == address(0) || cloneIdToShape[floorId].worth > cloneIdToShape[cloneId].worth ) { // if cloneId is not active, check floor clone cloneId = floorId; protoId = flotoId; } // if no cloneId is active, revert if (ownerOf[cloneId] == address(0)) { revert CloneNotFound(); } _updatePrice(protoId); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 subsidy = cloneIdToSubsidy[cloneId]; address owner = ownerOf[cloneId]; delete cloneIdToShape[cloneId]; delete cloneIdToSubsidy[cloneId]; _burn(cloneId); // token can only be sold to the clone at the index head popListHead(protoId); if (isERC1155) { if (ERC1155(tokenContract).balanceOf(address(this), id) < 1) { revert NFTNotReceived(); } ERC1155(tokenContract).safeTransferFrom(address(this), owner, id, 1, ""); } else { if (ERC721(tokenContract).ownerOf(id) != address(this)) { revert NFTNotReceived(); } ERC721(tokenContract).safeTransferFrom(address(this), owner, id); } if (IERC165(tokenContract).supportsInterface(_INTERFACE_ID_ERC2981)) { (address receiver, uint256 royaltyAmount) = IERC2981(tokenContract).royaltyInfo( cloneShape.tokenId, cloneShape.worth ); if (royaltyAmount > 0) { cloneShape.worth -= royaltyAmount; SafeTransferLib.safeTransfer( ERC20(ERC20Contract), receiver, royaltyAmount ); } } SafeTransferLib.safeTransfer( ERC20(ERC20Contract), from, cloneShape.worth + subsidy ); } /** * @dev will allow NFT sellers to sell by safeTransferFrom-ing directly to this contract. * @param data will contain ERC20 address that the seller wishes to sell for * allows specifying selling for the floor price * @return returns received selector */ function onERC721Received( address, address from, uint256 id, bytes calldata data ) external returns (bytes4) { (address ERC20Contract, bool floor) = abi.decode(data, (address, bool)); onTokenReceived(from, msg.sender /*ERC721 contract address*/, id, ERC20Contract, floor, false); return this.onERC721Received.selector; } function onERC1155Received( address, address from, uint256 id, uint256 amount, bytes calldata data ) external returns (bytes4) { if (amount != 1) { revert AmountInvalid(); } // address ERC1155Contract = msg.sender; (address ERC20Contract, bool floor) = abi.decode(data, (address, bool)); onTokenReceived(from, msg.sender /*ERC1155 contract address*/, id, ERC20Contract, floor, true); return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address from, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external returns (bytes4) { for (uint256 i=0; i < amounts.length; i++) { if (amounts[i] != 1) { revert AmountInvalid(); } } // address[] memory ERC20Contracts = new address[](ids.length); // bool[] memory floors = new bool[](ids.length); (address[] memory ERC20Contracts, bool[] memory floors) = abi.decode(data, (address[], bool[])); for (uint256 i=0; i < ids.length; i++) { onTokenReceived(from, msg.sender /*ERC1155 contract address*/, ids[i], ERC20Contracts[i], floors[i], true); } return this.onERC1155BatchReceived.selector; } /////////////////////////////////////////////// ////////////// PRIVATE FUNCTIONS ////////////// /////////////////////////////////////////////// /** * @notice transfer clone without owner/approval checks. * @param from current clone owner. * @param to transfer recipient. * @param id clone id. * @dev if the current clone owner implements ERC721Ejected, we call it. * we will still transfer the clone if that call reverts. * only to be called from `duplicate()` function to transfer to the next bidder. * `to` != address(0) is assumed and is not explicitly check. * `onERC721Received` is not called on the receiver, the bidder is responsible for accounting. */ function forceTransferFrom( address from, address to, uint256 id ) private { // no ownership or approval checks cause we're forcing a change of ownership if (from != ownerOf[id]) { revert FromInvalid(); } unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); // give contracts the option to account for a forced transfer. // if they don't implement the ejector we're stll going to move the token. if (from.code.length != 0) { // not sure if this is exploitable yet? try IERC721TokenEjector(from).onERC721Ejected{gas: 30000}(address(this), to, id, "") {} // EXTERNAL CALL catch {} } } // @dev: this function is not prod ready function _updatePrice(uint256 protoId) internal { uint256 cloneId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexHead[protoId]))); uint256 timeElapsed = block.timestamp - protoIdToTimestampLast[protoId]; if (timeElapsed > 0) { unchecked { protoIdToCumulativePrice[protoId] += cloneIdToShape[cloneId].worth * timeElapsed; } } protoIdToTimestampLast[protoId] = block.timestamp; } } /** * @title A funtion to support token ejection * @notice function is called if a contract must do accounting on a forced transfer */ interface IERC721TokenEjector { function onERC721Ejected( address operator, address to, uint256 id, bytes calldata data ) external returns (bytes4); }
* @title NFT derivative exchange inspired by the SALSA concept. @author calvbore @notice A user may self assess the price of an NFT and purchase a token representing the right to ownership when it is sold via this contract. Anybody may buy the token for a higher price and force a transfer from the previous owner to the new buyer./ ensure that CloneShape can always be casted to int128. change the type to ensure this? variables essential to calculating auction/price information for each cloneId
contract DittoMachine is ERC721, ERC721TokenReceiver, ERC1155TokenReceiver, CloneList { error AmountInvalid(); error AmountInvalidMin(); error InvalidFloorId(); error CloneNotFound(); error FromInvalid(); error IndexInvalid(); error NFTNotReceived(); error NotAuthorized(); bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; uint256 public constant FLOOR_ID = uint256(0xfddc260aecba8a66725ee58da4ea3cbfcf4ab6c6ad656c48345a575ca18c45c9); uint256 public constant BASE_TERM = 2**18; uint256 public constant MIN_FEE = 32; uint256 public constant DNOM = 2**16 - 1; uint256 public constant MIN_AMOUNT_FOR_NEW_CLONE = BASE_TERM + (BASE_TERM * MIN_FEE / DNOM); import {ERC721, ERC721TokenReceiver} from "@rari-capital/solmate/src/tokens/ERC721.sol"; import {ERC1155, ERC1155TokenReceiver} from "@rari-capital/solmate/src/tokens/ERC1155.sol"; import {SafeTransferLib, ERC20} from "@rari-capital/solmate/src/utils/SafeTransferLib.sol"; import {Strings} from "@openzeppelin/contracts/utils/Strings.sol"; import {IERC2981, IERC165} from "@openzeppelin/contracts/interfaces/IERC2981.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {Base64} from 'base64-sol/base64.sol'; import {CloneList} from "./CloneList.sol"; import {TimeCurve} from "./TimeCurve.sol"; struct CloneShape { uint256 tokenId; uint256 worth; address ERC721Contract; address ERC20Contract; uint8 heat; bool floor; uint256 term; } mapping(uint256 => uint256) public cloneIdToSubsidy; mapping(uint256 => uint256) public protoIdToCumulativePrice; mapping(uint256 => uint256) public protoIdToTimestampLast; mapping(uint256 => CloneShape) public cloneIdToShape; constructor() ERC721("Ditto", "DTO") { } function tokenURI(uint256 id) public view override returns (string memory) { CloneShape memory cloneShape = cloneIdToShape[id]; if (!cloneShape.floor) { try ERC721(cloneShape.ERC721Contract).tokenURI(cloneShape.tokenId) returns (string memory uri) { return uri; return ERC1155(cloneShape.ERC721Contract).uri(cloneShape.tokenId); } string memory _name = string(abi.encodePacked('Ditto Floor #', Strings.toString(id))); string memory description = string(abi.encodePacked( 'This Ditto represents the floor price of tokens at ', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20) )); string memory image = Base64.encode(bytes(generateSVGofTokenById(id))); return string(abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', _name, '", "description":"', description, '", "attributes": [{"trait_type": "Underlying NFT", "value": "', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20), Strings.toString(cloneShape.tokenId), '}], "owner":"', Strings.toHexString(uint160(ownerOf[id]), 20), '", "image": "', 'data:image/svg+xml;base64,', image, '"}' ) ) ) )); } } function tokenURI(uint256 id) public view override returns (string memory) { CloneShape memory cloneShape = cloneIdToShape[id]; if (!cloneShape.floor) { try ERC721(cloneShape.ERC721Contract).tokenURI(cloneShape.tokenId) returns (string memory uri) { return uri; return ERC1155(cloneShape.ERC721Contract).uri(cloneShape.tokenId); } string memory _name = string(abi.encodePacked('Ditto Floor #', Strings.toString(id))); string memory description = string(abi.encodePacked( 'This Ditto represents the floor price of tokens at ', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20) )); string memory image = Base64.encode(bytes(generateSVGofTokenById(id))); return string(abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', _name, '", "description":"', description, '", "attributes": [{"trait_type": "Underlying NFT", "value": "', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20), Strings.toString(cloneShape.tokenId), '}], "owner":"', Strings.toHexString(uint160(ownerOf[id]), 20), '", "image": "', 'data:image/svg+xml;base64,', image, '"}' ) ) ) )); } } function tokenURI(uint256 id) public view override returns (string memory) { CloneShape memory cloneShape = cloneIdToShape[id]; if (!cloneShape.floor) { try ERC721(cloneShape.ERC721Contract).tokenURI(cloneShape.tokenId) returns (string memory uri) { return uri; return ERC1155(cloneShape.ERC721Contract).uri(cloneShape.tokenId); } string memory _name = string(abi.encodePacked('Ditto Floor #', Strings.toString(id))); string memory description = string(abi.encodePacked( 'This Ditto represents the floor price of tokens at ', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20) )); string memory image = Base64.encode(bytes(generateSVGofTokenById(id))); return string(abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', _name, '", "description":"', description, '", "attributes": [{"trait_type": "Underlying NFT", "value": "', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20), Strings.toString(cloneShape.tokenId), '}], "owner":"', Strings.toHexString(uint160(ownerOf[id]), 20), '", "image": "', 'data:image/svg+xml;base64,', image, '"}' ) ) ) )); } } } catch { } else { function tokenURI(uint256 id) public view override returns (string memory) { CloneShape memory cloneShape = cloneIdToShape[id]; if (!cloneShape.floor) { try ERC721(cloneShape.ERC721Contract).tokenURI(cloneShape.tokenId) returns (string memory uri) { return uri; return ERC1155(cloneShape.ERC721Contract).uri(cloneShape.tokenId); } string memory _name = string(abi.encodePacked('Ditto Floor #', Strings.toString(id))); string memory description = string(abi.encodePacked( 'This Ditto represents the floor price of tokens at ', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20) )); string memory image = Base64.encode(bytes(generateSVGofTokenById(id))); return string(abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', _name, '", "description":"', description, '", "attributes": [{"trait_type": "Underlying NFT", "value": "', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20), Strings.toString(cloneShape.tokenId), '}], "owner":"', Strings.toHexString(uint160(ownerOf[id]), 20), '", "image": "', 'data:image/svg+xml;base64,', image, '"}' ) ) ) )); } } function tokenURI(uint256 id) public view override returns (string memory) { CloneShape memory cloneShape = cloneIdToShape[id]; if (!cloneShape.floor) { try ERC721(cloneShape.ERC721Contract).tokenURI(cloneShape.tokenId) returns (string memory uri) { return uri; return ERC1155(cloneShape.ERC721Contract).uri(cloneShape.tokenId); } string memory _name = string(abi.encodePacked('Ditto Floor #', Strings.toString(id))); string memory description = string(abi.encodePacked( 'This Ditto represents the floor price of tokens at ', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20) )); string memory image = Base64.encode(bytes(generateSVGofTokenById(id))); return string(abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', _name, '", "description":"', description, '", "attributes": [{"trait_type": "Underlying NFT", "value": "', Strings.toHexString(uint160(cloneIdToShape[id].ERC721Contract), 20), Strings.toString(cloneShape.tokenId), '}], "owner":"', Strings.toHexString(uint160(ownerOf[id]), 20), '", "image": "', 'data:image/svg+xml;base64,', image, '"}' ) ) ) )); } } '"},{"trait_type": "tokenId", "value": ', function generateSVGofTokenById(uint256 _tokenId) internal pure returns (string memory) { string memory svg = string(abi.encodePacked( renderTokenById(_tokenId), '</svg>' )); return svg; } function renderTokenById(uint256 _tokenId) public pure returns (string memory) { string memory hexColor = toHexString(uint24(_tokenId), 3); return string(abi.encodePacked( '<rect width="100" height="100" rx="15" style="fill:#', hexColor, '" />', '<g id="face" transform="matrix(0.531033,0,0,0.531033,-279.283,-398.06)">', '<g transform="matrix(0.673529,0,0,0.673529,201.831,282.644)">', '<circle cx="568.403" cy="815.132" r="3.15"/>', '</g>', '<g transform="matrix(0.673529,0,0,0.673529,272.214,282.644)">', '<circle cx="568.403" cy="815.132" r="3.15"/>', '</g>', '<g transform="matrix(1,0,0,1,0.0641825,0)">', '<path d="M572.927,854.4C604.319,859.15 635.71,859.166 667.102,854.4" style="fill:none;stroke:black;stroke-width:0.98px;"/>', '</g>', '</g>' )); } function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length); for (uint256 i = 2 * length; i > 0; --i) { buffer[i - 1] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length); for (uint256 i = 2 * length; i > 0; --i) { buffer[i - 1] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, ) external returns ( ) { if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } _ERC721Contract, _tokenId, _ERC20Contract, floor ))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { if (!validIndex(protoId, index)) { revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (value > cloneIdToShape[elderId].worth) { } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; ERC20(_ERC20Contract), msg.sender, address(this), _amount ); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); { uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); heat = 1; } cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } msg.sender, address(this), _amount ); uint256 subsidyDiv2 = subsidy >> 1; ERC20(_ERC20Contract), curOwner, ); function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, ) external returns ( ) { if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } _ERC721Contract, _tokenId, _ERC20Contract, floor ))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { if (!validIndex(protoId, index)) { revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (value > cloneIdToShape[elderId].worth) { } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; ERC20(_ERC20Contract), msg.sender, address(this), _amount ); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); { uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); heat = 1; } cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } msg.sender, address(this), _amount ); uint256 subsidyDiv2 = subsidy >> 1; ERC20(_ERC20Contract), curOwner, ); function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, ) external returns ( ) { if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } _ERC721Contract, _tokenId, _ERC20Contract, floor ))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { if (!validIndex(protoId, index)) { revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (value > cloneIdToShape[elderId].worth) { } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; ERC20(_ERC20Contract), msg.sender, address(this), _amount ); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); { uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); heat = 1; } cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } msg.sender, address(this), _amount ); uint256 subsidyDiv2 = subsidy >> 1; ERC20(_ERC20Contract), curOwner, ); uint256 protoId = uint256(keccak256(abi.encodePacked( uint256 cloneId = uint256(keccak256(abi.encodePacked(protoId, index))); function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, ) external returns ( ) { if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } _ERC721Contract, _tokenId, _ERC20Contract, floor ))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { if (!validIndex(protoId, index)) { revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (value > cloneIdToShape[elderId].worth) { } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; ERC20(_ERC20Contract), msg.sender, address(this), _amount ); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); { uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); heat = 1; } cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } msg.sender, address(this), _amount ); uint256 subsidyDiv2 = subsidy >> 1; ERC20(_ERC20Contract), curOwner, ); function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, ) external returns ( ) { if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } _ERC721Contract, _tokenId, _ERC20Contract, floor ))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { if (!validIndex(protoId, index)) { revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (value > cloneIdToShape[elderId].worth) { } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; ERC20(_ERC20Contract), msg.sender, address(this), _amount ); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); { uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); heat = 1; } cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } msg.sender, address(this), _amount ); uint256 subsidyDiv2 = subsidy >> 1; ERC20(_ERC20Contract), curOwner, ); function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, ) external returns ( ) { if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } _ERC721Contract, _tokenId, _ERC20Contract, floor ))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { if (!validIndex(protoId, index)) { revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (value > cloneIdToShape[elderId].worth) { } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; ERC20(_ERC20Contract), msg.sender, address(this), _amount ); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); { uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); heat = 1; } cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } msg.sender, address(this), _amount ); uint256 subsidyDiv2 = subsidy >> 1; ERC20(_ERC20Contract), curOwner, ); function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, ) external returns ( ) { if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } _ERC721Contract, _tokenId, _ERC20Contract, floor ))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { if (!validIndex(protoId, index)) { revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (value > cloneIdToShape[elderId].worth) { } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; ERC20(_ERC20Contract), msg.sender, address(this), _amount ); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); { uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); heat = 1; } cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } msg.sender, address(this), _amount ); uint256 subsidyDiv2 = subsidy >> 1; ERC20(_ERC20Contract), curOwner, ); uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, ) external returns ( ) { if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } _ERC721Contract, _tokenId, _ERC20Contract, floor ))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { if (!validIndex(protoId, index)) { revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (value > cloneIdToShape[elderId].worth) { } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; ERC20(_ERC20Contract), msg.sender, address(this), _amount ); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); { uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); heat = 1; } cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } msg.sender, address(this), _amount ); uint256 subsidyDiv2 = subsidy >> 1; ERC20(_ERC20Contract), curOwner, ); } else { uint256 subsidy = minAmount * (MIN_FEE * (1 + heat)) / DNOM; function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, ) external returns ( ) { if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } _ERC721Contract, _tokenId, _ERC20Contract, floor ))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { if (!validIndex(protoId, index)) { revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (value > cloneIdToShape[elderId].worth) { } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; ERC20(_ERC20Contract), msg.sender, address(this), _amount ); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); { uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); heat = 1; } cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } msg.sender, address(this), _amount ); uint256 subsidyDiv2 = subsidy >> 1; ERC20(_ERC20Contract), curOwner, ); function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, ) external returns ( ) { if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } _ERC721Contract, _tokenId, _ERC20Contract, floor ))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { if (!validIndex(protoId, index)) { revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (value > cloneIdToShape[elderId].worth) { } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; ERC20(_ERC20Contract), msg.sender, address(this), _amount ); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); { uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); heat = 1; } cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } msg.sender, address(this), _amount ); uint256 subsidyDiv2 = subsidy >> 1; ERC20(_ERC20Contract), curOwner, ); function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, ) external returns ( ) { if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } _ERC721Contract, _tokenId, _ERC20Contract, floor ))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { if (!validIndex(protoId, index)) { revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (value > cloneIdToShape[elderId].worth) { } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; ERC20(_ERC20Contract), msg.sender, address(this), _amount ); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); { uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); heat = 1; } cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } msg.sender, address(this), _amount ); uint256 subsidyDiv2 = subsidy >> 1; ERC20(_ERC20Contract), curOwner, ); function duplicate( address _ERC721Contract, uint256 _tokenId, address _ERC20Contract, uint256 _amount, bool floor, ) external returns ( ) { if (_amount < MIN_AMOUNT_FOR_NEW_CLONE) { revert AmountInvalidMin(); } if (floor && _tokenId != FLOOR_ID) { revert InvalidFloorId(); } _ERC721Contract, _tokenId, _ERC20Contract, floor ))); _updatePrice(protoId); if (ownerOf[cloneId] == address(0)) { if (!validIndex(protoId, index)) { revert IndexInvalid(); } uint256 floorId = uint256(keccak256(abi.encodePacked( _ERC721Contract, FLOOR_ID, _ERC20Contract, true ))); floorId = uint256(keccak256(abi.encodePacked(floorId, index))); uint256 value = _amount - subsidy; if (cloneId != floorId && ownerOf[floorId] != address(0)) { uint256 minAmount = cloneIdToShape[floorId].worth; if (value < minAmount) { revert AmountInvalid(); } } if (value > cloneIdToShape[elderId].worth) { } } _mint(msg.sender, cloneId); cloneIdToShape[cloneId] = CloneShape( _tokenId, value, _ERC721Contract, _ERC20Contract, 1, floor, block.timestamp + BASE_TERM ); pushListTail(protoId, index); cloneIdToSubsidy[cloneId] += subsidy; ERC20(_ERC20Contract), msg.sender, address(this), _amount ); CloneShape memory cloneShape = cloneIdToShape[cloneId]; uint256 heat = cloneShape.heat; uint256 minAmount = _getMinAmount(cloneShape); { uint256 elderId = uint256(keccak256(abi.encodePacked(protoId, protoIdToIndexToPrior[protoId][index]))); if (value > cloneIdToShape[elderId].worth) { revert AmountInvalid(); } } if (value < minAmount) { revert AmountInvalid(); } if (cloneShape.term > block.timestamp) { uint256 termLength = BASE_TERM + TimeCurve.calc(heat); uint256 cool = (heat+1) * elapsed / termLength; heat = (cool > heat) ? 1 : Math.min(heat - cool + 1, type(uint8).max); heat = 1; } cloneIdToShape[cloneId].term = block.timestamp + BASE_TERM + TimeCurve.calc(heat); } msg.sender, address(this), _amount ); uint256 subsidyDiv2 = subsidy >> 1; ERC20(_ERC20Contract), curOwner, ); } else { cloneIdToShape[cloneId].worth = value; ERC20(_ERC20Contract), address curOwner = ownerOf[cloneId]; cloneIdToSubsidy[cloneId] += subsidyDiv2; }
1,065,482
[ 1, 50, 4464, 16417, 7829, 316, 1752, 2921, 635, 326, 348, 1013, 5233, 12402, 18, 225, 1443, 90, 70, 479, 225, 432, 729, 2026, 365, 1551, 403, 326, 6205, 434, 392, 423, 4464, 471, 23701, 279, 1147, 5123, 326, 2145, 358, 23178, 1347, 518, 353, 272, 1673, 3970, 333, 6835, 18, 5502, 3432, 2026, 30143, 326, 1147, 364, 279, 10478, 6205, 471, 2944, 279, 7412, 628, 326, 2416, 3410, 358, 326, 394, 27037, 18, 19, 3387, 716, 12758, 8500, 848, 3712, 506, 28192, 358, 509, 10392, 18, 2549, 326, 618, 358, 3387, 333, 35, 3152, 18518, 2001, 358, 21046, 279, 4062, 19, 8694, 1779, 364, 1517, 3236, 548, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 463, 305, 869, 6981, 353, 4232, 39, 27, 5340, 16, 4232, 39, 27, 5340, 1345, 12952, 16, 4232, 39, 2499, 2539, 1345, 12952, 16, 12758, 682, 288, 203, 565, 555, 16811, 1941, 5621, 203, 565, 555, 16811, 1941, 2930, 5621, 203, 565, 555, 1962, 42, 5807, 548, 5621, 203, 565, 555, 12758, 2768, 5621, 203, 565, 555, 6338, 1941, 5621, 203, 565, 555, 3340, 1941, 5621, 203, 565, 555, 423, 4464, 1248, 8872, 5621, 203, 565, 555, 2288, 15341, 5621, 203, 203, 203, 565, 1731, 24, 3238, 5381, 389, 18865, 67, 734, 67, 654, 39, 5540, 11861, 273, 374, 92, 22, 69, 2539, 31777, 69, 31, 203, 565, 1731, 2313, 3238, 5381, 389, 20661, 67, 22093, 55, 273, 315, 26684, 28953, 14432, 203, 203, 565, 2254, 5034, 1071, 5381, 478, 1502, 916, 67, 734, 273, 2254, 5034, 12, 20, 5841, 449, 71, 22, 4848, 69, 557, 12124, 28, 69, 6028, 27, 2947, 1340, 8204, 2414, 24, 24852, 23, 7358, 7142, 74, 24, 378, 26, 71, 26, 361, 26, 4313, 71, 8875, 25574, 69, 25, 5877, 5353, 2643, 71, 7950, 71, 29, 1769, 203, 203, 565, 2254, 5034, 1071, 5381, 10250, 67, 15176, 273, 576, 636, 2643, 31, 203, 565, 2254, 5034, 1071, 5381, 6989, 67, 8090, 41, 273, 3847, 31, 203, 565, 2254, 5034, 1071, 5381, 18001, 1872, 273, 576, 636, 2313, 300, 404, 31, 203, 565, 2254, 5034, 1071, 5381, 6989, 67, 2192, 51, 5321, 67, 7473, 67, 12917, 67, 5017, 5998, 273, 10250, 67, 15176, 397, 261, 8369, 67, 15176, 380, 2 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; /** * @title Domain model for Bonds. */ library Bond { struct MetaData { /** Description of the purpose of the Bond. */ string name; /** Abbreviation to identify the Bond. */ string symbol; /** Metadata bucket not required for the operation of the Bond, but needed by external actors. */ string data; } struct Settings { /** Number of tokens to create, which get swapped for collateral tokens by depositing. */ uint256 debtTokenAmount; /** Token contract for the collateral that is swapped for debt tokens during deposit. */ address collateralTokens; /** * Unix timestamp for when the Bond is expired and anyone can move the remaining collateral to the Treasury, * then petitions may be made for redemption. */ uint256 expiryTimestamp; /** * Minimum debt holding allowed in the deposit phase. Once the minimum is met, * any sized deposit from that account is allowed, as the minimum has already been met. */ uint256 minimumDeposit; } struct TimeLockRewardPool { /** Tokens being used for the reward. */ address tokens; /** Total number of tokens awarded to guarantors. */ uint128 amount; /** Seconds reward is locked up after redemption is allowed. */ uint128 timeLock; } }
* @title Domain model for Bonds./
library Bond { pragma solidity ^0.8.0; struct MetaData { string name; string symbol; string data; } struct Settings { uint256 debtTokenAmount; address collateralTokens; uint256 expiryTimestamp; uint256 minimumDeposit; } struct TimeLockRewardPool { address tokens; uint128 amount; uint128 timeLock; } }
2,537,555
[ 1, 3748, 938, 364, 605, 4096, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 605, 1434, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 1958, 27512, 288, 203, 3639, 533, 508, 31, 203, 3639, 533, 3273, 31, 203, 3639, 533, 501, 31, 203, 203, 565, 289, 203, 565, 1958, 8709, 288, 203, 3639, 2254, 5034, 18202, 88, 1345, 6275, 31, 203, 3639, 1758, 4508, 2045, 287, 5157, 31, 203, 3639, 2254, 5034, 10839, 4921, 31, 203, 3639, 2254, 5034, 5224, 758, 1724, 31, 203, 203, 565, 289, 203, 565, 1958, 2647, 2531, 17631, 1060, 2864, 288, 203, 3639, 1758, 2430, 31, 203, 3639, 2254, 10392, 3844, 31, 203, 3639, 2254, 10392, 813, 2531, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.15; /** * GoldGate Token Contract * Copyright © 2017 by GoldGate https://goldgate.io */ /** * @title ERC20Basic * Simpler version of ERC20 interface * https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * transfer token for a specified address */ function transfer(address _to, uint256 _value) returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * Gets the balance of the specified address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Ownable * The Ownable contract has an owner address, and provides basic authorization control */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Allows the current owner to transfer control of the contract to a newOwner. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused { paused = true; Pause(); } /** * called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused { paused = false; Unpause(); } } /** * @title Ownable */ contract GGOwnable is Ownable { address public newOwner; /** * Allows the current owner to transfer control of the contract to an otherOwner. */ function transferOwnership(address otherOwner) onlyOwner { require(otherOwner != address(0)); newOwner = otherOwner; } /** * Finish ownership transfer. */ function approveOwnership() { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /** * @title Moderated * Moderator can make transfers from and to any account (including frozen). */ contract GGModerated is GGOwnable { address public moderator; address public newModerator; /** * Throws if called by any account other than the moderator. */ modifier onlyModerator() { require(msg.sender == moderator); _; } /** * Throws if called by any account other than the owner or moderator. */ modifier onlyOwnerOrModerator() { require((msg.sender == moderator) || (msg.sender == owner)); _; } /** * Moderator same as owner */ function GGModerated(){ moderator = msg.sender; } /** * Allows the current moderator to transfer control of the contract to an otherModerator. */ function transferModeratorship(address otherModerator) onlyModerator { newModerator = otherModerator; } /** * Complete moderatorship transfer. */ function approveModeratorship() { require(msg.sender == newModerator); moderator = newModerator; newModerator = address(0); } /** * Removes moderator from the contract. */ function removeModeratorship() onlyOwner { moderator = address(0); } function hasModerator() constant returns(bool) { return (moderator != address(0)); } } /** * @title Pausable */ contract GGPausable is Pausable, GGModerated { /** * called by the owner or moderator to pause, triggers stopped state */ function pause() onlyOwnerOrModerator whenNotPaused { paused = true; Pause(); } /** * called by the owner or moderator to unpause, returns to normal state */ function unpause() onlyOwnerOrModerator whenPaused { paused = false; Unpause(); } } /** * @title Standard ERC20 token * Implementation of the basic standard token. */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * transfer tokens from one address to another */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. */ function approve(address _spender, uint256 _value) returns (bool) { // to change the approve amount you first have to reduce the addresses` require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * function to check the amount of tokens that an owner allowed to a spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title SafeMath * Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * Pausable token with moderator role and freeze address implementation **/ contract ModToken is StandardToken, GGPausable { mapping(address => bool) frozen; /** * check if given address is frozen. Freeze works only if moderator role is active */ function isFrozen(address _addr) constant returns (bool){ return frozen[_addr] && hasModerator(); } /** * Freezes address (no transfer can be made from or to this address). */ function freeze(address _addr) onlyModerator { frozen[_addr] = true; } /** * Unfreezes frozen address. */ function unfreeze(address _addr) onlyModerator { frozen[_addr] = false; } /** * Declines transfers from/to frozen addresses. */ function transfer(address _to, uint256 _value) whenNotPaused returns (bool) { require(!isFrozen(msg.sender)); require(!isFrozen(_to)); return super.transfer(_to, _value); } /** * Declines transfers from/to/by frozen addresses. */ function transferFrom(address _from, address _to, uint256 _value) whenNotPaused returns (bool) { require(!isFrozen(msg.sender)); require(!isFrozen(_from)); require(!isFrozen(_to)); return super.transferFrom(_from, _to, _value); } /** * Allows moderator to transfer tokens from one address to another. */ function moderatorTransferFrom(address _from, address _to, uint256 _value) onlyModerator returns (bool) { balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); Transfer(_from, _to, _value); return true; } } contract GoldGate is ModToken { string public constant version = "1.0.0"; string public constant name = "GoldGate"; string public constant symbol = "BGG"; uint256 public constant decimals = 8; function GoldGate(uint256 _initialSupply) { totalSupply = _initialSupply; balances[msg.sender] = _initialSupply; } }
* Freezes address (no transfer can be made from or to this address)./
function freeze(address _addr) onlyModerator { frozen[_addr] = true; }
1,814,688
[ 1, 9194, 94, 281, 1758, 261, 2135, 7412, 848, 506, 7165, 628, 578, 358, 333, 1758, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 16684, 12, 2867, 389, 4793, 13, 1338, 1739, 7385, 288, 203, 1377, 12810, 63, 67, 4793, 65, 273, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; import "./Timer.sol"; contract Auction { address internal judgeAddress; address internal timerAddress; address internal sellerAddress; address internal winnerAddress; uint winningPrice; // TODO: place your code here // constructor constructor(address _sellerAddress, address _judgeAddress, address _timerAddress) public { judgeAddress = _judgeAddress; timerAddress = _timerAddress; sellerAddress = _sellerAddress; if (sellerAddress == address(0)) sellerAddress = msg.sender; } // This is provided for testing // You should use this instead of block.number directly // You should not modify this function. function time() public view returns (uint) { if (timerAddress != address(0)) return Timer(timerAddress).getTime(); return block.number; } function getWinner() public view returns (address winner) { return winnerAddress; } function getWinningPrice() public view returns (uint price) { return winningPrice; } // If no judge is specified, anybody can call this. // If a judge is specified, then only the judge or winning bidder may call. function finalize() public { // TODO: place your code here } // This can ONLY be called by seller or the judge (if a judge exists). // Money should only be refunded to the winner. function refund() public { // TODO: place your code here } // Withdraw funds from the contract. // If called, all funds available to the caller should be refunded. // This should be the *only* place the contract ever transfers funds out. // Ensure that your withdrawal functionality is not vulnerable to // re-entrancy or unchecked-spend vulnerabilities. function withdraw() public { //TODO: place your code here } }
This can ONLY be called by seller or the judge (if a judge exists). Money should only be refunded to the winner. TODO: place your code here
function refund() public { }
12,703,691
[ 1, 2503, 848, 20747, 506, 2566, 635, 29804, 578, 326, 525, 27110, 261, 430, 279, 525, 27110, 1704, 2934, 16892, 1410, 1338, 506, 1278, 12254, 358, 326, 5657, 1224, 18, 2660, 30, 3166, 3433, 981, 2674, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 16255, 1435, 1071, 288, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x45481Dc5cEC93dC7847D13AD05c564F5F3A23cDb/sources/contracts/LUCIANSOULS.sol
Store constant values for the 2 NFT Collections: 1. Is the TICKET NFT CollectionERC1155LazyMint public immutable ticket; 2. Is the SOUL NFT CollectionERC1155LazyMint public immutable soul;address _ticketAddress,address _soulAddress
contract LUCIANSOULS is ERC1155LazyMint { constructor( string memory _name, string memory _symbol, address _royaltyRecipient, uint128 _royaltyBps pragma solidity ^0.8.0; ) ERC1155LazyMint(_name, _symbol, _royaltyRecipient, _royaltyBps) { } function verifyClaim( address _claimer, uint256 , uint256 _quantity ) public view virtual override{ require(this.balanceOf(_claimer, 0) >= _quantity, "You don't own enough TICKET NFTs"); require(this.balanceOf(_claimer, 0) >= _quantity, "You don't own enough SOUL NFTs"); } function _transferTokensOnClaim( address _receiver, uint256 _tokenId, uint256 _quantity ) internal override { this.burn( _receiver, 0, _quantity ); this.burn( _receiver, 1, _quantity ); super._transferTokensOnClaim(_receiver, _tokenId, _quantity); } }
9,523,188
[ 1, 2257, 5381, 924, 364, 326, 576, 423, 4464, 5737, 30, 404, 18, 2585, 326, 399, 16656, 1584, 423, 4464, 2200, 654, 39, 2499, 2539, 14443, 49, 474, 1071, 11732, 9322, 31, 576, 18, 2585, 326, 7460, 1506, 423, 4464, 2200, 654, 39, 2499, 2539, 14443, 49, 474, 1071, 11732, 272, 1003, 31, 2867, 389, 16282, 1887, 16, 2867, 389, 87, 1003, 1887, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 25527, 7266, 1258, 3584, 1506, 55, 353, 4232, 39, 2499, 2539, 14443, 49, 474, 288, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 1758, 389, 3800, 15006, 18241, 16, 203, 3639, 2254, 10392, 389, 3800, 15006, 38, 1121, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 262, 4232, 39, 2499, 2539, 14443, 49, 474, 24899, 529, 16, 389, 7175, 16, 389, 3800, 15006, 18241, 16, 389, 3800, 15006, 38, 1121, 13, 288, 203, 565, 289, 203, 203, 565, 445, 3929, 9762, 12, 203, 3639, 1758, 389, 830, 69, 4417, 16, 203, 3639, 2254, 5034, 269, 203, 3639, 2254, 5034, 389, 16172, 203, 565, 262, 1071, 1476, 5024, 3849, 95, 203, 3639, 2583, 12, 2211, 18, 12296, 951, 24899, 830, 69, 4417, 16, 374, 13, 1545, 389, 16172, 16, 315, 6225, 2727, 1404, 4953, 7304, 399, 16656, 1584, 423, 4464, 87, 8863, 203, 3639, 2583, 12, 2211, 18, 12296, 951, 24899, 830, 69, 4417, 16, 374, 13, 1545, 389, 16172, 16, 315, 6225, 2727, 1404, 4953, 7304, 7460, 1506, 423, 4464, 87, 8863, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 5157, 1398, 9762, 12, 203, 3639, 1758, 389, 24454, 16, 203, 3639, 2254, 5034, 389, 2316, 548, 16, 203, 3639, 2254, 5034, 389, 16172, 203, 565, 262, 2713, 3849, 288, 203, 540, 203, 3639, 333, 18, 70, 321, 12, 203, 5411, 389, 24454, 16, 203, 5411, 374, 16, 203, 5411, 389, 16172, 203, 2 ]
./partial_match/1/0x21fC96B8C0d429820bcD03872083Bf8B1A0970eb/sources/TokenSale.sol
* @dev Low-level token purchase with ETH This function has a non-reentrancy guard, so it shouldn't be called by another `nonReentrant` function. @return The total tokens bought/ Send the received ETH to the beneficiary address
function buyWithETH() public payable hasPriceConsumer nonReentrant returns (uint256) { require(msg.value > 0, "ETH: invalid buy amount"); uint256 ethPrice = priceConsumer.getLatestPrice(); require(ethPrice > 0, "ETH price not available"); uint256 usdtAmount = msg.value.mul(ethPrice).div(10 ** 8); require(beneficiaryAddress != address(0), "Beneficiary address not set"); require(success, "ETH transfer to beneficiary failed"); uint256 tokens = _buyTokens(usdtAmount); totalRaisedETH += msg.value; return tokens; }
9,408,736
[ 1, 10520, 17, 2815, 1147, 23701, 598, 512, 2455, 1220, 445, 711, 279, 1661, 17, 2842, 313, 12514, 11026, 16, 1427, 518, 12044, 1404, 506, 2566, 635, 4042, 1375, 5836, 426, 8230, 970, 68, 445, 18, 327, 1021, 2078, 2430, 800, 9540, 19, 2479, 326, 5079, 512, 2455, 358, 326, 27641, 74, 14463, 814, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 1190, 1584, 44, 1435, 1071, 8843, 429, 711, 5147, 5869, 1661, 426, 8230, 970, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 405, 374, 16, 315, 1584, 44, 30, 2057, 30143, 3844, 8863, 203, 203, 3639, 2254, 5034, 13750, 5147, 273, 6205, 5869, 18, 588, 18650, 5147, 5621, 203, 3639, 2583, 12, 546, 5147, 405, 374, 16, 315, 1584, 44, 6205, 486, 2319, 8863, 203, 203, 3639, 2254, 5034, 584, 7510, 6275, 273, 1234, 18, 1132, 18, 16411, 12, 546, 5147, 2934, 2892, 12, 2163, 2826, 1725, 1769, 203, 203, 3639, 2583, 12, 70, 4009, 74, 14463, 814, 1887, 480, 1758, 12, 20, 3631, 315, 38, 4009, 74, 14463, 814, 1758, 486, 444, 8863, 203, 3639, 2583, 12, 4768, 16, 315, 1584, 44, 7412, 358, 27641, 74, 14463, 814, 2535, 8863, 203, 203, 3639, 2254, 5034, 2430, 273, 389, 70, 9835, 5157, 12, 407, 7510, 6275, 1769, 203, 203, 3639, 2078, 12649, 5918, 1584, 44, 1011, 1234, 18, 1132, 31, 203, 203, 3639, 327, 2430, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <=0.8.9; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract BridgeEth is Initializable, UUPSUpgradeable, AccessControlUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using ECDSAUpgradeable for bytes32; bytes32 public constant MAPPER_ROLE = keccak256("MAPPER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); string public constant name = "ETH-EKTA Bridge"; mapping(address => address) public EthEktaPairs; //ETH Token => EKTA Token mapping(address => address) public EktaEthPairs; //EKTA Token => ETH Token mapping(address => mapping(uint => bool)) public processedNonces; address public admin; address public tokenToSwapWithNative; event AddedTokenPair(address indexed ethToken, address indexed ektaToken); event UpdatedTokenPair(address indexed ethToken, address indexed ektaToken); event TokenDeposited(address indexed ethToken, address indexed ektaToken, uint256 amount, address indexed user); event TokenWithdrawn(address indexed ethToken, address indexed ektaToken, uint256 amount, address indexed user); event DepositedTokenToNative(address indexed ethToken, uint256 amount, address indexed user); event WithdrawnNativeToToken(address indexed ethToken, uint256 amount, address indexed user); event TokenFromContractTransferred(address externalAddress,address toAddress, uint amount); event EthFromContractTransferred(address toAddress, uint amount); event AdminAddressUpdated(address admin); event TokenToSwapWithNativeUpdated(address token); /** * @dev Initializes the contract. * * Requirements: * - @param _owner cannot be the zero address. * - @param _tokenToSwapWithNative cannot be the zero address. */ function initialize(address _owner, address _tokenToSwapWithNative) public initializer { require(_owner != address(0), "Bridge: Address cant be zero address"); require(_tokenToSwapWithNative != address(0), "Bridge: Token address cant be zero address"); _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setupRole(MAPPER_ROLE, _owner); _setupRole(PAUSER_ROLE, _owner); admin = msg.sender; tokenToSwapWithNative = _tokenToSwapWithNative; // initializing __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); __Ownable_init_unchained(); } function _authorizeUpgrade(address) internal override onlyOwner {} /** * @dev Creates a pair for eth and ekta token by the caller with MAPPER_ROLE. * * Requirements: * - @param _ethToken cannot be the zero address. * - @param _ektaToken cannot be the zero address. * * @return A boolean value indicating whether the operation succeeded. * * Emits a {AddedTokenPair} event indicating the paired token addresses. */ function addTokenPairs(address _ethToken, address _ektaToken) external onlyRole(MAPPER_ROLE) nonReentrant whenNotPaused returns(bool) { require(EthEktaPairs[_ethToken] == address(0) && EktaEthPairs[_ektaToken] == address(0), "Bridge: Already mapped"); _mapToken(_ethToken, _ektaToken); emit AddedTokenPair(_ethToken, _ektaToken); return true; } /** * @dev Updates the ekta pair address for eth token by the caller with MAPPER_ROLE * * Requirements: * - @param _ethToken cannot be the zero address. * - @param _ektaToken cannot be the zero address. * * @return A boolean value indicating whether the operation succeeded * * Emits a {UpdatedTokenPair} event indicating the paired token addresses */ function updateTokenPairs(address _ethToken, address _ektaToken) external onlyRole(MAPPER_ROLE) nonReentrant whenNotPaused returns(bool) { require(EthEktaPairs[_ethToken] != _ektaToken, "Bridge: Pair already exists"); require(EthEktaPairs[_ethToken] != address(0), "Bridge: Pair dont exists"); // clean token pairs to avoid re-mapping cleanTokenPairs(_ethToken); _mapToken(_ethToken, _ektaToken); emit UpdatedTokenPair(_ethToken, _ektaToken); return true; } /** * @dev Clears the eth and ekta pair address to avoid re-mapping by the caller with MAPPER_ROLE * * Requirements: * - @param _ethToken cant be zero address * * @return A boolean value indicating whether the operation succeeded */ function cleanTokenPairs(address _ethToken) public onlyRole(MAPPER_ROLE) whenNotPaused returns(bool) { require(_ethToken != address(0), "Bridge: Token address cant be zero address"); require(EthEktaPairs[_ethToken] != address(0), "Bridge: Pair dont exists"); address _ektaToken = EthEktaPairs[_ethToken]; EthEktaPairs[_ethToken] = address(0); EktaEthPairs[_ektaToken] = address(0); return true; } /** * @dev Internal function to map tokens * * Requirements: * - @param _ethToken cannot be the zero address. * - @param _ektaToken cannot be the zero address. */ function _mapToken(address _ethToken, address _ektaToken) internal { require(_ethToken != address(0) && _ektaToken != address(0), "Bridge: Token address cant be zero address"); // update EthEktaPairs and EktaEthPairs mapping EthEktaPairs[_ethToken] = _ektaToken; EktaEthPairs[_ektaToken] = _ethToken; } /** * @dev Move token amount from caller to contract address. * * Requirements: * - @param _ethToken cannot be the zero address. * - @param amount should be greater than 0. * * @return A boolean value indicating whether the operation succeeded. * * Emits a {TokenDeposited} event. */ function deposit(address _ethToken, uint256 amount) external nonReentrant whenNotPaused returns(bool) { require(_ethToken != address(0), "Bridge: Token cant be zero address"); require(EthEktaPairs[_ethToken] != address(0), "Bridge: Token not paired"); require(amount > 0, "Bridge: Amount cant be zero or negative numbers"); // transfer token to contract address IERC20Upgradeable(_ethToken).safeTransferFrom(msg.sender, address(this), amount); address ektaToken = EthEktaPairs[_ethToken]; emit TokenDeposited(_ethToken, ektaToken, amount, msg.sender); return true; } /** * @dev Move token amount from contract address to user * after successful verification of signature and nonce. * * Requirements: * - @param _ethToken cannot be the zero address. * - @param _ektaToken cannot be the zero address. * - @param user cannot be the zero address. * - @param amount should be greater than 0. * - @param nonce. * - @param signature. * * @return A boolean value indicating whether the operation succeeded. * * Emits a {TokenWithdrawn} event. */ function withdraw(address _ethToken, address _ektaToken, address user, uint256 amount, uint256 nonce, bytes calldata signature) external nonReentrant whenNotPaused returns(bool) { require(_ethToken != address(0), "Bridge: Token cant be zero address"); require(_ektaToken != address(0), "Bridge: Token cant be zero address"); require(EthEktaPairs[_ethToken] == _ektaToken, "Bridge: Token pair does not exist"); require(amount > 0, "Bridge: Amount cant be zero or negative numbers"); // check for nonce require(!processedNonces[user][nonce], 'Bridge: Transfer already processed'); // verify signature require(_verify(abi.encodePacked(user, amount, nonce, "ETH_WITHDRAW", _ethToken, _ektaToken), signature), "Bridge: Invalid signature"); // transfer token from contract address to user IERC20Upgradeable(_ethToken).safeTransfer(user, amount); // update nonce processedNonces[user][nonce] = true; address ektaToken = EthEktaPairs[_ethToken]; emit TokenWithdrawn(_ethToken, ektaToken, amount, user); return true; } /** * @dev Move `tokenToSwapWithNative` token amount from caller to contract address * * Requirements: * - @param amount should be greater than 0. * * @return A boolean value indicating whether the operation succeeded. * * Emits a {DepositedTokenToNative} event. */ function depositTokenToNative(uint256 amount) external nonReentrant whenNotPaused returns(bool) { require(amount > 0, "Bridge: Amount cant be zero or negative numbers"); // transfer token to contract address IERC20Upgradeable(tokenToSwapWithNative).safeTransferFrom(msg.sender, address(this), amount); emit DepositedTokenToNative(tokenToSwapWithNative, amount, msg.sender); return true; } /** * @dev Move `tokenToSwapWithNative` token amount from contract address to user * * Requirements: * - @param user cannot be the zero address. * - @param amount should be greater than 0. * - @param nonce. * - @param signature. * * @return A boolean value indicating whether the operation succeeded. * * Emits a {WithdrawnNativeToToken} event. */ function withdrawNativeToToken(address user, uint256 amount, uint256 nonce, bytes calldata signature) external nonReentrant whenNotPaused returns(bool) { require(amount > 0, "Bridge: Amount cant be zero or negative numbers"); // check for nonce require(!processedNonces[user][nonce], 'Bridge: Transfer already processed'); // verify signature require(_verify(abi.encodePacked(user, amount, nonce, "ETH_NATIVE_WITHDRAW"), signature), "Bridge: Invalid signature"); // transfer token from contract address to user IERC20Upgradeable(tokenToSwapWithNative).safeTransfer(user, amount); // update nonce processedNonces[user][nonce] = true; emit WithdrawnNativeToToken(tokenToSwapWithNative, amount, user); return true; } /** * @dev Update the admin address used for signature verification * by caller with DEFAULT_ADMIN_ROLE. * * Requirements: * - @param _admin cannot be the zero address. * * Emits a {AdminAddressUpdated} event indicating the updated admin address. */ function updateAdminAddress(address _admin) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_admin != address(0), "Bridge: Admin address cant be zero address"); admin = _admin; emit AdminAddressUpdated(admin); } /** * @dev Update the token address used for swapping with native * by caller with DEFAULT_ADMIN_ROLE. * * Requirements: * - @param token cannot be the zero address. * * Emits a {TokenToSwapWithNativeUpdated} event indicating the updated token address. */ function updateTokenToSwapWithNative(address token) external onlyRole(DEFAULT_ADMIN_ROLE) { require(token != address(0), "Bridge: Token address cant be zero address"); tokenToSwapWithNative = token; emit TokenToSwapWithNativeUpdated(tokenToSwapWithNative); } /** * @dev Pause the contract (stopped state) * by caller with PAUSER_ROLE. * * Requirements: * - The contract must not be paused. * * Emits a {Paused} event. */ function pause() external onlyRole(PAUSER_ROLE) { _pause(); } /** * @dev Unpause the contract (normal state) * by caller with PAUSER_ROLE. * * Requirements: * - The contract must be paused. * * Emits a {Unpaused} event. */ function unpause() external onlyRole(PAUSER_ROLE){ _unpause(); } /** * @dev Recover the amount of particular token from the contract address * by caller with DEFAULT_ADMIN_ROLE. * * Requirements: * - @param _tokenContract cannot be the zero address. * - @param amount should be greater than 0. * * Emits a {TokenFromContractTransferred} event indicating the token address and amount. */ function withdrawERC20Token(address _tokenContract, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_tokenContract != address(0), "Bridge: Address cant be zero address"); IERC20Upgradeable tokenContract = IERC20Upgradeable(_tokenContract); require(amount <= tokenContract.balanceOf(address(this)), "Bridge: Amount exceeds balance"); tokenContract.transfer(msg.sender, amount); emit TokenFromContractTransferred(_tokenContract, msg.sender, amount); } // to recieve ETH receive() external payable {} /** * @dev Recover ETH from the contract address * by caller with DEFAULT_ADMIN_ROLE. * * Requirements: * - @param user cannot be the zero address. * - @param amount cannot be greater than balance. * * Emits a {EthFromContractTransferred} event. */ function withdrawEthFromContract(address user, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { require(user != address(0), "Bridge: Address cant be zero address"); require(amount <= address(this).balance, "Bridge: Amount exceeds balance"); address payable _user = payable(user); (bool success, ) = _user.call{value: amount}(""); require(success, "Bridge: Transfer failed."); emit EthFromContractTransferred(user, amount); } /** * @dev Internal function to verify the signature. * * Requirements: * - @param data encoded bytes of signature params. * - @param signature. */ function _verify(bytes memory data, bytes calldata signature) view internal returns (bool) { return keccak256(data) .toEthSignedMessageHash() .recover(signature) == admin; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; }
* @dev Update the token address used for swapping with native by caller with DEFAULT_ADMIN_ROLE. Requirements: - @param token cannot be the zero address. Emits a {TokenToSwapWithNativeUpdated} event indicating the updated token address./
function updateTokenToSwapWithNative(address token) external onlyRole(DEFAULT_ADMIN_ROLE) { require(token != address(0), "Bridge: Token address cant be zero address"); tokenToSwapWithNative = token; emit TokenToSwapWithNativeUpdated(tokenToSwapWithNative); }
535,643
[ 1, 1891, 326, 1147, 1758, 1399, 364, 7720, 1382, 598, 6448, 635, 4894, 598, 3331, 67, 15468, 67, 16256, 18, 29076, 30, 300, 225, 1147, 2780, 506, 326, 3634, 1758, 18, 7377, 1282, 279, 288, 1345, 774, 12521, 1190, 9220, 7381, 97, 871, 11193, 326, 3526, 1147, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1089, 1345, 774, 12521, 1190, 9220, 12, 2867, 1147, 13, 3903, 1338, 2996, 12, 5280, 67, 15468, 67, 16256, 13, 288, 203, 565, 2583, 12, 2316, 480, 1758, 12, 20, 3631, 315, 13691, 30, 3155, 1758, 848, 88, 506, 3634, 1758, 8863, 203, 565, 1147, 774, 12521, 1190, 9220, 273, 1147, 31, 203, 565, 3626, 3155, 774, 12521, 1190, 9220, 7381, 12, 2316, 774, 12521, 1190, 9220, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/************************ * Version 0.0 of Bee Arbitration * WARNING: byte code is real close to ganache limit * a few more lines and it won't port over but if you * use remix you have some room to spare. There must be a * optmizer for bytecode size somewhere * * Not created for production * Not fully unit tested * No audits for hacking have been done * ***********************/ pragma solidity ^0.4.24; import 'openzeppelin-solidity/contracts/token/ERC20/ERC20.sol'; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; contract BaseModifiers is Ownable{ bool activated_; function activated() public view returns (bool) { return activated_; } modifier isActivated() { require(activated_ == true, "its not ready yet"); _; } function activateContract() public onlyOwner { activated_ = true; } function deactivateContract() public onlyOwner { activated_ = false; } } contract BeeModifiers is BaseModifiers { mapping (address => bool) public whiteListedContracts; function addContractAddress(address _contractAddress) onlyOwner external { require(whiteListedContracts[_contractAddress]==false, "contract addres already added"); whiteListedContracts[_contractAddress]=true; } function removeContractAddress(address _contractAddress) onlyOwner external { require (_contractAddress != 0, "contract address can't be 0"); require (whiteListedContracts[_contractAddress] != false, "must be a valid address"); delete(whiteListedContracts[_contractAddress]); } modifier isNotContract() { address _addr = msg.sender; require (_addr == tx.origin); uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry only white listed contracts allowed"); _; } modifier isWhitelistedContract() { address _addr = msg.sender; require(whiteListedContracts[_addr]==true); _; } } contract BeeArbEvents { event MinerBanned ( uint256 minerId, //the unique Ids of the arbitration requested uint256 timestamp //timestamp of request ); event MinerApproved ( uint256 minerId, //the unique Ids of the arbitration requested uint256 timestamp //timestamp of request ); // fired whenever an aribitration is requested event ArbRequested ( uint256 arbitrationId, //the unique Ids of the arbitration requested bytes32 paymentId, //payment Ids are byte32s, reservation Id might be different uint256 timestamp, //timestamp of request uint256 minTime, //min timetimestamp to wait for when miners can start to try and arbitrate uint256 maxTime, //maximum timestamp to wait until before defaulting to default arbitrators uint256 beeTokensDispute, //amount of bee tokens in dispute uint256 beeTokensArbitration //amount of bee tokens paid for arbitration to occur ); event MinerStartedMining ( uint256 arbitrationId, //The unique id of miner uint256 minerIndexId, //The index of the miner array (really a set) they are in uint256 stake, //the stake the miner started mining with uint256 timestamp //timestamp of request ); event MinerFailedStartedMining ( uint256 arbitrationId, //The unique id of miner bytes32 errorMessage, uint256 stake, //the stake the miner started mining with uint256 timestamp //timestamp of request ); event MinerStoppedMining ( uint256 arbitrationId, //The unique id of miner uint256 stake, //the stake the miner started mining with uint256 timestamp //timestamp of request ); event ArbitrationJobTriggered ( uint256 arbitrationJobId, //The unique id of job triggered address triggermanAddress, //the address of the person who triggered the event uint256 path, //the path that the trigger took uint256 timestamp //timestamp of request ); event ArbiterVoteSubmitted ( uint256 arbiterId, //The unique id of abiter uint256 voteSubmitted, //the path that the trigger took uint256 timestamp //timestamp of request ); // fired when not enough miners are present to start arbitration process event ArbDelayed ( uint256 errorCode, //1 = not enough miners uint256 arbitrationId, //the unique Id of the arbitration requested bytes32 paymentId, //payment Ids are byte32s, reservation Id might be different uint256 timestamp //timestamp ); // fired when an arbitraion is completed event ArbCompleted ( uint256 arbitrationId, //the unique Id of the arbitration requested //maybe put in who voted for what in here too? uint256 voteResult, // percent 0 - 100 awarded to guest, rest awarded to host bytes32 paymentId, //payment Ids are byte32s, reservation Id might be different uint256 timestamp //timestamp of vote ); event ArbiterPaid ( uint256 arbiterId, //id of arbiter uint256 vote, // vote casted uint256 amountPaid, //amount paid uint256 timestamp //timestamp of vote ); event ArbiterPenalized ( uint256 arbiterId, //id of arbiter uint256 voteId, // the unique id of the vote they needed to do but failed to do uint256 beeTokenTaken, //amount paid uint256 beeTokenStaked, //amount paid uint256 timestamp //timestamp of vote ); } contract BeeArbitrationStructs { struct ArbitrationJob { uint256 arbitrationId; //if this was an appeal, this is the Id of the arbitration it came from bytes32 paymentId; //payment Ids are byte32s, reservation Id might be different uint256 timestamp; //timestamp of request uint256 minMinerTime; //min timetimestamp to wait for when miners can start to try and arbitrate uint256 maxMinerTime; //maximum timestamp to wait until before defaulting to default arbitrators uint256 appealTimelimit; //maximum time allowed for appeal uint256 beeTokensArbitrationFee; //amount of bee tokens paid for arbitration to occur uint256 [] arbiterVoteIds; uint256 disputedAmountOfBeeTokens; address host; address guest; } enum ArbiterAccessState { PENDING_APPROVAL, // can trigger but cannot mine APPROVED, // can trigger and can mine BANNED //can trigger but cannot mine } //try to use up 256 bits struct Arbiter { ArbiterAccessState accessState;//8bit int, holds info if they can mine or trigger address minerAddress; uint256 miningArrayIndex; uint256 currentBeeTokenStake; uint256 arbitrationsCompleted; //maybe put this in reputation api uint256 arbitrationsAppealed; //maybe put this in reputation api uint256 [] arbiterVoteIds; } enum VoteState { NOT_ASSIGNED_TO_ARBITER, //assigned to a job but not yet assigned to a miner / arbiter yet PENDING_VOTE, //Arbiter hasn't voted yet VOTE_COMPLETE, //Arbiter has voted PENALIZED_NO_VOTE, //Arbiter failed to vote by min mining time and was penalized for it VOTE_PAID //Arbiter voted and was paid for it } struct ArbiterVote { VoteState state; //0 hasn't voted, 1 has voted, 2 penealized for not voting (NOTE: since we have extra bits, why not) uint8 vote;//0 by default uint256 arbitrationJobId; uint256 arbiterId; } struct MinerTicketHolder { uint256 miningId; uint256 numLottoTickets; } } contract BeeArbitration is BeeArbEvents, BeeModifiers, BeeArbitrationStructs { using SafeMath for uint256; uint8 beeTokenPenality = 100; //0-100% pentality for Arbiters's staked bee tokens if submission isn't completed by max time uint8 activeMinerPayPercentage = 100; //After the triggerman get's paid, this is the percentage of bee tokens that are left over that get distributed among the arbiters uint8 percentPenTokensToFee = 100; //percent of bee tokens taken from miners who didn't vote put into miners fee. rest just lives in contract until owner pulls it out uint8 percentAppealFeeToDisputeAmount = 0; //percent of bee tokens after we subtract arbitration fee to be put into dispute amount for host/ guest, the rest goes to owner of contract uint8 [] triggermanPayBeeTokenAmount = [2,3,3,3,3,3]; //how much the triggerman gets paid. each element in the array is a pay path uint8 [] percentDisputedChoices = [0,25,50,75,100];//0,25,50,75,100 in whitepaper. percent of bee tokens of the disputed amount to be distributed to the winner. This is the vote choices uint8 nonce = 0; //used for random number generation uint8 appealMultCost = 2; //multiplier of previous appeal cost so they appeal less uint8 arbitersPerJob = 5; //todo figure out gas price of executing everything, write up code that gets current eth price and current bee price then figures out a correct arb fee or static? uint256 public normArbFee = 1110000; //fee we charge to do arbitrations uint256 public minMiningStake = 1000; //min number of bee tokens needed to stake for miners uint256 minMinerTime = 1 days; //min time to wait before miners can be selected as Arbiters uint256 maxMinerTime = 5 days; //max time to wait before going to default Arbiters uint256 appealTime = 3 days; //max time allowed for users to appeal decisions Arbiter [] public existingArbiters;//requirement is existing Arbiters index 0 needs to be taken in constuctor because mapping returns 0 if not there MinerTicketHolder [] public arbitersMining; //we can't make this into a view because the contract that modifies data will need this info, read costs like 5k, write is 20k ArbitrationJob [] public arbitrationJobs; ArbiterVote [] public arbVotes; mapping (address => uint256) public addressToMinerId; uint256 [] public jobsInProgress; //when an arbitration job comes in, the Id is in here till it is completed or appealed mapping (bytes32 => uint256[]) public paymentIdToJobIds; address beeTokenContractAddress; ERC20 beeToken; //////// //OWNER FUNCTIONS //////// /** * @dev default function, unsure about this at the moment, maybe disable * -functionhash- unknown yet */ function () public payable { revert(); } /** * @dev constructor, adds default values for everything and adds in * a dummy var for our pointers that maps can go to. A map value without * a key produces a value of 0, so as an extra safeguard, I put in dummy * values at location 0 so if there is a problem it's not as bad * -functionhash- unknown yet */ constructor(address beeTokenAddress) public { beeTokenContractAddress = beeTokenAddress; beeToken = ERC20(beeTokenContractAddress); Arbiter memory dummyArbiter = Arbiter({ accessState:ArbiterAccessState.BANNED, minerAddress:0x0, currentBeeTokenStake:0, arbitrationsCompleted:0, arbitrationsAppealed:0, miningArrayIndex:0, arbiterVoteIds:new uint256[](0) }); existingArbiters.push(dummyArbiter); ArbitrationJob memory dummyArbiterJob = ArbitrationJob({ arbitrationId:0, paymentId:"dummyJob", timestamp:0, minMinerTime:0, maxMinerTime:0, appealTimelimit:0, beeTokensArbitrationFee:0, arbiterVoteIds:new uint256[](arbitersPerJob), disputedAmountOfBeeTokens:0, host:0x0, guest:0x0 }); arbitrationJobs.push(dummyArbiterJob); jobsInProgress.push(0); //not really needed but lets make it consistant //not really needed but better safe then sorry if someone decides to add in a mapping to this array ArbiterVote memory dummyArbiterVote = ArbiterVote({ state:VoteState.PENDING_VOTE, arbitrationJobId:0, vote:0, arbiterId:0 }); arbVotes.push(dummyArbiterVote); MinerTicketHolder memory curTickets = MinerTicketHolder({ miningId:0, numLottoTickets:0 }); arbitersMining.push(curTickets); } /** * @dev owner of the contract has to approve all miners before they can vote * -functionhash- unknown yet * @param arbId arbitrationId of the arbiter / miner */ function approveMiner(uint256 arbId) onlyOwner() external { require(arbId < existingArbiters.length, "no arbiter by that number exists"); Arbiter storage curMiner = existingArbiters[arbId]; curMiner.accessState = ArbiterAccessState.APPROVED; // emit MinerApproved(arbId, now); } /** * @dev take a ban a miner from voting again * -functionhash- unknown yet * @param arbId arbitrationId of the arbiter / miner */ function banMiner(uint256 arbId) onlyOwner() external { require(arbId < existingArbiters.length, "no arbiter by that number exists"); Arbiter storage curMiner = existingArbiters[arbId]; curMiner.accessState = ArbiterAccessState.BANNED; uint index = curMiner.miningArrayIndex; if (index >= 1) { removeMinerFromQueue(index); curMiner.miningArrayIndex = 0; //they could still be voting so we don't want to return their stake in case we need to penalize them later //require(beeToken.transfer(curMiner.minerAddress, curMiner.currentBeeTokenStake), "transfer to miner stake failed"); //curMiner.currentBeeTokenStake = 0; } // emit MinerBanned(arbId, now); } //Ability for owner to transfer other ERC20 tokens as well as bee dust out function transferToken(address tokenContractAddress, address transferTo, uint256 value) onlyOwner external { ERC20 token = ERC20(tokenContractAddress); if (tokenContractAddress == beeTokenContractAddress) { //if owner is transfering out bee token dust, make sure owner doesn't try and transfer out promised bee tokens uint256 promisedBeeTokens = 0; for (uint256 i =0; i<arbitrationJobs.length; i++) { if (now < arbitrationJobs[i].appealTimelimit || now < arbitrationJobs[i].maxMinerTime || now < arbitrationJobs[i].minMinerTime) { promisedBeeTokens += arbitrationJobs[i].beeTokensArbitrationFee; promisedBeeTokens += arbitrationJobs[i].disputedAmountOfBeeTokens; } } for (uint256 j =0; j<arbitersMining.length; j++) { promisedBeeTokens += existingArbiters[arbitersMining[j].miningId].currentBeeTokenStake; } uint256 extraBeeTokens = token.balanceOf(this)-promisedBeeTokens; require(value <= extraBeeTokens, "not enough bee tokens"); } require(token.transfer(transferTo, value), "trasfer of bee tokens to user failed"); } //////// //payment contract FUNCTIONS //////// /** * @dev bee payment contract must transfer the tokens before calling this * method or it will return an error. only payment contract can call this * Starts up an arbitration, don't forget to pay the arbitration fee on top * of the dispute amount * -functionhash- unknown yet * @param paymentId The Id that all the booking info is under * @param disputedBeeTokensAndFee How many bee tokens are under dispute * @param host The host eth wallet address * @param guest The guest eth wallet address */ //norm flow testing complete function requestArbitration(bytes32 paymentId, uint256 disputedBeeTokensAndFee, address guest, address host) external isWhitelistedContract() isActivated() { require(beeToken.transferFrom(msg.sender, address(this), disputedBeeTokensAndFee), "unable to transfer tokens from contract"); createJob(paymentId, disputedBeeTokensAndFee.sub(normArbFee), host, guest, 0); //event launched in create job, less reads } //////// //Everyone else FUNCTIONS //////// /** * @dev anyone can request an appeal but usually the host / guest would. * as a design decision I could limit it to a host or guest, but if there * is a bad vote, we as bee token can pay to request an appeal. * * -functionhash- unknown yet * @param prevArbId the arbitration that the person wants to dispute */ function requestAppeal(uint256 prevArbId) external isNotContract() isActivated() { require(arbitrationJobs.length > prevArbId, "prev ruling does not exist"); ArbitrationJob memory prevJob = arbitrationJobs[prevArbId]; require(now < prevJob.appealTimelimit, "previous rulling appeal time has already concluded"); require(now > prevJob.maxMinerTime, "previous rulling is still being voted on"); require(msg.sender == prevJob.host || msg.sender == prevJob.guest || msg.sender == owner, "appeal only avalible to guest, host or owner"); uint256 appealCost = normArbFee.mul(appealMultCost); //request money for appeal require(beeToken.transferFrom(msg.sender, address(this), appealCost), "payment for appeal rejected"); uint256 extraBeeTokensFromAppeal = appealCost.sub(normArbFee); uint256 beeToAddToDispute = extraBeeTokensFromAppeal.mul(percentAppealFeeToDisputeAmount) / 100; createJob(prevJob.paymentId, prevJob.disputedAmountOfBeeTokens.add(beeToAddToDispute) , prevJob.host, prevJob.guest, prevArbId); removeIndexFromArray(prevArbId, jobsInProgress); payArbs(prevJob); } /** * @dev preferabilly this is called when something is in the queue ready * to get mined otherwise it's kind of wasted gas. it announces that * the user is ready to get picked to be an arbiter * -functionhash- unknown yet * @param beeToStake The amount of bee tokens the miner is staking */ //norm flow tested function startMining(uint256 beeToStake) external isNotContract() isActivated() { require(beeToStake >= minMiningStake, "bee token stake not at least minimum required"); //check to see if user has a miner Id, if not, create miner and assign Id uint256 minerId = addressToMinerId[msg.sender]; if (minerId == 0) { //create miner minerId = registerNewUser(); } Arbiter memory curMiner = existingArbiters[minerId]; if (curMiner.accessState == ArbiterAccessState.APPROVED) { require (curMiner.miningArrayIndex == 0, "miner already in mining queue"); //require that the user is not currently in the mining state require(beeToken.transferFrom(curMiner.minerAddress, address(this), beeToStake), "bee token stake payment fail"); //get staked tokens curMiner.currentBeeTokenStake = beeToStake; //put miner into mining queue uint256 completedJobs = curMiner.arbitrationsCompleted.add(2); //make it not perfect and avoid div 0 err uint256 appealed = curMiner.arbitrationsAppealed.add(1); //make it not perfect and avoid div 0 err uint256 goodJobs = completedJobs.sub(appealed); uint256 tickets = beeToStake.mul(goodJobs) /completedJobs; MinerTicketHolder memory curTickets = MinerTicketHolder({ miningId:minerId, numLottoTickets:tickets }); uint256 minerArrayIndex = arbitersMining.push(curTickets)-1; curMiner.miningArrayIndex = minerArrayIndex; existingArbiters[minerId] = curMiner; emit MinerStartedMining(minerId,minerArrayIndex, beeToStake, now); } else { if (curMiner.accessState == ArbiterAccessState.BANNED) { emit MinerFailedStartedMining(minerId,"miner banned", beeToStake, now); } else if (curMiner.accessState == ArbiterAccessState.PENDING_APPROVAL) { emit MinerFailedStartedMining(minerId,"miner pending approval", beeToStake, now); } } } /** * @dev stops mining for the caller if they are in the mining state * -functionhash- unknown yet */ //norm flow tested function stopMining() external isNotContract() isActivated() { //take miner out of mining queue uint256 minerId = addressToMinerId[msg.sender]; require (minerId >=1, "miner doesn't exist"); Arbiter memory curMiner = existingArbiters[minerId]; uint index = curMiner.miningArrayIndex; require(index > 0, "miner not in mining queue"); //require that the user is currently mining removeMinerFromQueue(index); require(beeToken.transfer(curMiner.minerAddress, curMiner.currentBeeTokenStake), "transfer to miner stake failed"); emit MinerStoppedMining (minerId, curMiner.currentBeeTokenStake, now); curMiner.currentBeeTokenStake = 0; curMiner.miningArrayIndex = 0; existingArbiters[minerId] = curMiner; } /** * @dev A triggerman would use checkTriggermanNextNeededJob for free on * client side until they see something that needs to be triggered. * after that they would call this function to trigger an event and * get paid for it * -functionhash- unknown yet * @param arbitrationInProgressJobId the index of the arbitration job inside arbitration job */ function triggerArbJob(uint256 arbitrationInProgressJobId) external isNotContract() isActivated() { //TODO figure out gas it takes to do each one of the states, then assign percentage of single Arbiter pay for it require (arbitrationInProgressJobId<jobsInProgress.length, "job doesn't exist"); uint256 arbitraionJobId = jobsInProgress[arbitrationInProgressJobId]; ArbitrationJob storage currentJob = arbitrationJobs[arbitraionJobId]; //TODO this can be heavily optmized, way too many reads //check if miner job is voteComplete uint256 votesInProgress = 0; uint256 nonAssignedVotes = 0; for (uint256 i=0; i < currentJob.arbiterVoteIds.length; i++) { if (arbVotes[currentJob.arbiterVoteIds[i]].state == VoteState.VOTE_COMPLETE) { votesInProgress++; } else if (arbVotes[currentJob.arbiterVoteIds[i]].state == VoteState.NOT_ASSIGNED_TO_ARBITER) { nonAssignedVotes++; } } uint256 votersNeeded = arbitersPerJob - votesInProgress; if (nonAssignedVotes >0 && now > currentJob.minMinerTime && now < currentJob.maxMinerTime) { //job ready for miners to arbitrate, min time has been waited, assign Arbiters require (arbitersMining.length >= arbitersPerJob+1, "needs enough arbiters to init a vote state: createJob"); //TODO Optimization need to filter out unique miners from arbs mining.length < votes needed //select miners selectArbitersFromMiners (currentJob, arbitraionJobId); currentJob.maxMinerTime = now.add(maxMinerTime); payTriggerman(1, currentJob); emit ArbitrationJobTriggered(arbitraionJobId, msg.sender, 1, now); } else if (votersNeeded == 0 && now > currentJob.maxMinerTime && currentJob.appealTimelimit == 0) { //vote complete, set timer for users to appeal //set max appeal time currentJob.appealTimelimit = now.add(appealTime); payTriggerman(2, currentJob); emit ArbitrationJobTriggered(arbitraionJobId, msg.sender, 2, now); } else if (votersNeeded == 0 && now > currentJob.maxMinerTime && now > currentJob.appealTimelimit) { //vote complete and no appeal has taken place in max appeal time, render judgement //remove from jobsInProgress removeIndexFromArray(arbitrationInProgressJobId, jobsInProgress); //refund people / give either the renter or rentee the money abideByFinalVoteOfArbs(currentJob, arbitraionJobId); payArbs(currentJob); payTriggerman(3, currentJob); emit ArbitrationJobTriggered(arbitraionJobId, msg.sender, 3, now); //if vote not complete } else if (votersNeeded > 0 && now > currentJob.minMinerTime && now > currentJob.maxMinerTime) {//some people didn't vote or the max timer ran out penalizeArbitersForNotVoting (currentJob, arbitraionJobId); //penalize and boot all arbiters who didn't vote require (arbitersMining.length >= arbitersPerJob+1, "needs enough arbiters to init a vote state:vote not complete"); //TODO Optimization need to filter out unique miners from arbs mining.length < votes needed selectArbitersFromMiners (currentJob, arbitraionJobId); currentJob.minMinerTime = now.sub(2); currentJob.maxMinerTime = now.add(maxMinerTime); payTriggerman(4, currentJob); emit ArbitrationJobTriggered(arbitraionJobId, msg.sender, 4, now); emit ArbDelayed(1, arbitraionJobId, currentJob.paymentId, now); } else { //failed to trigger anything emit ArbitrationJobTriggered(arbitraionJobId, msg.sender, 0, now); } } /** * @dev once the miner is named to be an arbiter, then they can get paid to * vote, once they vote, we pay them. The arbiter will only get the * payment Id and amount of bee in dispute info from this contract, * they will need to get the rest of the info via centeralized backend * or payment contract for now (TODO change when storage gets cheaper) * -functionhash- unknown yet * @param voteId the vote id of the vote that the arbiter is processing * @param vote the vote that the arbiter is casting */ function arbitrationVote(uint256 voteId, uint8 vote) external isNotContract() isActivated() { ArbiterVote storage currentVote = arbVotes[voteId]; Arbiter storage curArb = existingArbiters[currentVote.arbiterId]; require (msg.sender == curArb.minerAddress, "only arbiter assigned to vote can vote"); //make sure it's the miner who owns the vote who is voting require(vote < percentDisputedChoices.length, "vote needs to be within the vote options"); ArbitrationJob storage currentJob = arbitrationJobs[currentVote.arbitrationJobId]; require (currentJob.maxMinerTime > now, "can't vote / change vote after time limit is completed");//make sure they still got time to vote //check to see if vote was discarded because user didn't vote in time require (currentVote.state == VoteState.PENDING_VOTE || currentVote.state == VoteState.VOTE_COMPLETE, "vote state invalid"); currentVote.vote = vote; currentVote.state = VoteState.VOTE_COMPLETE; emit ArbiterVoteSubmitted(currentVote.arbiterId, vote, now); } /** * @dev usually called via client so it doesn't cost gas because it's a view * then the client uses info to trigger actions and get paid for it returns next job needed to trigger * can also just be done client side * -functionhash- unknown yet */ function checkTriggermanNextNeededJob() external view returns (uint256) //returns next job needed to get triggered { for (uint256 i = 1; i<jobsInProgress.length; i++) { if (checkTriggermanNeededSingleJob(jobsInProgress[i])) { return jobsInProgress[i]; } } return 0; } /** * @dev checks to see if a job is ready to get triggered * * -functionhash- unknown yet * @param arbitrationInProgressJobId the index of the arbitration job inside arbitration job */ function checkTriggermanNeededSingleJob(uint256 arbitrationInProgressJobId) public view returns (bool) { require (arbitrationInProgressJobId<jobsInProgress.length, "arb job does not exit"); uint256 arbitraionJobId = jobsInProgress[arbitrationInProgressJobId]; ArbitrationJob storage currentJob = arbitrationJobs[arbitraionJobId]; //check if miner job is voteComplete uint256 votesInProgress = 0; uint256 nonAssignedVotes = 0; for (uint256 i=0; i < currentJob.arbiterVoteIds.length; i++) { if (arbVotes[currentJob.arbiterVoteIds[i]].state == VoteState.VOTE_COMPLETE) { votesInProgress++; } else if (arbVotes[currentJob.arbiterVoteIds[i]].state == VoteState.NOT_ASSIGNED_TO_ARBITER) { nonAssignedVotes++; } } uint256 votersNeeded = arbitersPerJob - votesInProgress; if (nonAssignedVotes >0 && now > currentJob.minMinerTime && now < currentJob.maxMinerTime) { //job ready for miners to arbitrate, min time has been waited, assign Arbiters if (arbitersMining.length > arbitersPerJob+1) { //TODO Optimization need to filter out unique miners from arbs mining.length < votes needed return false; } return true; } else if (votersNeeded == 0 && now > currentJob.maxMinerTime && currentJob.appealTimelimit == 0) { //vote complete, set timer for users to appeal return true; } else if (votersNeeded == 0 && now > currentJob.maxMinerTime && now > currentJob.appealTimelimit) { //vote complete and no appeal has taken place in max appeal time, render judgement return true; } else if (votersNeeded > 0 && now > currentJob.minMinerTime && now > currentJob.maxMinerTime) {//some people didn't vote or the max timer ran out //TODO predict how many arbiters will get dropped because they didn't vote and use arbitersPerJob+ needed arbs instead of *2 if (arbitersMining.length > (arbitersPerJob*2)+1) { //TODO Optimization need to filter out unique miners from arbs mining.length < votes needed return false; } return true; } return false; } /** * @dev next vote id that they need to do or 0 if no current jobs are avalible * * -functionhash- unknown yet */ function getMyFirstIncompletedVote() external view returns (uint256) { uint256 minerId = addressToMinerId[msg.sender]; require (minerId >0, "miner doesn't exist"); Arbiter memory curMiner = existingArbiters[minerId]; for(uint256 i = 0; i<curMiner.arbiterVoteIds.length; i++) { uint256 voteId = curMiner.arbiterVoteIds[i]; ArbiterVote memory currentVote = arbVotes[voteId]; if (currentVote.state == VoteState.PENDING_VOTE) { return voteId; } } return 0; } //////// //INTERNAL HELPER FUNCTIONS //////// //arbitors don't get paid until the end of the arbitration is appealed or function payArbs (ArbitrationJob memory currentJob) internal { uint256 beeTokenPaymentForArbitration = currentJob.beeTokensArbitrationFee.mul(activeMinerPayPercentage) / 100; beeTokenPaymentForArbitration = beeTokenPaymentForArbitration/currentJob.arbiterVoteIds.length; for (uint256 i=0; i < currentJob.arbiterVoteIds.length; i++) { ArbiterVote storage currentVote = arbVotes[currentJob.arbiterVoteIds[i]]; //storage cuz we are gonna mark as paid after require(currentVote.state != VoteState.VOTE_PAID, "vote already paid"); currentVote.state = VoteState.VOTE_PAID; uint256 minerId = currentVote.arbiterId; Arbiter memory curMiner = existingArbiters[minerId]; require(beeToken.transfer(curMiner.minerAddress, beeTokenPaymentForArbitration), "err transfering to arbiter for voting"); emit ArbiterPaid(minerId, currentVote.vote, beeTokenPaymentForArbitration, now); } } /** * @dev creates a job * -functionhash- unknown yet * @param paymentId The Id that all the booking info is under * @param disputedBeeTokens How many bee tokens are under dispute * @param host The host eth wallet address * @param guest The guest eth wallet address * @param arbitrationId If the job came from an appeal, the arbitrationId of the original job */ function createJob(bytes32 paymentId, uint256 disputedBeeTokens, address host, address guest, uint256 arbitrationId) internal { uint256 arbitrationFee = normArbFee; //check to see if we have enough bee tokens in the wallet to do as promised uint256 totalPromisedBeeTokens = arbitrationFee.add(disputedBeeTokens); for (uint i=0; i<arbitrationJobs.length; i++) { // do something totalPromisedBeeTokens.add(arbitrationJobs[i].beeTokensArbitrationFee); } require (beeToken.balanceOf(address(this)) >= totalPromisedBeeTokens, "not enough bee tokens in contract to do job"); //require (disputedBeeTokens > surgeArbFee); //make sure they have enough to pay for surge plus triggerman TODO: figure out triggerman cost sub norm arb cost uint256 timeRquested = now; uint256 curArbId = arbitrationJobs.length; ArbitrationJob memory currentJob = ArbitrationJob({ arbitrationId:arbitrationId, paymentId:paymentId, timestamp:timeRquested, minMinerTime:timeRquested.add(minMinerTime), maxMinerTime:timeRquested.add(minMinerTime).add(maxMinerTime), appealTimelimit:0, beeTokensArbitrationFee:arbitrationFee, arbiterVoteIds:new uint256[](arbitersPerJob), disputedAmountOfBeeTokens:disputedBeeTokens, host:host, guest:guest }); arbitrationJobs.push(currentJob); addVotesToJob(arbitrationJobs[curArbId], curArbId); paymentIdToJobIds[paymentId].push(curArbId); //put into arbitration queue jobsInProgress.push(curArbId); emit ArbRequested(arbitrationId, paymentId, timeRquested, timeRquested.add(minMinerTime), timeRquested.add(maxMinerTime), disputedBeeTokens, arbitrationFee); } /** * @dev add votes to job * -functionhash- unknown yet * @param currentJob The arbitration job we are adding votes to * @param currentJobId The Id of the arbitrationJob */ function addVotesToJob(ArbitrationJob storage currentJob, uint256 currentJobId) internal { for (uint256 currentJobVoteIndex=0; currentJobVoteIndex<arbitersPerJob; currentJobVoteIndex++) { assignVote(currentJob, currentJobId, currentJobVoteIndex); } } /** * @dev crate vote at location index of job and replace old vote that was there if there was an old vote * -functionhash- unknown yet * @param currentJob The arbitration job we are adding votes to * @param currentJobId The Id of the arbitrationJob * @param currentJobVoteIndex The index of the vote in the aribtration job vote array we are modifying */ function assignVote(ArbitrationJob storage currentJob, uint256 currentJobId, uint256 currentJobVoteIndex) internal { ArbiterVote memory addVote = ArbiterVote({ state:VoteState.NOT_ASSIGNED_TO_ARBITER, arbitrationJobId:currentJobId, vote:0, arbiterId:0 }); uint256 voteIndex = arbVotes.push(addVote)-1; currentJob.arbiterVoteIds[currentJobVoteIndex] = voteIndex; } /** * @dev Internal function. it removes an element from an array stored on * the blockchain without keeping order at a O(1) efficency * -functionhash- unknown yet * @param index The index of the array we are removing * @param arr The array we are modifying */ function removeIndexFromArray (uint256 index, uint256 [] storage arr) internal { //maybe make a memory version of this for functions that loaded everything into memory so it cost less gas require(index < arr.length, "index doesn't exist in array"); uint lastIndex = arr.length.sub(1); arr[index] = arr[lastIndex]; delete arr[lastIndex]; arr.length = lastIndex; } /** * @dev Internal function. it removes a miner from the mining queue * -functionhash- unknown yet * @param index The index of the array we are removing */ function removeMinerFromQueue (uint256 index) internal { //maybe make a memory version of this for functions that loaded everything into memory so it cost less gas require(index >= 1, "can't remove dummy miner"); require(index < arbitersMining.length, "index doens't exist in mining queue"); uint lastIndex = arbitersMining.length.sub(1); arbitersMining[index] = arbitersMining[lastIndex]; Arbiter storage curMiner = existingArbiters[arbitersMining[lastIndex].miningId]; curMiner.miningArrayIndex = index; delete arbitersMining[lastIndex]; arbitersMining.length = lastIndex; } /** * @dev penalize arbitors for not voting by taking some of their stake and * taking them off the mining queue * * -functionhash- unknown yet * @param currentJob The arbitration job we are searching through for non voters * @param currentJobId The arbitration job id that corrasponds to the arbitration job we passed in */ function penalizeArbitersForNotVoting (ArbitrationJob storage currentJob, uint256 currentJobId) internal { uint256 [] memory jobVotes = currentJob.arbiterVoteIds; uint256 beeTokenTaken = 0; //trim non voters out and keep the ones who voted for (uint256 currentJobIndex = 0; currentJobIndex<jobVotes.length; currentJobIndex++) { if (jobVotes[currentJobIndex] != 0 && arbVotes[jobVotes[currentJobIndex]].state == VoteState.PENDING_VOTE) { //keep votes that happened beeTokenTaken += penalizeArbiter(jobVotes[currentJobIndex]); //replace bad vote slot in job with blank job to fill with a miner at a later date assignVote(currentJob, currentJobId, currentJobIndex); } } beeTokenTaken = beeTokenTaken.mul(percentPenTokensToFee) / 100; //calculate what is added to fee currentJob.beeTokensArbitrationFee += beeTokenTaken; } /** * @dev selected miners from the mining pool to become Arbitors * * -functionhash- unknown yet * @param currentJob The arbitration job we are selecting miners for * @param arbId The arbitration job id that corrasponds to the arbitration job we passed in */ function selectArbitersFromMiners (ArbitrationJob storage currentJob, uint256 arbId) internal { uint256 [] memory voteIds = currentJob.arbiterVoteIds; MinerTicketHolder [] memory curTickets = arbitersMining; //make copy in memory //for arbieters that haven't voted, make them not vote again for this job for (uint256 j = 0 ;j<voteIds.length; j++) { ArbiterVote memory checkVote = arbVotes[voteIds[j]]; if (checkVote.state == VoteState.VOTE_COMPLETE) { uint256 lottoIndex = existingArbiters[checkVote.arbiterId].miningArrayIndex; curTickets[lottoIndex].numLottoTickets = 0; //take away mining tickets for existing arbiter } } for (uint256 i = 0 ;i<voteIds.length; i++) { ArbiterVote storage currentVote = arbVotes[voteIds[i]]; if (currentVote.state == VoteState.PENALIZED_NO_VOTE || currentVote.state == VoteState.NOT_ASSIGNED_TO_ARBITER) { uint256 arbiterId = selectArbiter(curTickets); require (arbiterId >0, "can't be the dummy miner..."); uint256 miningArrayIndex = existingArbiters[arbiterId].miningArrayIndex; curTickets[miningArrayIndex].numLottoTickets = 0; //take away mining tickets for existing arbiter if (currentVote.state == VoteState.PENALIZED_NO_VOTE) { ArbiterVote memory addVote = ArbiterVote({ state:VoteState.PENDING_VOTE, arbitrationJobId:arbId, vote:0, arbiterId:arbiterId }); uint256 voteIndex = arbVotes.push(addVote)-1; //replace new vote with old bad vote voteIds[i] = voteIndex; //push vote id to miner so they know they got a job to do existingArbiters[arbiterId].arbiterVoteIds.push(voteIndex); } else if (currentVote.state == VoteState.NOT_ASSIGNED_TO_ARBITER) { //assgin to arbiter if not assigned yet currentVote.state = VoteState.PENDING_VOTE; currentVote.arbiterId = arbiterId; //push vote id to miner so they know they got a job to do existingArbiters[arbiterId].arbiterVoteIds.push(voteIds[i]); } } } currentJob.arbiterVoteIds = voteIds; //save new voter ids. optimization so we don't read a ton of times from storage } /** * @dev needed to pay triggermen for doing any triggers * * -functionhash- unknown yet * @param pathCompleted The path we took in our triggering * @param currentJob The arbitration job we helped by triggering an event */ function payTriggerman (uint256 pathCompleted, ArbitrationJob storage currentJob) internal { //triggerman always pays himself uint256 beeTokenPaymentForTrigger = triggermanPayBeeTokenAmount[pathCompleted]; currentJob.beeTokensArbitrationFee = currentJob.beeTokensArbitrationFee.sub(beeTokenPaymentForTrigger); require(beeToken.transfer(msg.sender, beeTokenPaymentForTrigger), "error paying / transfering to triggerman"); } /** * @dev figures out how much to pay everyone then pays them. * * -functionhash- unknown yet * @param currentJob The job we are refunding the host / guest from */ function abideByFinalVoteOfArbs (ArbitrationJob memory currentJob, uint256 arbitraionJobId) internal { uint256 totalPercent = 0; for (uint256 j=0; j < currentJob.arbiterVoteIds.length; j++) { ArbiterVote memory currentVote = arbVotes[currentJob.arbiterVoteIds[j]]; totalPercent += percentDisputedChoices[currentVote.vote]; } uint256 medianPercent = totalPercent / currentJob.arbiterVoteIds.length; uint256 beeTokenForHost = currentJob.disputedAmountOfBeeTokens.mul(medianPercent)/100; require(beeToken.transfer(currentJob.host, beeTokenForHost), "err transfering to host"); uint256 beeTokenForGuest = currentJob.disputedAmountOfBeeTokens. sub(beeTokenForHost); require(beeToken.transfer(currentJob.guest, beeTokenForGuest), "err transfering to guest"); emit ArbCompleted(arbitraionJobId, medianPercent, currentJob.paymentId, now); } /** * @dev internal helper function to penalize arbiters for missing a vote * -functionhash- unknown yet * @param voteId The id of the vote that didn't get completed by the end time */ function penalizeArbiter(uint256 voteId) internal returns (uint256) { ArbiterVote storage currentVote = arbVotes[voteId]; require (currentVote.state == VoteState.PENDING_VOTE, "arbiter not in pending vote state, can't penalize"); Arbiter storage curMiner = existingArbiters[currentVote.arbiterId]; uint256 beeTokenTaken = (curMiner.currentBeeTokenStake).mul(beeTokenPenality) / 100; uint256 salvagedBeeTokens = curMiner.currentBeeTokenStake.sub(beeTokenTaken); if (salvagedBeeTokens > 0) { require(beeToken.transfer(curMiner.minerAddress, salvagedBeeTokens), "err transfering bee from bad arbiter");//take bee tokens from Arbiter } emit ArbiterPenalized(currentVote.arbiterId, voteId, beeTokenTaken,curMiner.currentBeeTokenStake, now); currentVote.state = VoteState.PENALIZED_NO_VOTE; curMiner.currentBeeTokenStake = 0; removeMinerFromQueue(curMiner.miningArrayIndex); //remove miner from mining because they didn't do their job //select one more Arbiter return beeTokenTaken; } /** * @dev internal function that helps select one arbiter * -functionhash- unknown yet * @param curTickets A memory copy of all miners modified to set tickets to 0 where we blacklisted. * A miner can't be picked twice for the same job */ function selectArbiter(MinerTicketHolder [] memory curTickets) internal returns (uint256) //returns arbiter id of winner { //get number of total tickets uint256 numTicketsOut = 0; for (uint256 i=0; i < curTickets.length; i++) { numTicketsOut = numTicketsOut.add(curTickets[i].numLottoTickets); } require (numTicketsOut > 2, "needs to have at least 2 tickets avalible to init a vote");//needs to be at least 2 tickets avalible uint256 winningLottoTicket = getRandomNumber(1, numTicketsOut); uint256 winningMinerIndex = 0; uint256 curLottoTicket = curTickets[winningMinerIndex].numLottoTickets; while(curLottoTicket < winningLottoTicket) { winningMinerIndex = winningMinerIndex.add(1); //winner not found, try next index curLottoTicket = curLottoTicket.add(curTickets[winningMinerIndex].numLottoTickets); } return curTickets[winningMinerIndex].miningId; } /** * @dev our random number generator, need to check how expensive it is to * call, might just use less info to generate the random number. stolen * from fomo3d game, LOL, lots of stuff stolen from their open source. * They got skillz for being one of the best teams, their code is solId * -functionhash- unknown yet * @param min The min amount that we want * @param max The max amount that we want to go up to (non inclusive) */ function getRandomNumber (uint256 min, uint256 max) internal returns (uint256) { nonce = (nonce+1)%255; //this might overflow and cause thrown mining requests uint256 rawRand = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number).add(nonce) ))); return (rawRand%(max-min))+min; } /** * @dev registers a mininer, but puts them in a approval needed state * the contract owner needs to review all of the pending miners and * approve them * -functionhash- unknown yet */ function registerNewUser() internal returns (uint256) { uint256 minerId = existingArbiters.length; Arbiter memory curMiner = Arbiter({ accessState:ArbiterAccessState.PENDING_APPROVAL, minerAddress:msg.sender, currentBeeTokenStake:0, arbitrationsCompleted:0, arbitrationsAppealed:0, miningArrayIndex:0, arbiterVoteIds:new uint256[](0) }); existingArbiters.push(curMiner); addressToMinerId[msg.sender] = minerId; return minerId; } }
arbitors don't get paid until the end of the arbitration is appealed or
{ uint256 beeTokenPaymentForArbitration = currentJob.beeTokensArbitrationFee.mul(activeMinerPayPercentage) / 100; beeTokenPaymentForArbitration = beeTokenPaymentForArbitration/currentJob.arbiterVoteIds.length; function payArbs (ArbitrationJob memory currentJob) internal for (uint256 i=0; i < currentJob.arbiterVoteIds.length; i++) { require(currentVote.state != VoteState.VOTE_PAID, "vote already paid"); currentVote.state = VoteState.VOTE_PAID; uint256 minerId = currentVote.arbiterId; Arbiter memory curMiner = existingArbiters[minerId]; require(beeToken.transfer(curMiner.minerAddress, beeTokenPaymentForArbitration), "err transfering to arbiter for voting"); emit ArbiterPaid(minerId, currentVote.vote, beeTokenPaymentForArbitration, now); } }
1,841,580
[ 1, 297, 3682, 1383, 2727, 1404, 336, 30591, 3180, 326, 679, 434, 326, 10056, 7034, 353, 7226, 18931, 578, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 2254, 5034, 27203, 1345, 6032, 1290, 686, 3682, 7034, 273, 783, 2278, 18, 70, 1340, 5157, 686, 3682, 7034, 14667, 18, 16411, 12, 3535, 2930, 264, 9148, 16397, 13, 342, 2130, 31, 203, 3639, 27203, 1345, 6032, 1290, 686, 3682, 7034, 273, 27203, 1345, 6032, 1290, 686, 3682, 7034, 19, 2972, 2278, 18, 6779, 2165, 19338, 2673, 18, 2469, 31, 203, 5411, 203, 203, 565, 445, 8843, 686, 2038, 261, 686, 3682, 7034, 2278, 3778, 783, 2278, 13, 7010, 3639, 2713, 203, 3639, 364, 261, 11890, 5034, 277, 33, 20, 31, 277, 411, 783, 2278, 18, 6779, 2165, 19338, 2673, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2583, 12, 2972, 19338, 18, 2019, 480, 27540, 1119, 18, 16169, 1448, 67, 4066, 734, 16, 315, 25911, 1818, 30591, 8863, 203, 5411, 783, 19338, 18, 2019, 273, 27540, 1119, 18, 16169, 1448, 67, 4066, 734, 31, 203, 5411, 2254, 5034, 1131, 264, 548, 273, 783, 19338, 18, 6779, 2165, 548, 31, 203, 5411, 1201, 70, 2165, 3778, 662, 2930, 264, 273, 2062, 686, 3682, 414, 63, 1154, 264, 548, 15533, 203, 5411, 2583, 12, 70, 1340, 1345, 18, 13866, 12, 1397, 2930, 264, 18, 1154, 264, 1887, 16, 27203, 1345, 6032, 1290, 686, 3682, 7034, 3631, 315, 370, 7412, 310, 358, 419, 70, 2165, 364, 331, 17128, 8863, 203, 540, 203, 2398, 203, 5411, 3626, 1201, 70, 2165, 16507, 350, 12, 1154, 264, 548, 16, 783, 19338, 18, 25911, 16, 27203, 1345, 6032, 1290, 686, 3682, 7034, 16, 2037, 1769, 203, 2 ]
// Specifies the version of Solidity, using semantic versioning. // Learn more: https://solidity.readthedocs.io/en/v0.5.10/layout-of-source-files.html#pragma pragma solidity ^0.5.2; // Defines a contract named `HelloWorld`. // A contract is a collection of functions and data (its state). // Once deployed, a contract resides at a specific address on the Ethereum blockchain. // Learn more: https://solidity.readthedocs.io/en/v0.5.10/structure-of-a-contract.html contract HelloWorld { // Declares a state variable `message` of type `string`. // State variables are variables whose values are permanently stored in contract storage. // The keyword `public` makes variables accessible from outside a contract // and creates a function that other contracts or clients can call to access the value. string public message; // Similar to many class-based object-oriented languages, a constructor is // a special function that is only executed upon contract creation. // Constructors are used to initialize the contract's data. // Learn more: https://solidity.readthedocs.io/en/v0.5.10/contracts.html#constructors constructor(string memory initMessage) public { // Accepts a string argument `initMessage` and sets the value // into the contract's `message` storage variable). message = initMessage; } // A public function that accepts a string argument // and updates the `message` storage variable. function update(string memory newMessage) public { message = newMessage; } }
Accepts a string argument `initMessage` and sets the value into the contract's `message` storage variable).
constructor(string memory initMessage) public { message = initMessage; }
923,832
[ 1, 26391, 279, 533, 1237, 1375, 2738, 1079, 68, 471, 1678, 326, 460, 1368, 326, 6835, 1807, 1375, 2150, 68, 2502, 2190, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 1080, 3778, 1208, 1079, 13, 1071, 288, 203, 3639, 883, 273, 1208, 1079, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x7296333e1615721f4Bd9Df1a3070537484A50CF8/sources/Pool.sol
/* @title Pool: Claim Tokens Based on a Pricing Function/ Larger the scale, lower the output for a claim Max percentage for a claim with infinite score Mapping of tree root to boolean to enable claims Mapping of tree root to account to mark as claimed
contract Pool is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 internal constant MAX_PERCENTAGE = 100; uint256 internal constant MAX_SCALE = 77; uint256 public scale; uint256 public max; mapping(bytes32 => bool) public roots; mapping(bytes32 => mapping(address => bool)) public claimed; event Enable(bytes32 root); event Withdraw( bytes32[] roots, address account, IERC20 token, uint256 amount ); event SetScale(uint256 scale); event SetMax(uint256 max); event DrainTo(IERC20[] tokens, address dest); Copyright 2020 Swap Holdings Ltd. struct Claim { bytes32 root; uint256 score; bytes32[] proof; } constructor(uint256 _scale, uint256 _max) public { require(_max <= MAX_PERCENTAGE, "MAX_TOO_HIGH"); require(_scale <= MAX_SCALE, "SCALE_TOO_HIGH"); scale = _scale; max = _max; } function enable(bytes32 root) external onlyOwner { require(roots[root] == false, "ROOT_EXISTS"); roots[root] = true; emit Enable(root); } function withdraw(Claim[] memory claims, IERC20 token) external { require(claims.length > 0, "CLAIMS_MUST_BE_PROVIDED"); uint256 totalScore = 0; bytes32[] memory rootList = new bytes32[](claims.length); Claim memory claim; for (uint256 i = 0; i < claims.length; i++) { claim = claims[i]; require(roots[claim.root], "ROOT_NOT_ENABLED"); require(!claimed[claim.root][msg.sender], "CLAIM_ALREADY_MADE"); require( verify(msg.sender, claim.root, claim.score, claim.proof), "PROOF_INVALID" ); totalScore = totalScore.add(claim.score); claimed[claim.root][msg.sender] = true; rootList[i] = claim.root; } uint256 amount = calculate(totalScore, token); token.safeTransfer(msg.sender, amount); emit Withdraw(rootList, msg.sender, token, amount); } function withdraw(Claim[] memory claims, IERC20 token) external { require(claims.length > 0, "CLAIMS_MUST_BE_PROVIDED"); uint256 totalScore = 0; bytes32[] memory rootList = new bytes32[](claims.length); Claim memory claim; for (uint256 i = 0; i < claims.length; i++) { claim = claims[i]; require(roots[claim.root], "ROOT_NOT_ENABLED"); require(!claimed[claim.root][msg.sender], "CLAIM_ALREADY_MADE"); require( verify(msg.sender, claim.root, claim.score, claim.proof), "PROOF_INVALID" ); totalScore = totalScore.add(claim.score); claimed[claim.root][msg.sender] = true; rootList[i] = claim.root; } uint256 amount = calculate(totalScore, token); token.safeTransfer(msg.sender, amount); emit Withdraw(rootList, msg.sender, token, amount); } function calculate(uint256 score, IERC20 token) public view returns (uint256 amount) { uint256 balance = token.balanceOf(address(this)); uint256 divisor = (uint256(10)**scale).add(score); return max.mul(score).mul(balance).div(divisor).div(100); } function calculateMultiple(uint256 score, IERC20[] calldata tokens) external view returns (uint256[] memory outputAmounts) { outputAmounts = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { uint256 output = calculate(score, tokens[i]); outputAmounts[i] = output; } } function calculateMultiple(uint256 score, IERC20[] calldata tokens) external view returns (uint256[] memory outputAmounts) { outputAmounts = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { uint256 output = calculate(score, tokens[i]); outputAmounts[i] = output; } } function verify( address participant, bytes32 root, uint256 score, bytes32[] memory proof ) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(participant, score)); return MerkleProof.verify(proof, root, leaf); } function setScale(uint256 _scale) external onlyOwner { require(_scale <= MAX_SCALE, "SCALE_TOO_HIGH"); scale = _scale; emit SetScale(scale); } function setMax(uint256 _max) external onlyOwner { require(_max <= MAX_PERCENTAGE, "MAX_TOO_HIGH"); max = _max; emit SetMax(max); } function drainTo(IERC20[] calldata tokens, address dest) external onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { uint256 bal = tokens[i].balanceOf(address(this)); tokens[i].safeTransfer(dest, bal); } emit DrainTo(tokens, dest); } function drainTo(IERC20[] calldata tokens, address dest) external onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { uint256 bal = tokens[i].balanceOf(address(this)); tokens[i].safeTransfer(dest, bal); } emit DrainTo(tokens, dest); } }
4,384,334
[ 1, 19, 225, 8828, 30, 18381, 13899, 25935, 603, 279, 453, 1512, 310, 4284, 19, 16236, 693, 326, 3159, 16, 2612, 326, 876, 364, 279, 7516, 4238, 11622, 364, 279, 7516, 598, 14853, 4462, 9408, 434, 2151, 1365, 358, 1250, 358, 4237, 11955, 9408, 434, 2151, 1365, 358, 2236, 358, 2267, 487, 7516, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 8828, 353, 14223, 6914, 288, 203, 225, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 225, 2254, 5034, 2713, 5381, 4552, 67, 3194, 19666, 2833, 273, 2130, 31, 203, 225, 2254, 5034, 2713, 5381, 4552, 67, 19378, 273, 28244, 31, 203, 225, 2254, 5034, 1071, 3159, 31, 203, 225, 2254, 5034, 1071, 943, 31, 203, 225, 2874, 12, 3890, 1578, 516, 1426, 13, 1071, 12876, 31, 203, 225, 2874, 12, 3890, 1578, 516, 2874, 12, 2867, 516, 1426, 3719, 1071, 7516, 329, 31, 203, 225, 871, 9677, 12, 3890, 1578, 1365, 1769, 203, 225, 871, 3423, 9446, 12, 203, 565, 1731, 1578, 8526, 12876, 16, 203, 565, 1758, 2236, 16, 203, 565, 467, 654, 39, 3462, 1147, 16, 203, 565, 2254, 5034, 3844, 203, 225, 11272, 203, 225, 871, 1000, 5587, 12, 11890, 5034, 3159, 1769, 203, 225, 871, 28113, 12, 11890, 5034, 943, 1769, 203, 225, 871, 463, 7596, 774, 12, 45, 654, 39, 3462, 8526, 2430, 16, 1758, 1570, 1769, 203, 225, 25417, 26599, 20, 12738, 670, 1673, 899, 511, 4465, 18, 203, 225, 1958, 18381, 288, 203, 565, 1731, 1578, 1365, 31, 203, 565, 2254, 5034, 4462, 31, 203, 565, 1731, 1578, 8526, 14601, 31, 203, 225, 289, 203, 203, 225, 3885, 12, 11890, 5034, 389, 5864, 16, 2254, 5034, 389, 1896, 13, 1071, 288, 203, 565, 2583, 24899, 1896, 1648, 4552, 67, 3194, 19666, 2833, 16, 315, 6694, 67, 4296, 51, 67, 29996, 8863, 203, 565, 2 ]
//Address: 0x8eb965ee9ccfbce76c0a06264492c0afefc2826d //Contract name: ToorToken //Balance: 0 Ether //Verification Date: 6/13/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract ToorToken is ERC20Basic, Ownable { using SafeMath for uint256; struct Account { uint balance; uint lastInterval; } mapping(address => Account) public accounts; mapping(uint256 => uint256) ratesByYear; mapping (address => mapping (address => uint256)) internal allowed; uint256 private rateMultiplier; uint256 initialSupply_; uint256 totalSupply_; uint256 public maxSupply; uint256 public startTime; uint256 public pendingRewardsToMint; string public name; uint public decimals; string public symbol; uint256 private tokenGenInterval; // This defines the frequency at which we calculate rewards uint256 private vestingPeriod; // Defines how often tokens vest to team uint256 private cliff; // Defines the minimum amount of time required before tokens vest uint256 public pendingInstallments; // Defines the number of pending vesting installments for team uint256 public paidInstallments; // Defines the number of paid vesting installments for team uint256 private totalVestingPool; // Defines total vesting pool set aside for team uint256 public pendingVestingPool; // Defines pending tokens in pool set aside for team uint256 public finalIntervalForTokenGen; // The last instance of reward calculation, after which rewards will cease uint256 private totalRateWindows; // This specifies the number of rate windows over the total period of time uint256 private intervalsPerWindow; // Total number of times we calculate rewards within 1 rate window // Variable to define once reward generation is complete bool public rewardGenerationComplete; // Ether addresses of founders and company mapping(uint256 => address) public distributionAddresses; // Events section event Mint(address indexed to, uint256 amount); event Burn(address indexed burner, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function ToorToken() public { name = "ToorCoin"; decimals = 18; symbol = "TOOR"; // Setup the token staking reward percentage per year rateMultiplier = 10**9; ratesByYear[1] = 1.00474436 * 10**9; ratesByYear[2] = 1.003278088 * 10**9; ratesByYear[3] = 1.002799842 * 10**9; ratesByYear[4] = 1.002443535 * 10**9; ratesByYear[5] = 1.002167763 * 10**9; ratesByYear[6] = 1.001947972 * 10**9; ratesByYear[7] = 1.001768676 * 10**9; ratesByYear[8] = 1.001619621 * 10**9; ratesByYear[9] = 1.001493749 * 10**9; ratesByYear[10] = 1.001386038 * 10**9; ratesByYear[11] = 1.001292822 * 10**9; ratesByYear[12] = 1.001211358 * 10**9; ratesByYear[13] = 1.001139554 * 10**9; ratesByYear[14] = 1.001075789 * 10**9; ratesByYear[15] = 1.001018783 * 10**9; ratesByYear[16] = 1.000967516 * 10**9; ratesByYear[17] = 1.000921162 * 10**9; ratesByYear[18] = 1.000879048 * 10**9; ratesByYear[19] = 1.000840616 * 10**9; ratesByYear[20] = 1.000805405 * 10**9; totalRateWindows = 20; maxSupply = 100000000 * 10**18; initialSupply_ = 13500000 * 10**18; pendingInstallments = 7; paidInstallments = 0; totalVestingPool = 4500000 * 10**18; startTime = now; distributionAddresses[1] = 0x7d3BC9bb69dAB0544d34b7302DED8806bCF715e6; // founder 1 distributionAddresses[2] = 0x34Cf9afae3f926B9D040CA7A279C411355c5C480; // founder 2 distributionAddresses[3] = 0x059Cbd8A57b1dD944Da020a0D0a18D8dD7e78E04; // founder 3 distributionAddresses[4] = 0x4F8bC705827Fb8A781b27B9F02d2491F531f8962; // founder 4 distributionAddresses[5] = 0x532d370a98a478714625E9148D1205be061Df3bf; // founder 5 distributionAddresses[6] = 0xDe485bB000fA57e73197eF709960Fb7e32e0380E; // company distributionAddresses[7] = 0xd562f635c75D2d7f3BE0005FBd3808a5cfb896bd; // bounty // This is for 20 years tokenGenInterval = 603936; // This is roughly 1 week in seconds uint256 timeToGenAllTokens = 628093440; // This is close to 20 years in seconds rewardGenerationComplete = false; // Mint initial tokens accounts[distributionAddresses[6]].balance = (initialSupply_ * 60) / 100; // 60% of initial balance goes to Company accounts[distributionAddresses[6]].lastInterval = 0; generateMintEvents(distributionAddresses[6],accounts[distributionAddresses[6]].balance); accounts[distributionAddresses[7]].balance = (initialSupply_ * 40) / 100; // 40% of inital balance goes to Bounty accounts[distributionAddresses[7]].lastInterval = 0; generateMintEvents(distributionAddresses[7],accounts[distributionAddresses[7]].balance); pendingVestingPool = totalVestingPool; pendingRewardsToMint = maxSupply - initialSupply_ - totalVestingPool; totalSupply_ = initialSupply_; vestingPeriod = timeToGenAllTokens / (totalRateWindows * 12); // One vesting period is a month cliff = vestingPeriod * 6; // Cliff is six vesting periods aka 6 months roughly finalIntervalForTokenGen = timeToGenAllTokens / tokenGenInterval; intervalsPerWindow = finalIntervalForTokenGen / totalRateWindows; } // This gives the total supply of actual minted coins. Does not take rewards pending minting into consideration function totalSupply() public view returns (uint256) { return totalSupply_; } // This function is called directly by users who wish to transfer tokens function transfer(address _to, uint256 _value) canTransfer(_to) public returns (bool) { // Call underlying transfer method and pass in the sender address transferBasic(msg.sender, _to, _value); return true; } // This function is called by both transfer and transferFrom function transferBasic(address _from, address _to, uint256 _value) internal { uint256 tokensOwedSender = 0; uint256 tokensOwedReceiver = 0; uint256 balSender = balanceOfBasic(_from); // Distribute rewards tokens first if (!rewardGenerationComplete) { tokensOwedSender = tokensOwed(_from); require(_value <= (balSender.add(tokensOwedSender))); // Sender should have the number of tokens they want to send tokensOwedReceiver = tokensOwed(_to); // If there were tokens owed, increase total supply accordingly if ((tokensOwedSender.add(tokensOwedReceiver)) > 0) { increaseTotalSupply(tokensOwedSender.add(tokensOwedReceiver)); // This will break if total exceeds max cap pendingRewardsToMint = pendingRewardsToMint.sub(tokensOwedSender.add(tokensOwedReceiver)); } // If there were tokens owed, raise mint events for them raiseEventIfMinted(_from, tokensOwedSender); raiseEventIfMinted(_to, tokensOwedReceiver); } else { require(_value <= balSender); } // Update balances of sender and receiver accounts[_from].balance = (balSender.add(tokensOwedSender)).sub(_value); accounts[_to].balance = (accounts[_to].balance.add(tokensOwedReceiver)).add(_value); // Update last intervals for sender and receiver uint256 currInt = intervalAtTime(now); accounts[_from].lastInterval = currInt; accounts[_to].lastInterval = currInt; emit Transfer(_from, _to, _value); } // If you want to transfer tokens to multiple receivers at once function batchTransfer(address[] _receivers, uint256 _value) public returns (bool) { uint256 cnt = _receivers.length; uint256 amount = cnt.mul(_value); // Check that the value to send is more than 0 require(_value > 0); // Add pending rewards for sender first if (!rewardGenerationComplete) { addReward(msg.sender); } // Get current balance of sender uint256 balSender = balanceOfBasic(msg.sender); // Check that the sender has the required amount require(balSender >= amount); // Update balance and lastInterval of sender accounts[msg.sender].balance = balSender.sub(amount); uint256 currInt = intervalAtTime(now); accounts[msg.sender].lastInterval = currInt; for (uint i = 0; i < cnt; i++) { // Add pending rewards for receiver first if (!rewardGenerationComplete) { address receiver = _receivers[i]; addReward(receiver); } // Update balance and lastInterval of receiver accounts[_receivers[i]].balance = (accounts[_receivers[i]].balance).add(_value); accounts[_receivers[i]].lastInterval = currInt; emit Transfer(msg.sender, _receivers[i], _value); } return true; } // This function allows someone to withdraw tokens from someone's address // For this to work, the person needs to have been approved by the account owner (via the approve function) function transferFrom(address _from, address _to, uint256 _value) canTransfer(_to) public returns (bool) { // Check that function caller has been approved to withdraw tokens require(_value <= allowed[_from][msg.sender]); // Call out base transfer method transferBasic(_from, _to, _value); // Subtract withdrawn tokens from allowance allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } // Increase the amount of tokens that an owner allowed to a spender. // approve should be called when allowed[_spender] == 0. To increment // allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // Decrease the amount of tokens that an owner allowed to a spender. // approve should be called when allowed[_spender] == 0. To decrement // allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function raiseEventIfMinted(address owner, uint256 tokensToReward) private returns (bool) { if (tokensToReward > 0) { generateMintEvents(owner, tokensToReward); } } function addReward(address owner) private returns (bool) { uint256 tokensToReward = tokensOwed(owner); if (tokensToReward > 0) { increaseTotalSupply(tokensToReward); // This will break if total supply exceeds max cap. Should never happen though as tokensOwed checks for this condition accounts[owner].balance = accounts[owner].balance.add(tokensToReward); accounts[owner].lastInterval = intervalAtTime(now); pendingRewardsToMint = pendingRewardsToMint.sub(tokensToReward); // This helps track rounding errors when computing rewards generateMintEvents(owner, tokensToReward); } return true; } // This function is to vest tokens to the founding team // This deliberately doesn't use SafeMath as all the values are controlled without risk of overflow function vestTokens() public returns (bool) { require(pendingInstallments > 0); require(paidInstallments < 7); require(pendingVestingPool > 0); require(now - startTime > cliff); // If they have rewards pending, allocate those first if (!rewardGenerationComplete) { for (uint256 i = 1; i <= 5; i++) { addReward(distributionAddresses[i]); } } uint256 currInterval = intervalAtTime(now); uint256 tokensToVest = 0; uint256 totalTokensToVest = 0; uint256 totalPool = totalVestingPool; uint256[2] memory founderCat; founderCat[0] = 0; founderCat[1] = 0; uint256[5] memory origFounderBal; origFounderBal[0] = accounts[distributionAddresses[1]].balance; origFounderBal[1] = accounts[distributionAddresses[2]].balance; origFounderBal[2] = accounts[distributionAddresses[3]].balance; origFounderBal[3] = accounts[distributionAddresses[4]].balance; origFounderBal[4] = accounts[distributionAddresses[5]].balance; uint256[2] memory rewardCat; rewardCat[0] = 0; rewardCat[1] = 0; // Pay out cliff if (paidInstallments < 1) { uint256 intervalAtCliff = intervalAtTime(cliff + startTime); tokensToVest = totalPool / 4; founderCat[0] = tokensToVest / 4; founderCat[1] = tokensToVest / 8; // Update vesting pool pendingVestingPool -= tokensToVest; // This condition checks if there are any rewards to pay after the cliff if (currInterval > intervalAtCliff && !rewardGenerationComplete) { rewardCat[0] = tokensOwedByInterval(founderCat[0], intervalAtCliff, currInterval); rewardCat[1] = rewardCat[0] / 2; // Add rewards to founder tokens being vested founderCat[0] += rewardCat[0]; founderCat[1] += rewardCat[1]; // Increase total amount of tokens to vest tokensToVest += ((3 * rewardCat[0]) + (2 * rewardCat[1])); // Reduce pending rewards pendingRewardsToMint -= ((3 * rewardCat[0]) + (2 * rewardCat[1])); } // Vest tokens for each of the founders, this includes any rewards pending since cliff passed accounts[distributionAddresses[1]].balance += founderCat[0]; accounts[distributionAddresses[2]].balance += founderCat[0]; accounts[distributionAddresses[3]].balance += founderCat[0]; accounts[distributionAddresses[4]].balance += founderCat[1]; accounts[distributionAddresses[5]].balance += founderCat[1]; totalTokensToVest = tokensToVest; // Update pending and paid installments pendingInstallments -= 1; paidInstallments += 1; } // Calculate the pending non-cliff installments to pay based on current time uint256 installments = ((currInterval * tokenGenInterval) - cliff) / vestingPeriod; uint256 installmentsToPay = installments + 1 - paidInstallments; // If there are no installments to pay, skip this if (installmentsToPay > 0) { if (installmentsToPay > pendingInstallments) { installmentsToPay = pendingInstallments; } // 12.5% vesting monthly after the cliff tokensToVest = (totalPool * 125) / 1000; founderCat[0] = tokensToVest / 4; founderCat[1] = tokensToVest / 8; uint256 intervalsAtVest = 0; // Loop through installments to pay, so that we can add token holding rewards as we go along for (uint256 installment = paidInstallments; installment < (installmentsToPay + paidInstallments); installment++) { intervalsAtVest = intervalAtTime(cliff + (installment * vestingPeriod) + startTime); // This condition checks if there are any rewards to pay after the cliff if (currInterval >= intervalsAtVest && !rewardGenerationComplete) { rewardCat[0] = tokensOwedByInterval(founderCat[0], intervalsAtVest, currInterval); rewardCat[1] = rewardCat[0] / 2; // Increase total amount of tokens to vest totalTokensToVest += tokensToVest; totalTokensToVest += ((3 * rewardCat[0]) + (2 * rewardCat[1])); // Reduce pending rewards pendingRewardsToMint -= ((3 * rewardCat[0]) + (2 * rewardCat[1])); // Vest tokens for each of the founders, this includes any rewards pending since vest interval passed accounts[distributionAddresses[1]].balance += (founderCat[0] + rewardCat[0]); accounts[distributionAddresses[2]].balance += (founderCat[0] + rewardCat[0]); accounts[distributionAddresses[3]].balance += (founderCat[0] + rewardCat[0]); accounts[distributionAddresses[4]].balance += (founderCat[1] + rewardCat[1]); accounts[distributionAddresses[5]].balance += (founderCat[1] + rewardCat[1]); } } // Reduce pendingVestingPool and update pending and paid installments pendingVestingPool -= (installmentsToPay * tokensToVest); pendingInstallments -= installmentsToPay; paidInstallments += installmentsToPay; } // Increase total supply by the number of tokens being vested increaseTotalSupply(totalTokensToVest); accounts[distributionAddresses[1]].lastInterval = currInterval; accounts[distributionAddresses[2]].lastInterval = currInterval; accounts[distributionAddresses[3]].lastInterval = currInterval; accounts[distributionAddresses[4]].lastInterval = currInterval; accounts[distributionAddresses[5]].lastInterval = currInterval; // Create events for token generation generateMintEvents(distributionAddresses[1], (accounts[distributionAddresses[1]].balance - origFounderBal[0])); generateMintEvents(distributionAddresses[2], (accounts[distributionAddresses[2]].balance - origFounderBal[1])); generateMintEvents(distributionAddresses[3], (accounts[distributionAddresses[3]].balance - origFounderBal[2])); generateMintEvents(distributionAddresses[4], (accounts[distributionAddresses[4]].balance - origFounderBal[3])); generateMintEvents(distributionAddresses[5], (accounts[distributionAddresses[5]].balance - origFounderBal[4])); } function increaseTotalSupply (uint256 tokens) private returns (bool) { require ((totalSupply_.add(tokens)) <= maxSupply); totalSupply_ = totalSupply_.add(tokens); return true; } function tokensOwed(address owner) public view returns (uint256) { // This array is introduced to circumvent stack depth issues uint256 currInterval = intervalAtTime(now); uint256 lastInterval = accounts[owner].lastInterval; uint256 balance = accounts[owner].balance; return tokensOwedByInterval(balance, lastInterval, currInterval); } function tokensOwedByInterval(uint256 balance, uint256 lastInterval, uint256 currInterval) public view returns (uint256) { // Once the specified address has received all possible rewards, don't calculate anything if (lastInterval >= currInterval || lastInterval >= finalIntervalForTokenGen) { return 0; } uint256 tokensHeld = balance; //tokensHeld uint256 intPerWin = intervalsPerWindow; uint256 totalRateWinds = totalRateWindows; // Defines the number of intervals we compute rewards for at a time uint256 intPerBatch = 5; // Hardcoded here instead of storing on blockchain to save gas mapping(uint256 => uint256) ratByYear = ratesByYear; uint256 ratMultiplier = rateMultiplier; uint256 minRateWindow = (lastInterval / intPerWin).add(1); uint256 maxRateWindow = (currInterval / intPerWin).add(1); if (maxRateWindow > totalRateWinds) { maxRateWindow = totalRateWinds; } // Loop through pending periods of rewards, and calculate the total balance user should hold for (uint256 rateWindow = minRateWindow; rateWindow <= maxRateWindow; rateWindow++) { uint256 intervals = getIntervalsForWindow(rateWindow, lastInterval, currInterval, intPerWin); // This part is to ensure we don't overflow when rewards are pending for a large number of intervals // Loop through interval in batches while (intervals > 0) { if (intervals >= intPerBatch) { tokensHeld = (tokensHeld.mul(ratByYear[rateWindow] ** intPerBatch)) / (ratMultiplier ** intPerBatch); intervals = intervals.sub(intPerBatch); } else { tokensHeld = (tokensHeld.mul(ratByYear[rateWindow] ** intervals)) / (ratMultiplier ** intervals); intervals = 0; } } } // Rewards owed are the total balance that user SHOULD have minus what they currently have return (tokensHeld.sub(balance)); } function intervalAtTime(uint256 time) public view returns (uint256) { // Check to see that time passed in is not before contract generation time, as that would cause a negative value in the next step if (time <= startTime) { return 0; } // Based on time passed in, check how many intervals have elapsed uint256 interval = (time.sub(startTime)) / tokenGenInterval; uint256 finalInt = finalIntervalForTokenGen; // Assign to local to reduce gas // Return max intervals if it's greater than that time if (interval > finalInt) { return finalInt; } else { return interval; } } // This function checks how many intervals for a given window do we owe tokens to someone for function getIntervalsForWindow(uint256 rateWindow, uint256 lastInterval, uint256 currInterval, uint256 intPerWind) public pure returns (uint256) { // If lastInterval for holder falls in a window previous to current one, the lastInterval for the window passed into the function would be the window start interval if (lastInterval < ((rateWindow.sub(1)).mul(intPerWind))) { lastInterval = ((rateWindow.sub(1)).mul(intPerWind)); } // If currentInterval for holder falls in a window higher than current one, the currentInterval for the window passed into the function would be the window end interval if (currInterval > rateWindow.mul(intPerWind)) { currInterval = rateWindow.mul(intPerWind); } return currInterval.sub(lastInterval); } // This function tells the balance of tokens at a particular address function balanceOf(address _owner) public view returns (uint256 balance) { if (rewardGenerationComplete) { return accounts[_owner].balance; } else { return (accounts[_owner].balance).add(tokensOwed(_owner)); } } function balanceOfBasic(address _owner) public view returns (uint256 balance) { return accounts[_owner].balance; } // This functions returns the last time at which rewards were transferred to a particular address function lastTimeOf(address _owner) public view returns (uint256 interval, uint256 time) { return (accounts[_owner].lastInterval, ((accounts[_owner].lastInterval).mul(tokenGenInterval)).add(startTime)); } // This function is not meant to be used. It's only written as a fail-safe against potential unforeseen issues function mint(address _to, uint256 _amount) onlyOwner public returns (bool) { // Add pending rewards for recipient of minted tokens if (!rewardGenerationComplete) { addReward(_to); } // Increase total supply by minted amount increaseTotalSupply(_amount); // Update balance and last interval accounts[_to].lastInterval = intervalAtTime(now); accounts[_to].balance = (accounts[_to].balance).add(_amount); generateMintEvents(_to, _amount); return true; } function generateMintEvents(address _to, uint256 _amount) private returns (bool) { emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } // Allows the burning of tokens function burn(uint256 _value) public { require(_value <= balanceOf(msg.sender)); // First add any rewards pending for the person burning tokens if (!rewardGenerationComplete) { addReward(msg.sender); } // Update balance and lastInterval of person burning tokens accounts[msg.sender].balance = (accounts[msg.sender].balance).sub(_value); accounts[msg.sender].lastInterval = intervalAtTime(now); // Update total supply totalSupply_ = totalSupply_.sub(_value); // Raise events emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); } // These set of functions allow changing of founder and company addresses function setFounder(uint256 id, address _to) onlyOwner public returns (bool) { require(_to != address(0)); distributionAddresses[id] = _to; return true; } // This is a setter for rewardGenerationComplete. It will be used to see if token rewards need to be computed, and can only be set by owner function setRewardGenerationComplete(bool _value) onlyOwner public returns (bool) { rewardGenerationComplete = _value; return true; } // This function is added to get a state of where the token is in term of reward generation function getNow() public view returns (uint256, uint256, uint256) { return (now, block.number, intervalAtTime(now)); } // This modifier is used on the transfer method and defines where tokens CANNOT be sent modifier canTransfer(address _to) { require(_to != address(0)); // Transfer should not be allowed to burn tokens _; } }
Update last intervals for sender and receiver
uint256 currInt = intervalAtTime(now);
1,005,514
[ 1, 1891, 1142, 10389, 364, 5793, 471, 5971, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 4306, 1702, 273, 3673, 861, 950, 12, 3338, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x1B0eD927c605f4CBc9065ac330dC0E009070Ce7D/sources/StakingRewardsStore.sol
* @dev returns the rewards data of a specific reserve in a specific pool @param poolToken the pool token representing the rewards pool @param reserveToken the reserve token in the rewards pool @return rewards data/
function poolRewards(IDSToken poolToken, IERC20Token reserveToken) external view override returns ( uint256, uint256, uint256 ) { PoolRewards memory data = _poolRewards[poolToken][reserveToken]; return (data.lastUpdateTime, data.rewardPerToken, data.totalClaimedRewards); }
5,325,937
[ 1, 6154, 326, 283, 6397, 501, 434, 279, 2923, 20501, 316, 279, 2923, 2845, 225, 2845, 1345, 326, 2845, 1147, 5123, 326, 283, 6397, 2845, 225, 20501, 1345, 326, 20501, 1147, 316, 326, 283, 6397, 2845, 327, 283, 6397, 501, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2845, 17631, 14727, 12, 734, 882, 969, 2845, 1345, 16, 467, 654, 39, 3462, 1345, 20501, 1345, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 16, 203, 5411, 2254, 5034, 16, 203, 5411, 2254, 5034, 203, 3639, 262, 203, 565, 288, 203, 3639, 8828, 17631, 14727, 3778, 501, 273, 389, 6011, 17631, 14727, 63, 6011, 1345, 6362, 455, 6527, 1345, 15533, 203, 203, 3639, 327, 261, 892, 18, 2722, 1891, 950, 16, 501, 18, 266, 2913, 2173, 1345, 16, 501, 18, 4963, 9762, 329, 17631, 14727, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x995D37D9B5630f5b768Fc1cca21F7F5046069420/sources/HarryPotterObamaSonic888InuAllFuckedYoMommaToken.sol
Denominator Limits will be disabled prior to ownership renounce
contract HarryPotterObamaSonic888InuAllFuckedYoMommaToken is ERC20, Ownable { mapping(address => bool) public noFee; mapping(address => bool) public noWalletLimit; mapping(address => bool) public noTransactionLimit; bool public launched = false; bool public limitsEnabled = true; bool public feesEnabled = true; uint256 public feeDenominator = 10000; uint256 public initialBuyFeeNumerator = 3000; uint256 public initialSellFeeNumerator = 3000; uint256 public finalBuyFeeNumerator = 200; uint256 public finalSellFeeNumerator = 200; uint256 public buyFeeNumerator; uint256 public sellFeeNumerator; uint256 public supply = 1_000_000_000 * 10**decimals(); uint256 public maxTxnAmount = supply / 100; uint256 public maxWalletAmount = supply / 100; uint256 public swapFeeTokensAtAmount = supply / 10000; address public feeRecipient = address(0x072C8fD59Abf4e667477B82dccc5f6E83Dd44F57); address public liquidationAMM; address public weth; IRouter public router; uint256 private startTradingBlockNumber; bool private inFeeLiquidation = false; constructor( address routerAddress ) Ownable() ERC20( unicode"HarryPotterObamaSonic888InuAllFuckedYoMomma", unicode"DOGE" receive() external payable {} function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } ) { _mint(address(this), supply); router = IRouter(routerAddress); weth = router.WETH(); liquidationAMM = IV2Factory( router.factory() ).createPair( address(this), weth ); noWalletLimit[liquidationAMM] = true; _approve(address(this), address(router), type(uint256).max); } function setNoWalletLimit(address account, bool hasNoLimit) external onlyOwner { require(noWalletLimit[account] != hasNoLimit, "No limit address state already set"); noWalletLimit[account] = hasNoLimit; } function setNoTransactionLimit(address account, bool hasNoLimit) external onlyOwner { require(noWalletLimit[account] != hasNoLimit, "No limit address state already set"); noWalletLimit[account] = hasNoLimit; } function setNoFee(address account, bool hasNoFee) external onlyOwner { require(noFee[account] != hasNoFee, "No fee address state already set"); noFee[account] = hasNoFee; } function setFeeRecipient(address feeRecipient_) external onlyOwner { feeRecipient = feeRecipient_; } function disableLimits() public onlyOwner { require(limitsEnabled); limitsEnabled = false; } function setFees(uint256 _buyFeeNumerator, uint256 _sellFeeNumerator) public onlyOwner { require(_buyFeeNumerator <= buyFeeNumerator && _sellFeeNumerator <= sellFeeNumerator); buyFeeNumerator = _buyFeeNumerator; sellFeeNumerator = _sellFeeNumerator; if (buyFeeNumerator + sellFeeNumerator == 0) { feesEnabled = false; } } function setFees(uint256 _buyFeeNumerator, uint256 _sellFeeNumerator) public onlyOwner { require(_buyFeeNumerator <= buyFeeNumerator && _sellFeeNumerator <= sellFeeNumerator); buyFeeNumerator = _buyFeeNumerator; sellFeeNumerator = _sellFeeNumerator; if (buyFeeNumerator + sellFeeNumerator == 0) { feesEnabled = false; } } function withdrawStuckTokens(address tokenAddress, uint256 amount) external { require(tokenAddress != address(this)); uint256 tokenBalance = IERC20(tokenAddress).balanceOf(address(this)); uint256 amountToTransfer = amount == 0 ? tokenBalance : amount; IERC20(tokenAddress).transfer(feeRecipient, amountToTransfer); } function withdrawStuckETH() external { require(success); } (bool success,) = feeRecipient.call{value: address(this).balance}(""); function renounceOwnership() public override onlyOwner { setFees(finalBuyFeeNumerator, finalSellFeeNumerator); if (limitsEnabled) { disableLimits(); } super.renounceOwnership(); } function renounceOwnership() public override onlyOwner { setFees(finalBuyFeeNumerator, finalSellFeeNumerator); if (limitsEnabled) { disableLimits(); } super.renounceOwnership(); } function _transfer(address from, address to, uint256 amount) internal override { if (amount == 0 || inFeeLiquidation || !launched || noFee[from] || noFee[to]) { super._transfer(from, to, amount); return; } if (to == liquidationAMM) { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > swapFeeTokensAtAmount) { inFeeLiquidation = true; swapTokensForEth(contractBalance); inFeeLiquidation = false; } if (address(this).balance > 0) { } if (feesEnabled) { uint256 feeAmount = amount * sellFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } } if (from == liquidationAMM && feesEnabled) { uint256 feeAmount = amount * buyFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } if (limitsEnabled) { if (!noTransactionLimit[from]) { require(amount <= maxTxnAmount); } if (!noWalletLimit[to]) { require(amount + balanceOf(to) <= maxWalletAmount); } require(block.number >= startTradingBlockNumber); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { if (amount == 0 || inFeeLiquidation || !launched || noFee[from] || noFee[to]) { super._transfer(from, to, amount); return; } if (to == liquidationAMM) { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > swapFeeTokensAtAmount) { inFeeLiquidation = true; swapTokensForEth(contractBalance); inFeeLiquidation = false; } if (address(this).balance > 0) { } if (feesEnabled) { uint256 feeAmount = amount * sellFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } } if (from == liquidationAMM && feesEnabled) { uint256 feeAmount = amount * buyFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } if (limitsEnabled) { if (!noTransactionLimit[from]) { require(amount <= maxTxnAmount); } if (!noWalletLimit[to]) { require(amount + balanceOf(to) <= maxWalletAmount); } require(block.number >= startTradingBlockNumber); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { if (amount == 0 || inFeeLiquidation || !launched || noFee[from] || noFee[to]) { super._transfer(from, to, amount); return; } if (to == liquidationAMM) { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > swapFeeTokensAtAmount) { inFeeLiquidation = true; swapTokensForEth(contractBalance); inFeeLiquidation = false; } if (address(this).balance > 0) { } if (feesEnabled) { uint256 feeAmount = amount * sellFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } } if (from == liquidationAMM && feesEnabled) { uint256 feeAmount = amount * buyFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } if (limitsEnabled) { if (!noTransactionLimit[from]) { require(amount <= maxTxnAmount); } if (!noWalletLimit[to]) { require(amount + balanceOf(to) <= maxWalletAmount); } require(block.number >= startTradingBlockNumber); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { if (amount == 0 || inFeeLiquidation || !launched || noFee[from] || noFee[to]) { super._transfer(from, to, amount); return; } if (to == liquidationAMM) { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > swapFeeTokensAtAmount) { inFeeLiquidation = true; swapTokensForEth(contractBalance); inFeeLiquidation = false; } if (address(this).balance > 0) { } if (feesEnabled) { uint256 feeAmount = amount * sellFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } } if (from == liquidationAMM && feesEnabled) { uint256 feeAmount = amount * buyFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } if (limitsEnabled) { if (!noTransactionLimit[from]) { require(amount <= maxTxnAmount); } if (!noWalletLimit[to]) { require(amount + balanceOf(to) <= maxWalletAmount); } require(block.number >= startTradingBlockNumber); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { if (amount == 0 || inFeeLiquidation || !launched || noFee[from] || noFee[to]) { super._transfer(from, to, amount); return; } if (to == liquidationAMM) { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > swapFeeTokensAtAmount) { inFeeLiquidation = true; swapTokensForEth(contractBalance); inFeeLiquidation = false; } if (address(this).balance > 0) { } if (feesEnabled) { uint256 feeAmount = amount * sellFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } } if (from == liquidationAMM && feesEnabled) { uint256 feeAmount = amount * buyFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } if (limitsEnabled) { if (!noTransactionLimit[from]) { require(amount <= maxTxnAmount); } if (!noWalletLimit[to]) { require(amount + balanceOf(to) <= maxWalletAmount); } require(block.number >= startTradingBlockNumber); } super._transfer(from, to, amount); } (bool success,) = feeRecipient.call{value: address(this).balance}(""); function _transfer(address from, address to, uint256 amount) internal override { if (amount == 0 || inFeeLiquidation || !launched || noFee[from] || noFee[to]) { super._transfer(from, to, amount); return; } if (to == liquidationAMM) { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > swapFeeTokensAtAmount) { inFeeLiquidation = true; swapTokensForEth(contractBalance); inFeeLiquidation = false; } if (address(this).balance > 0) { } if (feesEnabled) { uint256 feeAmount = amount * sellFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } } if (from == liquidationAMM && feesEnabled) { uint256 feeAmount = amount * buyFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } if (limitsEnabled) { if (!noTransactionLimit[from]) { require(amount <= maxTxnAmount); } if (!noWalletLimit[to]) { require(amount + balanceOf(to) <= maxWalletAmount); } require(block.number >= startTradingBlockNumber); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { if (amount == 0 || inFeeLiquidation || !launched || noFee[from] || noFee[to]) { super._transfer(from, to, amount); return; } if (to == liquidationAMM) { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > swapFeeTokensAtAmount) { inFeeLiquidation = true; swapTokensForEth(contractBalance); inFeeLiquidation = false; } if (address(this).balance > 0) { } if (feesEnabled) { uint256 feeAmount = amount * sellFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } } if (from == liquidationAMM && feesEnabled) { uint256 feeAmount = amount * buyFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } if (limitsEnabled) { if (!noTransactionLimit[from]) { require(amount <= maxTxnAmount); } if (!noWalletLimit[to]) { require(amount + balanceOf(to) <= maxWalletAmount); } require(block.number >= startTradingBlockNumber); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { if (amount == 0 || inFeeLiquidation || !launched || noFee[from] || noFee[to]) { super._transfer(from, to, amount); return; } if (to == liquidationAMM) { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > swapFeeTokensAtAmount) { inFeeLiquidation = true; swapTokensForEth(contractBalance); inFeeLiquidation = false; } if (address(this).balance > 0) { } if (feesEnabled) { uint256 feeAmount = amount * sellFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } } if (from == liquidationAMM && feesEnabled) { uint256 feeAmount = amount * buyFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } if (limitsEnabled) { if (!noTransactionLimit[from]) { require(amount <= maxTxnAmount); } if (!noWalletLimit[to]) { require(amount + balanceOf(to) <= maxWalletAmount); } require(block.number >= startTradingBlockNumber); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { if (amount == 0 || inFeeLiquidation || !launched || noFee[from] || noFee[to]) { super._transfer(from, to, amount); return; } if (to == liquidationAMM) { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > swapFeeTokensAtAmount) { inFeeLiquidation = true; swapTokensForEth(contractBalance); inFeeLiquidation = false; } if (address(this).balance > 0) { } if (feesEnabled) { uint256 feeAmount = amount * sellFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } } if (from == liquidationAMM && feesEnabled) { uint256 feeAmount = amount * buyFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } if (limitsEnabled) { if (!noTransactionLimit[from]) { require(amount <= maxTxnAmount); } if (!noWalletLimit[to]) { require(amount + balanceOf(to) <= maxWalletAmount); } require(block.number >= startTradingBlockNumber); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { if (amount == 0 || inFeeLiquidation || !launched || noFee[from] || noFee[to]) { super._transfer(from, to, amount); return; } if (to == liquidationAMM) { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > swapFeeTokensAtAmount) { inFeeLiquidation = true; swapTokensForEth(contractBalance); inFeeLiquidation = false; } if (address(this).balance > 0) { } if (feesEnabled) { uint256 feeAmount = amount * sellFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } } if (from == liquidationAMM && feesEnabled) { uint256 feeAmount = amount * buyFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } if (limitsEnabled) { if (!noTransactionLimit[from]) { require(amount <= maxTxnAmount); } if (!noWalletLimit[to]) { require(amount + balanceOf(to) <= maxWalletAmount); } require(block.number >= startTradingBlockNumber); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { if (amount == 0 || inFeeLiquidation || !launched || noFee[from] || noFee[to]) { super._transfer(from, to, amount); return; } if (to == liquidationAMM) { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > swapFeeTokensAtAmount) { inFeeLiquidation = true; swapTokensForEth(contractBalance); inFeeLiquidation = false; } if (address(this).balance > 0) { } if (feesEnabled) { uint256 feeAmount = amount * sellFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } } if (from == liquidationAMM && feesEnabled) { uint256 feeAmount = amount * buyFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } if (limitsEnabled) { if (!noTransactionLimit[from]) { require(amount <= maxTxnAmount); } if (!noWalletLimit[to]) { require(amount + balanceOf(to) <= maxWalletAmount); } require(block.number >= startTradingBlockNumber); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { if (amount == 0 || inFeeLiquidation || !launched || noFee[from] || noFee[to]) { super._transfer(from, to, amount); return; } if (to == liquidationAMM) { uint256 contractBalance = balanceOf(address(this)); if (contractBalance > swapFeeTokensAtAmount) { inFeeLiquidation = true; swapTokensForEth(contractBalance); inFeeLiquidation = false; } if (address(this).balance > 0) { } if (feesEnabled) { uint256 feeAmount = amount * sellFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } } if (from == liquidationAMM && feesEnabled) { uint256 feeAmount = amount * buyFeeNumerator / feeDenominator; if (feeAmount > 0) { amount = amount - feeAmount; super._transfer(from, address(this), feeAmount); } } if (limitsEnabled) { if (!noTransactionLimit[from]) { require(amount <= maxTxnAmount); } if (!noWalletLimit[to]) { require(amount + balanceOf(to) <= maxWalletAmount); } require(block.number >= startTradingBlockNumber); } super._transfer(from, to, amount); } function fuckYoMomma( uint256 blockDelay ) external payable onlyOwner { address(this), balanceOf(address(this)), 0, 0, feeRecipient, block.timestamp ); startTradingBlockNumber = block.number + blockDelay; buyFeeNumerator = initialBuyFeeNumerator; sellFeeNumerator = initialSellFeeNumerator; launched = true; } router.addLiquidityETH{value: address(this).balance}( function swapTokensForEth(uint256 tokenAmount) internal { address[] memory path = new address[](2); path[0] = address(this); path[1] = weth; router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } }
4,101,593
[ 1, 8517, 26721, 27240, 903, 506, 5673, 6432, 358, 23178, 1654, 8386, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 670, 297, 1176, 18411, 387, 10516, 20789, 55, 15506, 5482, 28, 382, 89, 1595, 42, 9031, 329, 61, 83, 49, 362, 2540, 1345, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 1158, 14667, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 1158, 16936, 3039, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 1158, 3342, 3039, 31, 203, 7010, 565, 1426, 1071, 28786, 10792, 273, 629, 31, 203, 565, 1426, 1071, 8181, 1526, 9079, 273, 638, 31, 203, 565, 1426, 1071, 1656, 281, 1526, 1171, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 14036, 8517, 26721, 6647, 273, 12619, 31, 203, 565, 2254, 5034, 1071, 2172, 38, 9835, 14667, 2578, 7385, 282, 273, 225, 29839, 31, 203, 565, 2254, 5034, 1071, 2172, 55, 1165, 14667, 2578, 7385, 225, 273, 225, 29839, 31, 203, 565, 2254, 5034, 1071, 727, 38, 9835, 14667, 2578, 7385, 377, 273, 282, 4044, 31, 203, 565, 2254, 5034, 1071, 727, 55, 1165, 14667, 2578, 7385, 565, 273, 282, 4044, 31, 203, 565, 2254, 5034, 1071, 30143, 14667, 2578, 7385, 31, 203, 565, 2254, 5034, 1071, 357, 80, 14667, 2578, 7385, 31, 203, 203, 565, 2254, 5034, 1071, 14467, 10402, 273, 404, 67, 3784, 67, 3784, 67, 3784, 380, 1728, 636, 31734, 5621, 203, 377, 203, 565, 2254, 5034, 1071, 943, 13789, 6275, 2398, 273, 14467, 342, 2130, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 6275, 1850, 273, 14467, 342, 2130, 31, 203, 203, 565, 2 ]
pragma solidity ^0.5.0; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@openzeppelin/contracts/lifecycle/Pausable.sol'; import '@openzeppelin/contracts/introspection/IERC165.sol'; import './TokenBuyInterface.sol'; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) public; function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; function mintLand(address to, uint256 OVRLandID) public returns (bool); } contract Ownable { address payable public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } constructor () internal { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } function transferOwnership(address payable _newOwner) public onlyOwner { require(_newOwner != address(0), "Ownable: new owner can't be the zero address"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /// The ICO contract to run auctions and buy OVRLands (ERC721) after winning in exchange for OVRTokens (ERC20) /// Also handles land sells and purchases for people that want to exchange their land once they got it contract ICO is Ownable, Pausable, IERC721Receiver { using SafeMath for uint256; // Default state is NOT_STARTED enum AuctionState { NOT_STARTED, ACTIVE, ENDED } enum LandOfferState { NOT_STARTED, ACTIVE, ACCEPTED, DECLINED, EXPIRED, CANCELLED } struct Land { address payable owner; uint256 landToBuy; uint256 paid; uint256 lastBidTimestamp; AuctionState state; uint256 cashbackAmount; bool isCashbackRedeemed; // Marketplace functionality uint256 sellPrice; bool onSale; bool hasBeenRedeemed; uint256 lastUpdateTimestamp; uint256 paidWith; uint256 amountToReturn; // How many tokens or eth to return if outbidded } struct LandOffer { uint256 id; // The unique land offer identifier address payable by; uint256 group; // Unique counter for group orders to desactive those after 1 has been approved uint256 landId; uint256 price; uint256 timestamp; uint256 expirationDate; LandOfferState state; } event WonLand(address indexed winner, uint256 indexed landId, uint256 price); event LandSaleStarted(address indexed owner, uint256 indexed landId, uint256 price); event CashbackRedeemed(uint256 indexed landId, address indexed receiver, uint256 amount, uint256 timestamp); // For lands that have been on sale but were removed by the owner event LandSaleCancelled(address indexed owner, uint256 indexed landId); event LandOfferCreated(uint256 indexed id, address indexed by, uint256 indexed landId, uint256 price, uint256 timestamp, uint256 expirationDate); event LandSold(uint256 indexed landId, address indexed oldOwner, address indexed buyer, uint256 price, uint256 timestamp); event LandOfferDeclined(uint256 indexed landOfferId, uint256 indexed landId); event LandOfferCancelled(uint256 indexed offerId); address public ovrToken; address public ovrLand; address public tokenBuy; address public approved; uint256 public initialLandBid; uint256 public lastLandOfferId; // A counter for setting up ids // When the contract was created required for calculating cashbacks uint256 public contractCreationDate; // LandID => Land mapping (uint256 => Land) public lands; // User => a list of owned land ids mapping (address => uint256[]) public ownedLands; // User => how many tokens he can cashback with redeemCashback() mapping (address => uint256) public cashbacks; // LandID => All the LandOffer IDS each landId has mapping (uint256 => uint256[]) public landOfferIds; // LandOfferId => LandOffer mapping (uint256 => LandOffer) public landOffers; // LandID => groupCounter mapping (uint256 => uint256) public groupCounters; // Lands that have initiated the auction process can be either active or ended uint256[] public activeLands; uint256 public auctionLandDuration = 24 hours; // Default 24 hours // Lands that are on sale or have been sold previously // This array is immutable meaning it won't delete already existing ids // because it's a very gas consuming process. // When a land is sold, the pointed Land id from `lands` is updated // There can be multiple instances of the same id inside so filter them in js uint256[] public landsOnSaleOrSold; modifier onlyApproved { require(msg.sender == approved); _; } constructor(address _ovrToken, address _ovrLand, address _tokenBuy, uint256 _initialLandBid) public { require(_ovrToken != address(0), "The OVR ERC20 token address can't be empty"); require(_ovrLand != address(0), "The OVR land ERC721 token address can't be empty"); require(_tokenBuy != address(0), "The TokenBuy contract address can't be empty"); require(_initialLandBid != 0, "The initial land bid can't be zero"); ovrToken = _ovrToken; ovrLand = _ovrLand; tokenBuy = _tokenBuy; initialLandBid = _initialLandBid; contractCreationDate = now; } function setApproved(address _approved) public onlyOwner { approved = _approved; } /// Sets the duration of each land auction function setAuctionLandDuration(uint256 _time) public onlyOwner { require(_time > 0, "The auction duration can't be zero"); auctionLandDuration = _time; } /// To redeem the land that you won in an auction function redeemWonLand(uint256 _landId) public whenNotPaused { Land storage land = lands[_landId]; if (now.sub(land.lastBidTimestamp) >= auctionLandDuration) { land.state = AuctionState.ENDED; } require(land.state == AuctionState.ENDED, "You can't redeem this land until its auction is finished"); require(land.owner == msg.sender, 'You must be the land winner to redeem it'); uint256 cashbackPercentage; uint256 monthPurchasedSinceBeginning = now.sub(contractCreationDate).div(30 days) + 1; if (monthPurchasedSinceBeginning == 1) { cashbackPercentage = 95; } else if (monthPurchasedSinceBeginning == 2) { cashbackPercentage = 85; } else if (monthPurchasedSinceBeginning == 3) { cashbackPercentage = 75; } else if (monthPurchasedSinceBeginning == 4) { cashbackPercentage = 65; } else if (monthPurchasedSinceBeginning == 5) { cashbackPercentage = 55; } else if (monthPurchasedSinceBeginning == 6) { cashbackPercentage = 45; } else if (monthPurchasedSinceBeginning == 7) { cashbackPercentage = 35; } else if (monthPurchasedSinceBeginning == 8) { cashbackPercentage = 25; } else if (monthPurchasedSinceBeginning == 9) { cashbackPercentage = 15; } else { cashbackPercentage = 0; } uint256 cashback = land.paid.mul(cashbackPercentage).div(100); cashbacks[msg.sender] = cashbacks[msg.sender].add(cashback); land.cashbackAmount = cashback; land.hasBeenRedeemed = true; // Transfer the land to the user IERC721(ovrLand).mintLand(msg.sender, _landId); ownedLands[msg.sender].push(_landId); emit WonLand(msg.sender, _landId, land.paid); } function redeemBulkLands(uint256[] memory _landIds) public whenNotPaused { for (uint256 i = 0; i < _landIds.length; i++) { redeemWonLand(_landIds[i]); } } /// To get your cashback for the buyers in the initial 9 months /// @param _landId The land whose cashback you want to get function redeemCashback(uint256 _landId) public whenNotPaused { Land storage land = lands[_landId]; require(!land.isCashbackRedeemed, 'The cashback has already been redeemed for this land'); require(land.hasBeenRedeemed, 'The land must be redeemed before getting its cashback'); require(land.owner == msg.sender, 'You must be the land owner to redeem its cashback'); require(now.sub(land.lastBidTimestamp) >= 30 days, "You can't redeem a cashback before 30 days"); uint256 tempAmount = land.cashbackAmount; cashbacks[msg.sender] = cashbacks[msg.sender].sub(land.cashbackAmount); land.isCashbackRedeemed = true; land.cashbackAmount = 0; IERC20(ovrToken).transfer(msg.sender, tempAmount); emit CashbackRedeemed(_landId, msg.sender, land.cashbackAmount, now); } /// To extract the tokens that may have been sent to this contract by accident function extractTokens(address _tokenToExtract, uint256 _amount) public onlyOwner whenNotPaused { IERC20(_tokenToExtract).transfer(owner, _amount); } function extractEth() public onlyOwner whenNotPaused { owner.transfer(address(this).balance); } /// To put on sell a land you own /// Note: the price can be 0 to give it away for free /// The seller must approve the ERC721 token to the ICO contract ONLY if _onSale is true /// @param _onSale To indicate whether you want to put it on sale or remove it from the sale function putLandOnSale(uint256 _landId, uint256 _price, bool _onSale) public whenNotPaused { Land storage land = lands[_landId]; require(msg.sender == land.owner, 'You must be the land owner to put it on sale'); require(land.state == AuctionState.ENDED, 'The land auction must have been completed to put it on sale'); if (_onSale) { address _approved = IERC721(ovrLand).getApproved(_landId); require(_approved == address(this), 'You must approve this contract to manage your ERC721 token'); } land.onSale = _onSale; land.sellPrice = _price; land.lastUpdateTimestamp = now; landsOnSaleOrSold.push(_landId); if (_onSale) { IERC721(ovrLand).safeTransferFrom(msg.sender, address(this), _landId); emit LandSaleStarted(land.owner, _landId, _price); } else { IERC721(ovrLand).safeTransferFrom(address(this), msg.sender, _landId); emit LandSaleCancelled(land.owner, _landId); } } /// To buy a land on sale /// The buyer must approve the land price in OVR tokens to purchase it beforehand function buyLand(uint256 _landId) public whenNotPaused { Land storage land = lands[_landId]; address oldOwner = land.owner; uint256 salePrice = land.sellPrice; uint256 allowance = IERC20(ovrToken).allowance(msg.sender, address(this)); require(land.onSale, 'The land must be on sale to buy it'); require(allowance >= land.sellPrice, 'You must approve the right amount of OVR tokens to buy this land'); require(land.state == AuctionState.ENDED, 'The land auction must have been completed to buy it'); land.owner = msg.sender; land.onSale = false; land.sellPrice = 0; land.lastUpdateTimestamp = now; IERC20(ovrToken).transferFrom(msg.sender, oldOwner, salePrice); IERC721(ovrLand).safeTransferFrom(address(this), msg.sender, _landId); emit LandSold(_landId, oldOwner, msg.sender, salePrice, now); } /// To offer someone to buy his land for a specific price /// it doesn't matter if the land is on sale or not, this offer will be sent regardless /// If the user already has an existing offer, override it with this new one /// The frontend will have to get all the offers and check those made by the same person to only keep /// the most recent one by looking at the timestamp function offerToBuyLand(uint256 _landId, uint256 _price, uint256 _expirationDate) public whenNotPaused { Land storage land = lands[_landId]; uint256 allowance = IERC20(ovrToken).allowance(msg.sender, address(this)); require(land.state == AuctionState.ENDED, 'The land auction must have been completed to send the offer to buy it'); require(allowance >= _price, 'You must approve the right amount of OVR tokens to offer to buy it'); require(_expirationDate > now, 'The expiration date must be larger than now'); lastLandOfferId++; LandOffer memory newOffer = LandOffer(lastLandOfferId, msg.sender, groupCounters[_landId], _landId, _price, now, _expirationDate, LandOfferState.ACTIVE); landOffers[lastLandOfferId] = newOffer; landOfferIds[_landId].push(lastLandOfferId); emit LandOfferCreated(lastLandOfferId, msg.sender, _landId, _price, now, _expirationDate); } /// To cancel buy offers function cancelBuyOffer(uint256 _offerId) public whenNotPaused { LandOffer storage offer = landOffers[_offerId]; require(msg.sender == offer.by, 'You must be the owner to cancel the buy offer'); offer.state = LandOfferState.CANCELLED; emit LandOfferCancelled(_offerId); } /// To respond to a buy land offer independently on whether your land is on sale or not /// kinda like ebay does it with the custom buy offers function respondToBuyOffer(uint256 _landOfferId, bool _accept) public whenNotPaused { LandOffer storage landOffer = landOffers[_landOfferId]; Land storage land = lands[landOffer.landId]; require(landOffer.state == LandOfferState.ACTIVE, 'The offer must be active to be able to respond to it'); require(landOffer.expirationDate > now, 'The offer is expired'); require(land.owner == msg.sender, 'You must be the owner to accept the land offer'); if (_accept) { address _approved = IERC721(ovrLand).getApproved(land.landToBuy); require(_approved == address(this), 'You must approve this contract to manage your ERC721 token'); emit LandSold(land.landToBuy, land.owner, landOffer.by, landOffer.price, now); IERC20(ovrToken).transferFrom(landOffer.by, land.owner, landOffer.price); IERC721(ovrLand).safeTransferFrom(land.owner, landOffer.by, land.landToBuy); landOffer.state = LandOfferState.ACCEPTED; land.owner = landOffer.by; land.onSale = false; land.sellPrice = 0; groupCounters[landOffer.landId]++; } else { landOffer.state = LandOfferState.DECLINED; emit LandOfferDeclined(_landOfferId, land.landToBuy); } } /// To update the lands value array function setLands( address payable owner, uint256 landToBuy, uint256 paid, AuctionState state, uint256 paidWith, uint256 amountToReturn ) public onlyApproved { lands[landToBuy] = Land(owner, landToBuy, paid, now, state, 0, false, 0, false, false, now, paidWith, amountToReturn); } function pushActiveLand(uint256 _landId) public onlyApproved { activeLands.push(_landId); } /// Returns an array with the the landOfferIds for a given land id /// you can check each independently using the array ownedLands function checkMyLandOffers(uint256 _landId) public view returns(uint256[] memory) { return landOfferIds[_landId]; } /// Returns the landIds you won so you know which landIds you can redeem function checkWonLands() public view returns(uint256[] memory) { uint256[] memory result; uint256 counter = 0; for(uint256 i = 0; i < activeLands.length; i++) { uint256 landId = activeLands[i]; if (lands[landId].state == AuctionState.ENDED && lands[landId].owner == msg.sender) { result[counter] = landId; counter = counter.add(1); } } return result; } /// Checks if the token you want to buy is within the epoch available /// @return bool True if it's in a valid epoch and false if not function checkEpoch(uint256 _landId) public view returns(bool) { uint256 currentMonth = now.sub(contractCreationDate).div(30) + 1; // Extract the last 2 digits uint256 landIdDigits = _landId % 100; if (currentMonth == 1) { if (landIdDigits <= 17) { return true; } else { return false; } } else if (currentMonth == 2) { if (landIdDigits > 17 && landIdDigits <= 35) { return true; } else { return false; } } else if (currentMonth == 3) { if (landIdDigits > 35 && landIdDigits <= 53) { return true; } else { return false; } } else if (currentMonth == 4) { if (landIdDigits > 53 && landIdDigits <= 70) { return true; } else { return false; } } else if (currentMonth == 5) { if (landIdDigits > 70 && landIdDigits <= 88) { return true; } else { return false; } } else if (currentMonth == 6) { if (landIdDigits > 88 && landIdDigits <= 99) { return true; } else { return false; } } return true; } function getActiveLands() public view returns(uint256[] memory) { return activeLands; } function getLandsOnSaleOrSold() public view returns(uint256[] memory) { return landsOnSaleOrSold; } function getLandOffers(uint256 _landId) public view returns(uint256[] memory) { return landOfferIds[_landId]; } function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4) { // Both return values work return this.onERC721Received.selector; // return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } } contract ICOParticipate is Ownable, Pausable { using SafeMath for uint256; event AuctionStarted(address indexed lastBidder, uint256 indexed landToBuy, uint256 paid, uint256 timestamp); event AuctionBid(address indexed newBidder, address indexed oldBidder, uint256 indexed landToBuy, uint256 paid, uint256 timestamp); address public ovrLand; address public tokenBuy; IERC20 public ovrToken; IERC20 public dai; IERC20 public usdt; IERC20 public usdc; uint256 public tokensPerUsd; uint256 public ethPrice; ICO public ico; constructor (address _ico) public { ico = ICO(_ico); ovrLand = ico.ovrLand(); tokenBuy = ico.tokenBuy(); ovrToken = IERC20(ico.ovrToken()); dai = IERC20(TokenBuyInterface(tokenBuy).daiToken()); usdt = IERC20(TokenBuyInterface(tokenBuy).usdtToken()); usdc = IERC20(TokenBuyInterface(tokenBuy).usdcToken()); updateTokenBuyValues(); } function updateTokenBuyValues() public { tokensPerUsd = TokenBuyInterface(tokenBuy).tokensPerUsd() / 2; ethPrice = TokenBuyInterface(tokenBuy).ethPrice(); } function participate (uint256 _token, uint256 _bid, uint256 _landId) public payable whenNotPaused { updateTokenBuyValues(); if (msg.value > 0) { uint256 calculatedBid = msg.value.mul(ethPrice).mul(tokensPerUsd) + 1; require(calculatedBid >= _bid, 'You must send more or equal the value of tokens to buy'); } require(ico.checkEpoch(_landId), "This land isn't available at the current epoch"); require(_bid > 0 || msg.value > 0, "The bid can't be zero"); (,,, uint256 lastBidTimestamp, ICO.AuctionState state,,,,,,,,) = ico.lands(_landId); if (state == ICO.AuctionState.NOT_STARTED) { require(_bid >= ico.initialLandBid(), 'The bid must be larger or equal the initial minimum'); participateNewAuction(_token, _bid, _landId); } else if (state == ICO.AuctionState.ACTIVE) { require(now.sub(lastBidTimestamp) < ico.auctionLandDuration(), 'This land auction has ended'); participateActiveAuction(_token, _bid, _landId); } else if (state == ICO.AuctionState.ENDED) { revert('The auction has ended for this land 1'); } else { revert('The auction has ended for this land 2'); } } function participateActiveAuction (uint256 _token, uint256 _bid, uint256 _landId) internal whenNotPaused { (address payable oldBidder,, uint256 oldBid,, ICO.AuctionState state,,,,,,, uint256 paidWith, uint256 amountToReturn) = ico.lands(_landId); require(_bid >= oldBid.mul(2), 'Your bid must be equal or larger than double the previous one'); // Transfer the new tokens if (_token == 1) { dai.transferFrom(msg.sender, address(this), _bid.div(tokensPerUsd)); } else if (_token == 2) { usdt.transferFrom(msg.sender, address(this), _bid.div(tokensPerUsd)); } else if (_token == 3) { usdc.transferFrom(msg.sender, address(this), _bid.div(tokensPerUsd)); } else if (_token == 4) { ovrToken.transferFrom(msg.sender, address(this), _bid); } if (paidWith == 0) { ico.setLands(msg.sender, _landId, _bid, state, _token, msg.value); } else { ico.setLands(msg.sender, _landId, _bid, state, _token, _bid.div(tokensPerUsd)); } // Return previous bidder's tokens if (paidWith == 0) { oldBidder.transfer(amountToReturn); } else if (paidWith == 1) { dai.transfer(oldBidder, amountToReturn); } else if (paidWith == 2) { usdt.transfer(oldBidder, amountToReturn); } else if (paidWith == 3) { usdc.transfer(oldBidder, amountToReturn); } else if (paidWith == 4) { ovrToken.transfer(oldBidder, oldBid); } emit AuctionBid(msg.sender, oldBidder, _landId, _bid, now); } function participateNewAuction (uint256 _token, uint256 _bid, uint256 _landId) internal whenNotPaused { if (_token == 0) { ico.setLands(msg.sender, _landId, _bid, ICO.AuctionState.ACTIVE, _token, msg.value); } else { ico.setLands(msg.sender, _landId, _bid, ICO.AuctionState.ACTIVE, _token, _bid.div(tokensPerUsd)); } if (_token == 1) { dai.transferFrom(msg.sender, address(this), _bid.div(tokensPerUsd)); } else if (_token == 2) { usdt.transferFrom(msg.sender, address(this), _bid.div(tokensPerUsd)); } else if (_token == 3) { usdc.transferFrom(msg.sender, address(this), _bid.div(tokensPerUsd)); } else if (_token == 4) { ovrToken.transferFrom(msg.sender, address(this), _bid); } ico.pushActiveLand(_landId); emit AuctionStarted(msg.sender, _landId, _bid, now); } /// To extract the tokens that may have been sent to this contract by accident function extractTokens(address _tokenToExtract, uint256 _amount) public onlyOwner whenNotPaused { IERC20(_tokenToExtract).transfer(owner, _amount); } function extractEth() public onlyOwner whenNotPaused { owner.transfer(address(this).balance); } }
To buy a land on sale The buyer must approve the land price in OVR tokens to purchase it beforehand
function buyLand(uint256 _landId) public whenNotPaused { Land storage land = lands[_landId]; address oldOwner = land.owner; uint256 salePrice = land.sellPrice; uint256 allowance = IERC20(ovrToken).allowance(msg.sender, address(this)); require(land.onSale, 'The land must be on sale to buy it'); require(allowance >= land.sellPrice, 'You must approve the right amount of OVR tokens to buy this land'); require(land.state == AuctionState.ENDED, 'The land auction must have been completed to buy it'); land.owner = msg.sender; land.onSale = false; land.sellPrice = 0; land.lastUpdateTimestamp = now; IERC20(ovrToken).transferFrom(msg.sender, oldOwner, salePrice); IERC721(ovrLand).safeTransferFrom(address(this), msg.sender, _landId); emit LandSold(_landId, oldOwner, msg.sender, salePrice, now); }
12,638,974
[ 1, 774, 30143, 279, 19193, 603, 272, 5349, 1021, 27037, 1297, 6617, 537, 326, 19193, 6205, 316, 531, 10986, 2430, 358, 23701, 518, 1865, 2349, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 29398, 12, 11890, 5034, 389, 15733, 548, 13, 1071, 1347, 1248, 28590, 288, 203, 3639, 511, 464, 2502, 19193, 273, 328, 5708, 63, 67, 15733, 548, 15533, 203, 3639, 1758, 1592, 5541, 273, 19193, 18, 8443, 31, 203, 3639, 2254, 5034, 272, 5349, 5147, 273, 19193, 18, 87, 1165, 5147, 31, 203, 3639, 2254, 5034, 1699, 1359, 273, 467, 654, 39, 3462, 12, 1527, 86, 1345, 2934, 5965, 1359, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 10019, 203, 3639, 2583, 12, 15733, 18, 265, 30746, 16, 296, 1986, 19193, 1297, 506, 603, 272, 5349, 358, 30143, 518, 8284, 203, 3639, 2583, 12, 5965, 1359, 1545, 19193, 18, 87, 1165, 5147, 16, 296, 6225, 1297, 6617, 537, 326, 2145, 3844, 434, 531, 10986, 2430, 358, 30143, 333, 19193, 8284, 203, 3639, 2583, 12, 15733, 18, 2019, 422, 432, 4062, 1119, 18, 22088, 16, 296, 1986, 19193, 279, 4062, 1297, 1240, 2118, 5951, 358, 30143, 518, 8284, 203, 3639, 19193, 18, 8443, 273, 1234, 18, 15330, 31, 203, 3639, 19193, 18, 265, 30746, 273, 629, 31, 203, 3639, 19193, 18, 87, 1165, 5147, 273, 374, 31, 203, 3639, 19193, 18, 2722, 1891, 4921, 273, 2037, 31, 203, 3639, 467, 654, 39, 3462, 12, 1527, 86, 1345, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1592, 5541, 16, 272, 5349, 5147, 1769, 203, 3639, 467, 654, 39, 27, 5340, 12, 1527, 86, 29398, 2934, 4626, 5912, 1265, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 16, 389, 15733, 548, 1769, 203, 3639, 3626, 2 ]
//Address: 0x94394EbE010332c5A40d946658779d26dA3aC92B //Contract name: LooksCoinCrowdSale //Balance: 0 Ether //Verification Date: 1/15/2018 //Transacion Count: 5 // CODE STARTS HERE pragma solidity ^0.4.19; /* * LooksCoin token sale contract * * Refer to https://lookrev.com/tokensale/ for more information. * * Developer: LookRev * */ /* * ERC20 Token Standard */ contract ERC20 { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); uint256 public totalSupply; function balanceOf(address _owner) constant public returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) constant public returns (uint256 remaining); } /** * Provides methods to safely add, subtract and multiply uint256 numbers. */ contract SafeMath { /** * Add two uint256 values, revert in case of overflow. * * @param a first value to add * @param b second value to add * @return a + b */ function safeAdd(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /** * Subtract one uint256 value from another, throw in case of underflow. * * @param a value to subtract from * @param b value to subtract * @return a - b */ function safeSub(uint256 a, uint256 b) internal returns (uint256) { assert(a >= b); return a - b; } /** * Multiply two uint256 values, throw in case of overflow. * * @param a first value to multiply * @param b second value to multiply * @return a * b */ function safeMul(uint256 a, uint256 b) internal returns (uint256) { if (a == 0 || b == 0) return 0; uint256 c = a * b; assert(c / a == b); return c; } /** * Divid uint256 values, throw in case of overflow. * * @param a first value numerator * @param b second value denominator * @return a / b */ function safeDiv(uint256 a, uint256 b) internal returns (uint256) { assert(b != 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } } /* Provides support and utilities for contract ownership */ contract Ownable { address owner; address newOwner; function Ownable() { owner = msg.sender; } /** * Allows execution by the owner only. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * Transferring the contract ownership to the new owner. * * @param _newOwner new contractor owner */ function transferOwnership(address _newOwner) onlyOwner { if (_newOwner != 0x0) { newOwner = _newOwner; } } /** * Accept the contract ownership by the new owner. * */ function acceptOwnership() { require(msg.sender == newOwner); owner = newOwner; OwnershipTransferred(owner, newOwner); newOwner = 0x0; } event OwnershipTransferred(address indexed _from, address indexed _to); } /** * Standard Token Smart Contract */ contract StandardToken is ERC20, SafeMath { /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) balances; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) internal allowed; /** * Mapping from addresses of token holders to the mapping of token amount spent. * Use by the token holders to spend their utility tokens. */ mapping (address => mapping (address => uint256)) spentamount; /** * Mapping of the addition of the addresse of buyers. */ mapping (address => bool) buyerAppended; /** * Mapping of the addition of addresses of buyers. */ address[] buyers; /** * Mapping of the addresses of VIP token holders. */ address[] vips; /** * Mapping for VIP rank for qualified token holders * Higher VIP ranking (with earlier timestamp) has higher bidding priority when * competing for the same product or service on platform. * Higher VIP ranking address can outbid other lower ranking addresses only once per * selling window or promotion period. * Usage of the VIP ranking and bid priority will be described on token website. */ mapping (address => uint256) viprank; /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer(address _to, uint256 _value) returns (bool success) { require(_to != 0x0); if (balances[msg.sender] < _value) return false; balances[msg.sender] = safeSub(balances[msg.sender],_value); balances[_to] = safeAdd(balances[_to],_value); Transfer(msg.sender, _to, _value); return true; } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(_to != 0x0); if(_from == _to) return false; if (balances[_from] < _value) return false; if (_value > allowed[_from][msg.sender]) return false; balances[_from] = safeSub(balances[_from],_value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_value); balances[_to] = safeAdd(balances[_to],_value); Transfer(_from, _to, _value); return true; } /** * Allow given spender to transfer given number of tokens from message sender. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve(address _spender, uint256 _value) returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { return false; } if (balances[msg.sender] < _value) { return false; } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * LooksCoin Token * * VIP ranking is recorded at the time when the token holding address first meet VIP coin * holding level. * VIP ranking is valid for the lifetime of a token wallet address, as long as it meets * VIP coin holding level. * VIP ranking is used to calculate priority when competing with other bids for the * same product or service on the platform. * Higher VIP ranking (with earlier timestamp) has higher priority. * Higher VIP ranking address can outbid other lower ranking wallet addresse owners only once * per selling window or promotion period. * Usage of the LooksCoin, VIP ranking and bid priority will be described on token website. * */ contract LooksCoin is StandardToken, Ownable { uint256 public constant decimals = 0; /** * Minimium contribution to record a VIP rank * Token holding address needs have at least 24000 LooksCoin to be ranked as VIP * VIP rank can only be set through purchasing tokens */ uint256 public constant VIP_MINIMUM = 24000; /** * Initial number of tokens. */ uint256 constant INITIAL_TOKENS_COUNT = 100000000; /** * Crowdsale contract address. */ address public tokenSaleContract = 0x0; /** * Init Placeholder */ address coinmaster = address(0x33169f40d18c6c2590901db23000D84052a11F54); /** * Create new LooksCoin token Smart Contract. * Contract is needed in _tokenSaleContract address. * * @param _tokenSaleContract of crowdsale contract * */ function LooksCoin(address _tokenSaleContract) { assert(_tokenSaleContract != 0x0); owner = coinmaster; tokenSaleContract = _tokenSaleContract; balances[owner] = INITIAL_TOKENS_COUNT; totalSupply = INITIAL_TOKENS_COUNT; } /** * Get name of this token. * * @return name of this token */ function name() constant returns (string name) { return "LooksCoin"; } /** * Get symbol of this token. * * @return symbol of this token */ function symbol() constant returns (string symbol) { return "LOOKS"; } /** * @dev Set new sale manage contract. * May only be called by owner. * * @param _newSaleManageContract new token sale manage contract. */ function setSaleManageContract(address _newSaleManageContract) { require(msg.sender == owner); assert(_newSaleManageContract != 0x0); tokenSaleContract = _newSaleManageContract; } /** * Get VIP rank of a given owner. * VIP ranking is valid for the lifetime of a token wallet address, * as long as it meets VIP holding level. * * @param _to participant address to get the vip rank * @return vip rank of the owner of given address */ function getVIPRank(address _to) constant public returns (uint256 rank) { if (balances[_to] < VIP_MINIMUM) { return 0; } return viprank[_to]; } /** * Check and update VIP rank of a given token buyer. * Contribution timestamp is recorded for VIP rank * Recorded timestamp for VIP ranking should always be earlier than the current time * * @param _to address to check the vip rank * @return rank vip rank of the owner of given address if any */ function updateVIPRank(address _to) returns (uint256 rank) { // Contribution timestamp is recorded for VIP rank // Recorded timestamp for VIP ranking should always be earlier than current time if (balances[_to] >= VIP_MINIMUM && viprank[_to] == 0) { viprank[_to] = now; vips.push(_to); } return viprank[_to]; } event TokenRewardsAdded(address indexed participant, uint256 balance); /** * Reward participant the tokens they purchased or earned * * @param _to address to credit tokens to the * @param _value number of tokens to transfer to given recipient * * @return true if tokens were transferred successfully, false otherwise */ function rewardTokens(address _to, uint256 _value) { require(msg.sender == tokenSaleContract || msg.sender == owner); assert(_to != 0x0); require(_value > 0); balances[_to] = safeAdd(balances[_to], _value); totalSupply = safeAdd(totalSupply, _value); updateVIPRank(_to); TokenRewardsAdded(_to, _value); } event SpentTokens(address indexed participant, address indexed recipient, uint256 amount); /** * Spend given number of tokens for a usage. * * @param _to address to spend utility tokens at * @param _value number of tokens to spend * @return true on success, false on error */ function spend(address _to, uint256 _value) public returns (bool success) { require(_value > 0); assert(_to != 0x0); if (balances[msg.sender] < _value) return false; balances[msg.sender] = safeSub(balances[msg.sender],_value); balances[_to] = safeAdd(balances[_to],_value); spentamount[msg.sender][_to] = safeAdd(spentamount[msg.sender][_to], _value); SpentTokens(msg.sender, _to, _value); if(!buyerAppended[msg.sender]) { buyerAppended[msg.sender] = true; buyers.push(msg.sender); } return true; } function getSpentAmount(address _who, address _to) constant returns (uint256) { return spentamount[_who][_to]; } event Burn(address indexed burner, uint256 value); /** * Burn given number of tokens belonging to message sender. * It can be applied by account with address this.tokensaleContract * * @param _value number of tokens to burn * @return true on success, false on error */ function burnTokens(address burner, uint256 _value) public returns (bool success) { require(msg.sender == burner || msg.sender == owner); assert(burner != 0x0); if (_value > totalSupply) return false; if (_value > balances[burner]) return false; balances[burner] = safeSub(balances[burner],_value); totalSupply = safeSub(totalSupply,_value); Burn(burner, _value); return true; } function getVIPOwner(uint256 index) constant returns (address) { return (vips[index]); } function getVIPCount() constant returns (uint256) { return vips.length; } function getBuyer(uint256 index) constant returns (address) { return (buyers[index]); } function getBuyersCount() constant returns (uint256) { return buyers.length; } } /** * LooksCoin CrowdSale Contract * * The token sale controller, allows contributing ether in exchange for LooksCoin. * The price (exchange rate with ETH) is 2400 LOOKS per ETH at crowdsale. * VIP ranking is recorded at the time when the token holding address first meet VIP coin holding level. * VIP ranking is valid for the lifetime of a token wallet address, as long as it meets VIP coin holding level. * VIP ranking is used to calculate priority when competing with other bids for the * same product or service on the platform. * Higher VIP ranking (with earlier timestamp) has higher priority. * Higher VIP ranking address can outbid other lower ranking addresses only once per selling window * or promotion period. * Usage of the LooksCoin, VIP ranking and bid priority will be described on token website. * * LooksCoin CrowdSale Bonus ******************************************************************************************************************* * First Ten (10) VIP token holders get 20% bonus of the LOOKS tokens in their VIP addresses * Eleven (11th) to Fifty (50th) VIP token holders get 10% bonus of the LOOKS tokens in their VIP addresses * Fifty One (51th) to One Hundred (100th) VIP token holders get 5% bonus of the LOOKS tokens in their VIP addresses ******************************************************************************************************************* * * Bonus tokens will be distributed by coin master when LooksCoin has 100 VIP rank token wallet addresses * */ contract LooksCoinCrowdSale { LooksCoin public looksCoin; ERC20 public preSaleToken; // initial price in wei (numerator) uint256 public constant TOKEN_PRICE_N = 1e18; // initial price in wei (denominator) uint256 public constant TOKEN_PRICE_D = 2400; // 1 ETH = 2,400 LOOKS tokens address saleController = 0x0; // Amount of imported tokens from preSale uint256 public importedTokens = 0; // Amount of tokens sold uint256 public tokensSold = 0; /** * Address of the owner of this smart contract. */ address fundstorage = 0x0; /** * States of the crowdsale contract. */ enum State{ Pause, Init, Running, Stopped, Migrated } State public currentState = State.Running; /** * Modifier. */ modifier onCrowdSaleRunning() { // Checks, if CrowdSale is running and has not been paused require(currentState == State.Running); _; } /** * Create new LOOKS token Smart Contract, make message sender to be the * owner of smart contract, issue given number of tokens and give them to * message sender. */ function LooksCoinCrowdSale() { saleController = msg.sender; fundstorage = msg.sender; looksCoin = new LooksCoin(this); preSaleToken = ERC20(0x253C7dd074f4BaCb305387F922225A4f737C08bd); } /** * @dev Set new state * @param _newState Value of new state */ function setState(State _newState) { require(msg.sender == saleController); currentState = _newState; } /** * @dev Set new token sale controller. * May only be called by sale controller. * * @param _newSaleController new token sale controller. */ function setSaleController(address _newSaleController) { require(msg.sender == saleController); assert(_newSaleController != 0x0); saleController = _newSaleController; } /** * Set new wallet address for the smart contract. * May only be called by smart contract owner. * * @param _fundstorage new wallet address of the smart contract */ function setWallet(address _fundstorage) { require(msg.sender == saleController); assert(_fundstorage != 0x0); fundstorage = _fundstorage; WalletUpdated(fundstorage); } event WalletUpdated(address newWallet); /** * saves info if account's tokens were imported from pre-CrowdSale */ mapping (address => bool) private importedFromPreSale; event TokensImport(address indexed participant, uint256 tokens, uint256 totalImport); /** * Imports account's tokens from pre-Sale. * It can be done only by account owner or CrowdSale manager * @param _account Address of account which tokens will be imported */ function importTokens(address _account) returns (bool success) { // only token holder or manager can do import require(currentState == State.Running); require(msg.sender == saleController || msg.sender == _account); require(!importedFromPreSale[_account]); // Token decimals in PreSale was 18 uint256 preSaleBalance = preSaleToken.balanceOf(_account) / TOKEN_PRICE_N; if (preSaleBalance == 0) return false; looksCoin.rewardTokens(_account, preSaleBalance); importedTokens = importedTokens + preSaleBalance; importedFromPreSale[_account] = true; TokensImport(_account, preSaleBalance, importedTokens); return true; } // fallback function() public payable { buyTokens(); } event TokensBought(address indexed buyer, uint256 ethers, uint256 tokens, uint256 tokensSold); /** * Accept ethers to buy tokens during the token sale * Minimium holdings to receive a VIP rank is 24000 LooksCoin */ function buyTokens() payable returns (uint256 amount) { require(currentState == State.Running); assert(msg.sender != 0x0); require(msg.value > 0); // Calculate number of tokens for contributed wei uint256 tokens = msg.value * TOKEN_PRICE_D / TOKEN_PRICE_N; if (tokens == 0) return 0; looksCoin.rewardTokens(msg.sender, tokens); tokensSold = tokensSold + tokens; // Transfer the contributed ethers to the crowdsale fundstorage assert(fundstorage.send(msg.value)); TokensBought(msg.sender, msg.value, tokens, tokensSold); return tokens; } }
* Accept ethers to buy tokens during the token sale Minimium holdings to receive a VIP rank is 24000 LooksCoin/ Calculate number of tokens for contributed wei Transfer the contributed ethers to the crowdsale fundstorage
function buyTokens() payable returns (uint256 amount) { require(currentState == State.Running); assert(msg.sender != 0x0); require(msg.value > 0); uint256 tokens = msg.value * TOKEN_PRICE_D / TOKEN_PRICE_N; if (tokens == 0) return 0; looksCoin.rewardTokens(msg.sender, tokens); tokensSold = tokensSold + tokens; assert(fundstorage.send(msg.value)); TokensBought(msg.sender, msg.value, tokens, tokensSold); return tokens; }
6,429,652
[ 1, 5933, 13750, 414, 358, 30143, 2430, 4982, 326, 1147, 272, 5349, 5444, 381, 5077, 6887, 899, 358, 6798, 279, 776, 2579, 6171, 353, 4248, 3784, 10176, 87, 27055, 19, 9029, 1300, 434, 2430, 364, 356, 11050, 732, 77, 12279, 326, 356, 11050, 13750, 414, 358, 326, 276, 492, 2377, 5349, 284, 1074, 5697, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 5157, 1435, 8843, 429, 1135, 261, 11890, 5034, 3844, 13, 203, 565, 288, 203, 3639, 2583, 12, 2972, 1119, 422, 3287, 18, 7051, 1769, 203, 3639, 1815, 12, 3576, 18, 15330, 480, 374, 92, 20, 1769, 203, 3639, 2583, 12, 3576, 18, 1132, 405, 374, 1769, 203, 203, 3639, 2254, 5034, 2430, 273, 1234, 18, 1132, 380, 14275, 67, 7698, 1441, 67, 40, 342, 14275, 67, 7698, 1441, 67, 50, 31, 203, 3639, 309, 261, 7860, 422, 374, 13, 327, 374, 31, 203, 203, 3639, 10192, 27055, 18, 266, 2913, 5157, 12, 3576, 18, 15330, 16, 2430, 1769, 203, 3639, 2430, 55, 1673, 273, 2430, 55, 1673, 397, 2430, 31, 203, 203, 3639, 1815, 12, 74, 1074, 5697, 18, 4661, 12, 3576, 18, 1132, 10019, 203, 3639, 13899, 13809, 9540, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 16, 2430, 16, 2430, 55, 1673, 1769, 203, 3639, 327, 2430, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.22 <0.6.0; pragma experimental ABIEncoderV2; contract AccessRightsManagement{ mapping (address => string) public hasIdentity; mapping (string => User) usermap; identityRequests[] public identityQueue; //mapping (address => string) requestIdentity; string[][4] public accessQueue; mapping (uint8 => string[50]) accessmap; uint8 counter; //string[50] test; struct identityRequests { address userAddress; string userString; string message; } struct User { bool[5] isAdmin; int8[4] hasAccessRight; bytes32 role; string description; bool exists; } constructor() public { hasIdentity[msg.sender] = "test"; //Atleast 1 administrator should be defined in constructor usermap["test"].role = "admin"; usermap["test"].description = "Global Administrator, keeps track of everything"; usermap["test"].isAdmin[0] = true; usermap["test"].isAdmin[1] = true; usermap["test"].isAdmin[2] = true; usermap["test"].isAdmin[3] = true; usermap["test"].isAdmin[4] = true; usermap["test"].hasAccessRight[0] = 2; usermap["test"].hasAccessRight[1] = 2; usermap["test"].hasAccessRight[2] = 2; usermap["test"].hasAccessRight[3] = 2; usermap["test"].exists = true; } modifier onlyUser(string memory userkey) { require(keccak256(abi.encode(hasIdentity[msg.sender])) == keccak256(abi.encode(userkey))); _; } function welcome(string memory userkey) public view returns (bool recognised) { if(usermap[userkey].exists) { return true; } else { return false; } } function proceedWelcome(string memory userkey, string memory notice) public returns (bool worked) { if(!usermap[userkey].exists) { identityRequests memory user; user.userAddress = msg.sender; user.userString = userkey; user.message = notice; // uint256 a = identityQueue.length; identityQueue.push(user); // identityQueue[identityQueue.length] = user; usermap[userkey].exists = true; return true; } return false; } function showAccessRights(string memory userkey) public view onlyUser(userkey) returns (int8[4] memory accessrights, bytes32 role) { return (usermap[userkey].hasAccessRight, usermap[userkey].role); } function getAdminRights(string memory userkey) public view onlyUser(userkey) returns (bool[5] memory isAdmin) { return (usermap[userkey].isAdmin); } function newAccessRight(string memory userkey, uint8 accesstype) public onlyUser(userkey) returns(int8 accessstatus) { /** int8 accessstatusl = usermap[userkey].hasAccessRight[accesstype]; if(accessstatusl == 0) usermap[userkey].hasAccessRight[accesstype] = 1; //0 means -1 and so on return accessstatusl; */ int8 accessstatusbefore = usermap[userkey].hasAccessRight[accesstype]; if(accessstatusbefore == 0) { usermap[userkey].hasAccessRight[accesstype] = 1; //0 means -1 and so on //uint length = accessQueue[accesstype].length; //accessQueue[accesstype][length-1] = userkey; //accessmap[accesstype] = string[] memory; //uint length = accessmap[accesstype].length-1; accessmap[0][counter] = userkey; counter++; //test[test.length] = userkey; } return accessstatusbefore; } function handleRequest(string memory adminkey, uint8 listcount, uint8 accesstype, bool answer) public onlyUser(adminkey) returns(bool allowed) { string memory userkey = accessmap[accesstype][listcount]; if(usermap[adminkey].isAdmin[accesstype] == true) { if(usermap[userkey].hasAccessRight[accesstype] != 2) { if(answer == true) usermap[userkey].hasAccessRight[accesstype] = 2; else usermap[userkey].hasAccessRight[accesstype] = 0; for(uint i = listcount+1; i<counter; i++) { accessmap[accesstype][i-1] = accessmap[accesstype][i]; } //accessQueue[accesstype][listcount][accessQueue[accesstype][listcount].length-1] = noRequest; delete accessmap[accesstype][counter-1]; // accessmap[accesstype].length--; counter--; } return true; } return false; } function getCreationRequest(string memory adminkey) public view onlyUser(adminkey) returns(string memory message) { if(usermap[adminkey].isAdmin[4]) { if(identityQueue.length > 0) return identityQueue[0].message; //If not exists, string will be empty else return ""; } } function handleCreationRequest(string memory adminkey, bool answer, bytes32 role, string memory description, int8[4] memory initialAccessRights, bool[5] memory initialAdminRights) public onlyUser(adminkey) { require(usermap[adminkey].isAdmin[4]); if(answer) { hasIdentity[identityQueue[0].userAddress] = identityQueue[0].userString; usermap[identityQueue[0].userString].role = role; usermap[identityQueue[0].userString].description = description; usermap[identityQueue[0].userString].isAdmin = initialAdminRights; usermap[identityQueue[0].userString].hasAccessRight = initialAccessRights; } //identityRequests memory noRequest; for(uint i = 1; i<identityQueue.length; i++) { identityQueue[i-1] = identityQueue[i]; } //identityQueue[identityQueue.length-1] = noRequest; delete identityQueue[identityQueue.length-1]; identityQueue.length--; } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function bytes32ToString(bytes32 x) public pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint v = 0; v < charCount; v++) { bytesStringTrimmed[v] = bytesString[v]; } return string(bytesStringTrimmed); } // Test Methods function proceedWelcomeView() public view returns(string memory) { return identityQueue[0].userString; //Problem if empty } function getUser(string memory name) public view returns(User memory) { return usermap[name]; //Problem if empty } function getQueue() public view returns(identityRequests[] memory) { return identityQueue; //Problem if empty } }
Atleast 1 administrator should be defined in constructor
hasIdentity[msg.sender] = "test";
12,995,185
[ 1, 861, 16446, 404, 22330, 1410, 506, 2553, 316, 3885, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 711, 4334, 63, 3576, 18, 15330, 65, 273, 315, 3813, 14432, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.6; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {PermissionAdmin} from '@kyber.network/utils-sc/contracts/PermissionAdmin.sol'; import {PermissionOperators} from '@kyber.network/utils-sc/contracts/PermissionOperators.sol'; import {IERC20Ext} from '@kyber.network/utils-sc/contracts/IERC20Ext.sol'; import {IKyberGovernance} from '../interfaces/governance/IKyberGovernance.sol'; import {IRewardsDistributor} from '../interfaces/rewardDistribution/IRewardsDistributor.sol'; /** Internal contracts to participate in KyberDAO and claim rewards for Kyber Only accept external delegation, all reward will be transferred */ contract KyberInternalGovernance is PermissionOperators { using SafeERC20 for IERC20Ext; IERC20Ext public constant ETH_TOKEN_ADDRESS = IERC20Ext(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); address payable public rewardRecipient; IKyberGovernance public governance; IRewardsDistributor public rewardDistributor; constructor( address _admin, address payable _rewardRecipient, IKyberGovernance _governance, IRewardsDistributor _rewardDistributor, address _operator ) PermissionAdmin(_admin) { require(_rewardRecipient != address(0), "invalid reward recipient"); require(_governance != IKyberGovernance(0), "invalid kyber governance"); require(_rewardDistributor != IRewardsDistributor(0), "invalid reward distributor"); rewardRecipient = _rewardRecipient; governance = _governance; rewardDistributor = _rewardDistributor; if (_operator != address(0)) { // consistent with current design operators[_operator] = true; operatorsGroup.push(_operator); emit OperatorAdded(_operator, true); } } receive() external payable {} /** * @dev only operator can vote, given list of proposal ids * and an option for each proposal */ function vote( uint256[] calldata proposalIds, uint256[] calldata optionBitMasks ) external onlyOperator { require(proposalIds.length == optionBitMasks.length, "invalid length"); for(uint256 i = 0; i < proposalIds.length; i++) { governance.submitVote(proposalIds[i], optionBitMasks[i]); } } /** * @dev anyone can call to claim rewards for multiple epochs * @dev all eth will be sent back to rewardRecipient */ function claimRewards( uint256 cycle, uint256 index, IERC20Ext[] calldata tokens, uint256[] calldata cumulativeAmounts, bytes32[] calldata merkleProof ) external returns (uint256[] memory claimAmounts) { claimAmounts = rewardDistributor.claim( cycle, index, address(this), tokens, cumulativeAmounts, merkleProof ); for(uint256 i = 0; i < tokens.length; i++) { uint256 bal = tokens[i] == ETH_TOKEN_ADDRESS ? address(this).balance : tokens[i].balanceOf(address(this)); if (bal > 0) _transferToken(tokens[i], bal); } } function updateRewardRecipient(address payable _newRecipient) external onlyAdmin { require(_newRecipient != address(0), "invalid address"); rewardRecipient = _newRecipient; } /** * @dev most likely unused, but put here for flexibility or in case a mistake in deployment */ function updateKyberContracts( IKyberGovernance _governance, IRewardsDistributor _rewardDistributor ) external onlyAdmin { require(_governance != IKyberGovernance(0), "invalid kyber dao"); require(_rewardDistributor != IRewardsDistributor(0), "invalid reward distributor"); governance = _governance; rewardDistributor = _rewardDistributor; } /** * @dev allow withdraw funds of any tokens to rewardRecipient address */ function withdrawFund( IERC20Ext[] calldata tokens, uint256[] calldata amounts ) external { require(tokens.length == amounts.length, "invalid length"); for(uint256 i = 0; i < tokens.length; i++) { _transferToken(tokens[i], amounts[i]); } } function _transferToken(IERC20Ext token, uint256 amount) internal { if (token == ETH_TOKEN_ADDRESS) { (bool success, ) = rewardRecipient.call { value: amount }(""); require(success, "transfer eth failed"); } else { token.safeTransfer(rewardRecipient, amount); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; abstract contract PermissionAdmin { address public admin; address public pendingAdmin; event AdminClaimed(address newAdmin, address previousAdmin); event TransferAdminPending(address pendingAdmin); constructor(address _admin) { require(_admin != address(0), "admin 0"); admin = _admin; } modifier onlyAdmin() { require(msg.sender == admin, "only admin"); _; } /** * @dev Allows the current admin to set the pendingAdmin address. * @param newAdmin The address to transfer ownership to. */ function transferAdmin(address newAdmin) public onlyAdmin { require(newAdmin != address(0), "new admin 0"); emit TransferAdminPending(newAdmin); pendingAdmin = newAdmin; } /** * @dev Allows the current admin to set the admin in one tx. Useful initial deployment. * @param newAdmin The address to transfer ownership to. */ function transferAdminQuickly(address newAdmin) public onlyAdmin { require(newAdmin != address(0), "admin 0"); emit TransferAdminPending(newAdmin); emit AdminClaimed(newAdmin, admin); admin = newAdmin; } /** * @dev Allows the pendingAdmin address to finalize the change admin process. */ function claimAdmin() public { require(pendingAdmin == msg.sender, "not pending"); emit AdminClaimed(pendingAdmin, admin); admin = pendingAdmin; pendingAdmin = address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./PermissionAdmin.sol"; abstract contract PermissionOperators is PermissionAdmin { uint256 private constant MAX_GROUP_SIZE = 50; mapping(address => bool) internal operators; address[] internal operatorsGroup; event OperatorAdded(address newOperator, bool isAdd); modifier onlyOperator() { require(operators[msg.sender], "only operator"); _; } function getOperators() external view returns (address[] memory) { return operatorsGroup; } function addOperator(address newOperator) public onlyAdmin { require(!operators[newOperator], "operator exists"); // prevent duplicates. require(operatorsGroup.length < MAX_GROUP_SIZE, "max operators"); emit OperatorAdded(newOperator, true); operators[newOperator] = true; operatorsGroup.push(newOperator); } function removeOperator(address operator) public onlyAdmin { require(operators[operator], "not operator"); operators[operator] = false; for (uint256 i = 0; i < operatorsGroup.length; ++i) { if (operatorsGroup[i] == operator) { operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1]; operatorsGroup.pop(); emit OperatorAdded(operator, false); break; } } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @dev Interface extending ERC20 standard to include decimals() as * it is optional in the OpenZeppelin IERC20 interface. */ interface IERC20Ext is IERC20 { /** * @dev This function is required as Kyber requires to interact * with token.decimals() with many of its operations. */ function decimals() external view returns (uint8 digits); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.6; pragma abicoder v2; import {IExecutorWithTimelock} from './IExecutorWithTimelock.sol'; import {IVotingPowerStrategy} from './IVotingPowerStrategy.sol'; interface IKyberGovernance { enum ProposalState { Pending, Canceled, Active, Failed, Succeeded, Queued, Expired, Executed, Finalized } enum ProposalType {Generic, Binary} /// For Binary proposal, optionBitMask is 0/1/2 /// For Generic proposal, optionBitMask is bitmask of voted options struct Vote { uint32 optionBitMask; uint224 votingPower; } struct ProposalWithoutVote { uint256 id; ProposalType proposalType; address creator; IExecutorWithTimelock executor; IVotingPowerStrategy strategy; address[] targets; uint256[] weiValues; string[] signatures; bytes[] calldatas; bool[] withDelegatecalls; string[] options; uint256[] voteCounts; uint256 totalVotes; uint256 maxVotingPower; uint256 startTime; uint256 endTime; uint256 executionTime; string link; bool executed; bool canceled; } struct Proposal { ProposalWithoutVote proposalData; mapping(address => Vote) votes; } struct BinaryProposalParams { address[] targets; uint256[] weiValues; string[] signatures; bytes[] calldatas; bool[] withDelegatecalls; } /** * @dev emitted when a new binary proposal is created * @param proposalId id of the binary proposal * @param creator address of the creator * @param executor ExecutorWithTimelock contract that will execute the proposal * @param strategy votingPowerStrategy contract to calculate voting power * @param targets list of contracts called by proposal's associated transactions * @param weiValues list of value in wei for each propoposal's associated transaction * @param signatures list of function signatures (can be empty) to be used * when created the callData * @param calldatas list of calldatas: if associated signature empty, * calldata ready, else calldata is arguments * @param withDelegatecalls boolean, true = transaction delegatecalls the taget, * else calls the target * @param startTime timestamp when vote starts * @param endTime timestamp when vote ends * @param link URL link of the proposal * @param maxVotingPower max voting power for this proposal **/ event BinaryProposalCreated( uint256 proposalId, address indexed creator, IExecutorWithTimelock indexed executor, IVotingPowerStrategy indexed strategy, address[] targets, uint256[] weiValues, string[] signatures, bytes[] calldatas, bool[] withDelegatecalls, uint256 startTime, uint256 endTime, string link, uint256 maxVotingPower ); /** * @dev emitted when a new generic proposal is created * @param proposalId id of the generic proposal * @param creator address of the creator * @param executor ExecutorWithTimelock contract that will execute the proposal * @param strategy votingPowerStrategy contract to calculate voting power * @param options list of proposal vote options * @param startTime timestamp when vote starts * @param endTime timestamp when vote ends * @param link URL link of the proposal * @param maxVotingPower max voting power for this proposal **/ event GenericProposalCreated( uint256 proposalId, address indexed creator, IExecutorWithTimelock indexed executor, IVotingPowerStrategy indexed strategy, string[] options, uint256 startTime, uint256 endTime, string link, uint256 maxVotingPower ); /** * @dev emitted when a proposal is canceled * @param proposalId id of the proposal **/ event ProposalCanceled(uint256 proposalId); /** * @dev emitted when a proposal is queued * @param proposalId id of the proposal * @param executionTime time when proposal underlying transactions can be executed * @param initiatorQueueing address of the initiator of the queuing transaction **/ event ProposalQueued( uint256 indexed proposalId, uint256 executionTime, address indexed initiatorQueueing ); /** * @dev emitted when a proposal is executed * @param proposalId id of the proposal * @param initiatorExecution address of the initiator of the execution transaction **/ event ProposalExecuted(uint256 proposalId, address indexed initiatorExecution); /** * @dev emitted when a vote is registered * @param proposalId id of the proposal * @param voter address of the voter * @param voteOptions vote options selected by voter * @param votingPower Power of the voter/vote **/ event VoteEmitted( uint256 indexed proposalId, address indexed voter, uint32 indexed voteOptions, uint224 votingPower ); /** * @dev emitted when a vote is registered * @param proposalId id of the proposal * @param voter address of the voter * @param voteOptions vote options selected by voter * @param oldVotingPower Old power of the voter/vote * @param newVotingPower New power of the voter/vote **/ event VotingPowerChanged( uint256 indexed proposalId, address indexed voter, uint32 indexed voteOptions, uint224 oldVotingPower, uint224 newVotingPower ); event DaoOperatorTransferred(address indexed newDaoOperator); event ExecutorAuthorized(address indexed executor); event ExecutorUnauthorized(address indexed executor); event VotingPowerStrategyAuthorized(address indexed strategy); event VotingPowerStrategyUnauthorized(address indexed strategy); /** * @dev Function is triggered when users withdraw from staking and change voting power */ function handleVotingPowerChanged( address staker, uint256 newVotingPower, uint256[] calldata proposalIds ) external; /** * @dev Creates a Binary Proposal (needs to be validated by the Proposal Validator) * @param executor The ExecutorWithTimelock contract that will execute the proposal * @param strategy voting power strategy of the proposal * @param executionParams data for execution, includes * targets list of contracts called by proposal's associated transactions * weiValues list of value in wei for each proposal's associated transaction * signatures list of function signatures (can be empty) * to be used when created the callData * calldatas list of calldatas: if associated signature empty, * calldata ready, else calldata is arguments * withDelegatecalls boolean, true = transaction delegatecalls the taget, * else calls the target * @param startTime start timestamp to allow vote * @param endTime end timestamp of the proposal * @param link link to the proposal description **/ function createBinaryProposal( IExecutorWithTimelock executor, IVotingPowerStrategy strategy, BinaryProposalParams memory executionParams, uint256 startTime, uint256 endTime, string memory link ) external returns (uint256 proposalId); /** * @dev Creates a Generic Proposal * @param executor ExecutorWithTimelock contract that will execute the proposal * @param strategy votingPowerStrategy contract to calculate voting power * @param options list of proposal vote options * @param startTime timestamp when vote starts * @param endTime timestamp when vote ends * @param link URL link of the proposal **/ function createGenericProposal( IExecutorWithTimelock executor, IVotingPowerStrategy strategy, string[] memory options, uint256 startTime, uint256 endTime, string memory link ) external returns (uint256 proposalId); /** * @dev Cancels a Proposal, * either at anytime by guardian * or when proposal is Pending/Active and threshold no longer reached * @param proposalId id of the proposal **/ function cancel(uint256 proposalId) external; /** * @dev Queue the proposal (If Proposal Succeeded) * @param proposalId id of the proposal to queue **/ function queue(uint256 proposalId) external; /** * @dev Execute the proposal (If Proposal Queued) * @param proposalId id of the proposal to execute **/ function execute(uint256 proposalId) external payable; /** * @dev Function allowing msg.sender to vote for/against a proposal * @param proposalId id of the proposal * @param optionBitMask vote option(s) selected **/ function submitVote(uint256 proposalId, uint256 optionBitMask) external; /** * @dev Function to register the vote of user that has voted offchain via signature * @param proposalId id of the proposal * @param choice the bit mask of voted options * @param v v part of the voter signature * @param r r part of the voter signature * @param s s part of the voter signature **/ function submitVoteBySignature( uint256 proposalId, uint256 choice, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Add new addresses to the list of authorized executors * @param executors list of new addresses to be authorized executors **/ function authorizeExecutors(address[] calldata executors) external; /** * @dev Remove addresses to the list of authorized executors * @param executors list of addresses to be removed as authorized executors **/ function unauthorizeExecutors(address[] calldata executors) external; /** * @dev Add new addresses to the list of authorized strategies * @param strategies list of new addresses to be authorized strategies **/ function authorizeVotingPowerStrategies(address[] calldata strategies) external; /** * @dev Remove addresses to the list of authorized strategies * @param strategies list of addresses to be removed as authorized strategies **/ function unauthorizeVotingPowerStrategies(address[] calldata strategies) external; /** * @dev Returns whether an address is an authorized executor * @param executor address to evaluate as authorized executor * @return true if authorized **/ function isExecutorAuthorized(address executor) external view returns (bool); /** * @dev Returns whether an address is an authorized strategy * @param strategy address to evaluate as authorized strategy * @return true if authorized **/ function isVotingPowerStrategyAuthorized(address strategy) external view returns (bool); /** * @dev Getter the address of the guardian, that can mainly cancel proposals * @return The address of the guardian **/ function getDaoOperator() external view returns (address); /** * @dev Getter of the proposal count (the current number of proposals ever created) * @return the proposal count **/ function getProposalsCount() external view returns (uint256); /** * @dev Getter of a proposal by id * @param proposalId id of the proposal to get * @return the proposal as ProposalWithoutVote memory object **/ function getProposalById(uint256 proposalId) external view returns (ProposalWithoutVote memory); /** * @dev Getter of the vote data of a proposal by id * including totalVotes, voteCounts and options * @param proposalId id of the proposal * @return (totalVotes, voteCounts, options) **/ function getProposalVoteDataById(uint256 proposalId) external view returns ( uint256, uint256[] memory, string[] memory ); /** * @dev Getter of the Vote of a voter about a proposal * Note: Vote is a struct: ({uint32 bitOptionMask, uint224 votingPower}) * @param proposalId id of the proposal * @param voter address of the voter * @return The associated Vote memory object **/ function getVoteOnProposal(uint256 proposalId, address voter) external view returns (Vote memory); /** * @dev Get the current state of a proposal * @param proposalId id of the proposal * @return The current state if the proposal **/ function getProposalState(uint256 proposalId) external view returns (ProposalState); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IERC20Ext} from '@kyber.network/utils-sc/contracts/IERC20Ext.sol'; interface IRewardsDistributor { event Claimed( uint256 indexed cycle, address indexed user, IERC20Ext[] tokens, uint256[] claimAmounts ); /** * @dev Claim accumulated rewards for a set of tokens at a given cycle number * @param cycle cycle number * @param index user reward info index in the array of reward info * during merkle tree generation * @param user wallet address of reward beneficiary * @param tokens array of tokens claimable by reward beneficiary * @param cumulativeAmounts cumulative token amounts claimable by reward beneficiary * @param merkleProof merkle proof of claim * @return claimAmounts actual claimed token amounts sent to the reward beneficiary **/ function claim( uint256 cycle, uint256 index, address user, IERC20Ext[] calldata tokens, uint256[] calldata cumulativeAmounts, bytes32[] calldata merkleProof ) external returns (uint256[] memory claimAmounts); /** * @dev Checks whether a claim is valid or not * @param cycle cycle number * @param index user reward info index in the array of reward info * during merkle tree generation * @param user wallet address of reward beneficiary * @param tokens array of tokens claimable by reward beneficiary * @param cumulativeAmounts cumulative token amounts claimable by reward beneficiary * @param merkleProof merkle proof of claim * @return true if valid claim, false otherwise **/ function isValidClaim( uint256 cycle, uint256 index, address user, IERC20Ext[] calldata tokens, uint256[] calldata cumulativeAmounts, bytes32[] calldata merkleProof ) external view returns (bool); /** * @dev Fetch accumulated claimed rewards for a set of tokens since the first cycle * @param user wallet address of reward beneficiary * @param tokens array of tokens claimed by reward beneficiary * @return userClaimedAmounts claimed token amounts by reward beneficiary since the first cycle **/ function getClaimedAmounts(address user, IERC20Ext[] calldata tokens) external view returns (uint256[] memory userClaimedAmounts); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.6; pragma abicoder v2; import {IKyberGovernance} from './IKyberGovernance.sol'; interface IExecutorWithTimelock { /** * @dev emitted when a new pending admin is set * @param newPendingAdmin address of the new pending admin **/ event NewPendingAdmin(address newPendingAdmin); /** * @dev emitted when a new admin is set * @param newAdmin address of the new admin **/ event NewAdmin(address newAdmin); /** * @dev emitted when a new delay (between queueing and execution) is set * @param delay new delay **/ event NewDelay(uint256 delay); /** * @dev emitted when a new (trans)action is Queued. * @param actionHash hash of the action * @param target address of the targeted contract * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ event QueuedAction( bytes32 actionHash, address indexed target, uint256 value, string signature, bytes data, uint256 executionTime, bool withDelegatecall ); /** * @dev emitted when an action is Cancelled * @param actionHash hash of the action * @param target address of the targeted contract * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ event CancelledAction( bytes32 actionHash, address indexed target, uint256 value, string signature, bytes data, uint256 executionTime, bool withDelegatecall ); /** * @dev emitted when an action is Cancelled * @param actionHash hash of the action * @param target address of the targeted contract * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target * @param resultData the actual callData used on the target **/ event ExecutedAction( bytes32 actionHash, address indexed target, uint256 value, string signature, bytes data, uint256 executionTime, bool withDelegatecall, bytes resultData ); /** * @dev Function, called by Governance, that queue a transaction, returns action hash * @param target smart contract target * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ function queueTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) external returns (bytes32); /** * @dev Function, called by Governance, that cancels a transaction, returns the callData executed * @param target smart contract target * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ function executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) external payable returns (bytes memory); /** * @dev Function, called by Governance, that cancels a transaction, returns action hash * @param target smart contract target * @param value wei value of the transaction * @param signature function signature of the transaction * @param data function arguments of the transaction or callData if signature empty * @param executionTime time at which to execute the transaction * @param withDelegatecall boolean, true = transaction delegatecalls the target, else calls the target **/ function cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) external returns (bytes32); /** * @dev Getter of the current admin address (should be governance) * @return The address of the current admin **/ function getAdmin() external view returns (address); /** * @dev Getter of the current pending admin address * @return The address of the pending admin **/ function getPendingAdmin() external view returns (address); /** * @dev Getter of the delay between queuing and execution * @return The delay in seconds **/ function getDelay() external view returns (uint256); /** * @dev Returns whether an action (via actionHash) is queued * @param actionHash hash of the action to be checked * keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall)) * @return true if underlying action of actionHash is queued **/ function isActionQueued(bytes32 actionHash) external view returns (bool); /** * @dev Checks whether a proposal is over its grace period * @param governance Governance contract * @param proposalId Id of the proposal against which to test * @return true of proposal is over grace period **/ function isProposalOverGracePeriod(IKyberGovernance governance, uint256 proposalId) external view returns (bool); /** * @dev Getter of grace period constant * @return grace period in seconds **/ function GRACE_PERIOD() external view returns (uint256); /** * @dev Getter of minimum delay constant * @return minimum delay in seconds **/ function MINIMUM_DELAY() external view returns (uint256); /** * @dev Getter of maximum delay constant * @return maximum delay in seconds **/ function MAXIMUM_DELAY() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.6; pragma abicoder v2; import {IWithdrawHandler} from '../staking/IWithdrawHandler.sol'; interface IVotingPowerStrategy is IWithdrawHandler { /** * @dev call by governance when create a proposal */ function handleProposalCreation( uint256 proposalId, uint256 startTime, uint256 endTime ) external; /** * @dev call by governance when cancel a proposal */ function handleProposalCancellation(uint256 proposalId) external; /** * @dev call by governance when submitting a vote * @param choice: unused param for future usage * @return votingPower of voter */ function handleVote( address voter, uint256 proposalId, uint256 choice ) external returns (uint256 votingPower); /** * @dev get voter's voting power given timestamp * @dev for reading purposes and validating voting power for creating/canceling proposal in the furture * @dev when submitVote, should call 'handleVote' instead */ function getVotingPower(address voter, uint256 timestamp) external view returns (uint256 votingPower); /** * @dev validate that startTime and endTime are suitable for calculating voting power * @dev with current version, startTime and endTime must be in the sameEpcoh */ function validateProposalCreation(uint256 startTime, uint256 endTime) external view returns (bool); /** * @dev getMaxVotingPower at current time * @dev call by governance when creating a proposal */ function getMaxVotingPower() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.6; pragma abicoder v2; /** * @title Interface for callbacks hooks when user withdraws from staking contract */ interface IWithdrawHandler { function handleWithdrawal(address staker, uint256 reduceAmount) external; }
* @dev most likely unused, but put here for flexibility or in case a mistake in deployment/
function updateKyberContracts( IKyberGovernance _governance, IRewardsDistributor _rewardDistributor ) external onlyAdmin { require(_governance != IKyberGovernance(0), "invalid kyber dao"); require(_rewardDistributor != IRewardsDistributor(0), "invalid reward distributor"); governance = _governance; rewardDistributor = _rewardDistributor; }
10,159,956
[ 1, 10329, 10374, 10197, 16, 1496, 1378, 2674, 364, 16600, 3628, 578, 316, 648, 279, 27228, 911, 316, 6314, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 47, 93, 744, 20723, 12, 203, 3639, 467, 47, 93, 744, 43, 1643, 82, 1359, 389, 75, 1643, 82, 1359, 16, 203, 3639, 15908, 359, 14727, 1669, 19293, 389, 266, 2913, 1669, 19293, 203, 565, 262, 203, 3639, 3903, 1338, 4446, 203, 565, 288, 203, 3639, 2583, 24899, 75, 1643, 82, 1359, 480, 467, 47, 93, 744, 43, 1643, 82, 1359, 12, 20, 3631, 315, 5387, 417, 93, 744, 15229, 8863, 203, 3639, 2583, 24899, 266, 2913, 1669, 19293, 480, 15908, 359, 14727, 1669, 19293, 12, 20, 3631, 315, 5387, 19890, 1015, 19293, 8863, 203, 3639, 314, 1643, 82, 1359, 273, 389, 75, 1643, 82, 1359, 31, 203, 3639, 19890, 1669, 19293, 273, 389, 266, 2913, 1669, 19293, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-12-07 */ // SPDX-License-Identifier: MIT // ((/*, ,*((/,. // &&@@&&%#/*. .*(#&&@@@@%. // &&@@@@@@@&%(. ,#%&@@@@@@@@%. // &&@@@@@@@@@&&(, ,#&@@@@@@@@@@@%. // &&@@@@@@@@@@@&&/. .(&&@@@@@@@@@@@@%. // %&@@@@@@@@@@@@@&(, *#&@@@@@@@@@@@@@@%. // #&@@@@@@@@@@@@@@&#* .*#@@@@@@@@@@@@@@@&#. // #&@@@@@@@@@@@@@@@@#. ,%&@@@@@@@@@@@@@@@&#. // #&@@@@@@@@@@@@@@@@%(, ,(&@@@@@@@@@@@@@@@@&#. // #&@@@@@@@@@@@@@@@@&&/ .(%&@@@@@@@@@@@@@@@@&#. // #%@@@@@@@@@@@@@@@@@@(. ,(/,. .#&@@@@@@@@@@@@@@@@@&#. // (%@@@@@@@@@@@@@@@@@@#*. ./%&&&/. .*%@@@@@@@@@@@@@@@@@@%(. // (%@@@@@@@@@@@@@@@@@@#*. *#&@@@@&%*. .*%@@@@@@@@@@@@@@@@@@%(. // (%@@@@@@@@@@@@@@@@@@#/. ./#@@@@@@@@%(. ./%@@@@@@@@@@@@@@@@@@%(. // (%@@@@@@@@@@@@@@@@@@#/. ./&@@@@@@@@@@&(* ,/%@@@@@@@@@@@@@@@@@@%(. // (%@@@@@@@@@@@@@@@@@@%/. ,#&@@@@@@@@@@@@&#,. ,/%@@@@@@@@@@@@@@@@@@%(. // /%@@@@@@@@@@@@@@@@@@#/. *(&@@@@@@@@@@@@@@&&* ./%@@@@@@@@@@@@@@@@@&%(. // /%@@@@@@@@@@@@@@@@@@#/. .(&@@@@@@@@@@@@@@@@@#*. ,/%@@@@@@@@@@@@@@@@@&#/. // ,#@@@@@@@@@@@@@@@@@@#/. ./%@@@@@@@@@@@@@@@@@@&#, ,/%@@@@@@@@@@@@@@@@@&(, // /%&@@@@@@@@@@@@@@@@#/. *#&@@@@@@@@@@@@@@@@@@@&* ,/%@@@@@@@@@@@@@@@@&%* // .*#&@@@@@@@@@@@@@@@#/. /&&@@@@@@@@@@@@@@@@@@@&/. ,/%@@@@@@@@@@@@@@@@#*. // ,(&@@@@@@@@@@@@@@#/. /@@@@@@@@@@@@@@@@@@@@@&(, ,/%@@@@@@@@@@@@@@%(, // .*(&&@@@@@@@@@@@#/. /&&@@@@@@@@@@@@@@@@@@@&/, ,/%@@@@@@@@@@@&%/, // ./%&@@@@@@@@@#/. *#&@@@@@@@@@@@@@@@@@@@%* ,/%@@@@@@@@@&%* // ,/#%&&@@@@#/. ,#&@@@@@@@@@@@@@@@@@#/. ,/%@@@@&&%(/, // ./#&@@%/. ,/&@@@@@@@@@@@@@@%(, ,/%@@%#*. // .,,, ,/%&@@@@@@@@&%(* .,,,. // ,/%&@@@%(*. // .,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,**((/*,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, // // pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; contract Warden { /// @notice EIP-20 token name for this token string public constant name = "WardenSwap"; /// @notice EIP-20 token symbol for this token string public constant symbol = "WAD"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 200_000_000e18; // 200 million Wad /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Warden token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Wad::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Wad::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Wad::permit: invalid signature"); require(signatory == owner, "Wad::permit: unauthorized"); require(now <= deadline, "Wad::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Wad::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Wad::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Wad::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Wad::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Wad::delegateBySig: invalid nonce"); require(now <= expiry, "Wad::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Wad::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Wad::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Wad::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Wad::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Wad::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Wad::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Wad::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Wad::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
* @notice Transfer `amount` tokens from `src` to `dst` @param src The address of the source account @param dst The address of the destination account @param rawAmount The number of tokens to transfer @return Whether or not the transfer succeeded/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Wad::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Wad::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; }
7,826,555
[ 1, 5912, 1375, 8949, 68, 2430, 628, 1375, 4816, 68, 358, 1375, 11057, 68, 225, 1705, 1021, 1758, 434, 326, 1084, 2236, 225, 3046, 1021, 1758, 434, 326, 2929, 2236, 225, 1831, 6275, 1021, 1300, 434, 2430, 358, 7412, 327, 17403, 578, 486, 326, 7412, 15784, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 1705, 16, 1758, 3046, 16, 2254, 1831, 6275, 13, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 1758, 17571, 264, 273, 1234, 18, 15330, 31, 203, 3639, 2254, 10525, 17571, 264, 7009, 1359, 273, 1699, 6872, 63, 4816, 6362, 87, 1302, 264, 15533, 203, 3639, 2254, 10525, 3844, 273, 4183, 10525, 12, 1899, 6275, 16, 315, 59, 361, 2866, 12908, 537, 30, 3844, 14399, 19332, 4125, 8863, 203, 203, 3639, 309, 261, 87, 1302, 264, 480, 1705, 597, 17571, 264, 7009, 1359, 480, 2254, 10525, 19236, 21, 3719, 288, 203, 5411, 2254, 10525, 394, 7009, 1359, 273, 720, 10525, 12, 87, 1302, 264, 7009, 1359, 16, 3844, 16, 315, 59, 361, 2866, 13866, 1265, 30, 7412, 3844, 14399, 17571, 264, 1699, 1359, 8863, 203, 5411, 1699, 6872, 63, 4816, 6362, 87, 1302, 264, 65, 273, 394, 7009, 1359, 31, 203, 203, 5411, 3626, 1716, 685, 1125, 12, 4816, 16, 17571, 264, 16, 394, 7009, 1359, 1769, 203, 3639, 289, 203, 203, 3639, 389, 13866, 5157, 12, 4816, 16, 3046, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.2; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; contract HappyRedPacket { struct RedPacket { uint256 packed1; // exp(48) total_tokens(80) hash(64) id(64) BIG ENDIAN uint256 packed2; // ifrandom(1) token_type(8) total_number(8) claimed(8) creator(64) token_addr(160) mapping(address => uint256) claimed_list; } event CreationSuccess( uint total, bytes32 id, string name, string message, address creator, uint creation_time, address token_address ); event ClaimSuccess( bytes32 id, address claimer, uint claimed_value, address token_address ); event RefundSuccess( bytes32 id, address token_address, uint remaining_balance ); using SafeERC20 for IERC20; uint32 nonce; address public contract_creator; mapping(bytes32 => RedPacket) redpacket_by_id; string constant private magic = "Former NBA Commissioner David St"; // 32 bytes bytes32 private seed; uint256 constant MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; constructor() public { contract_creator = msg.sender; seed = keccak256(abi.encodePacked(magic, block.timestamp, contract_creator)); } // Inits a red packet instance // _token_type: 0 - ETH 1 - ERC20 function create_red_packet (bytes32 _hash, uint _number, bool _ifrandom, uint _duration, bytes32 _seed, string memory _message, string memory _name, uint _token_type, address _token_addr, uint _total_tokens) public payable { nonce ++; require(_total_tokens >= _number, "#tokens > #packets"); require(_number > 0, "At least 1 recipient"); require(_number < 256, "At most 255 recipients"); require(_token_type == 0 || _token_type == 1, "Unrecognizable token type"); if (_token_type == 0) require(msg.value >= _total_tokens, "No enough ETH"); else if (_token_type == 1) { require(IERC20(_token_addr).allowance(msg.sender, address(this)) >= _total_tokens, "No enough allowance"); IERC20(_token_addr).safeTransferFrom(msg.sender, address(this), _total_tokens); } bytes32 _id = keccak256(abi.encodePacked(msg.sender, block.timestamp, nonce, seed, _seed)); uint _random_type = _ifrandom ? 1 : 0; RedPacket storage redp = redpacket_by_id[_id]; redp.packed1 = wrap1(_hash, _total_tokens, _duration); redp.packed2 = wrap2(_token_addr, _number, _token_type, _random_type); emit CreationSuccess(_total_tokens, _id, _name, _message, msg.sender, block.timestamp, _token_addr); } // It takes the unhashed password and a hashed random seed generated from the user function claim(bytes32 id, string memory password, address _recipient, bytes32 validation) public returns (uint claimed) { RedPacket storage rp = redpacket_by_id[id]; address payable recipient = address(uint160(_recipient)); // Unsuccessful require (unbox(rp.packed1, 224, 32, "duration") > block.timestamp, "Expired"); uint total_number = unbox(rp.packed2, 239, 15, "total_number"); uint claimed_number = unbox(rp.packed2, 224, 15, "claimed_number"); require (claimed_number < total_number, "Out of stock"); require (uint256(keccak256(bytes(password))) >> 128 == unbox(rp.packed1, 0, 128, "hash"), "Wrong password"); require (validation == keccak256(toBytes(msg.sender)), "Validation failed"); uint256 claimed_tokens; uint256 token_type = unbox(rp.packed2, 254, 1, "token_type"); uint256 ifrandom = unbox(rp.packed2, 255, 1, "ifrandom"); uint256 remaining_tokens = unbox(rp.packed1, 128, 96, "remaining_tokens"); if (ifrandom == 1) { if (total_number - claimed_number == 1) claimed_tokens = remaining_tokens; else claimed_tokens = random(seed, nonce) % SafeMath.div(SafeMath.mul(remaining_tokens, 2), total_number - claimed_number); if (claimed_tokens == 0) claimed_tokens = 1; } else { if (total_number - claimed_number == 1) claimed_tokens = remaining_tokens; else claimed_tokens = SafeMath.div(remaining_tokens, (total_number - claimed_number)); } rp.packed1 = rewriteBox(rp.packed1, 128, 96, remaining_tokens - claimed_tokens, "remaining_tokens"); // Penalize greedy attackers by placing duplication check at the very last require(rp.claimed_list[msg.sender] == 0, "Already claimed"); rp.claimed_list[msg.sender] = claimed_tokens; rp.packed2 = rewriteBox(rp.packed2, 224, 15, claimed_number + 1, "claimed_number"); // Transfer the red packet after state changing if (token_type == 0) recipient.transfer(claimed_tokens); else if (token_type == 1) transfer_token(address(unbox(rp.packed2, 0, 160, "token_address")), address(this), recipient, claimed_tokens); // Claim success event emit ClaimSuccess(id, recipient, claimed_tokens, address(unbox(rp.packed2, 0, 160, "token_address"))); return claimed_tokens; } // Returns 1. remaining value 2. total number of red packets 3. claimed number of red packets function check_availability(bytes32 id) external view returns ( address token_address, uint balance, uint total, uint claimed, bool expired, uint256 claimed_amount) { RedPacket storage rp = redpacket_by_id[id]; return ( address(unbox(rp.packed2, 0, 160, "token_address")), unbox(rp.packed1, 128, 96, "remaining_tokens"), unbox(rp.packed2, 239, 15, "total_number"), unbox(rp.packed2, 224, 15, "claimed_number"), block.timestamp > unbox(rp.packed1, 224, 32, "duration"), rp.claimed_list[msg.sender] ); } function refund(bytes32 id) public { RedPacket storage rp = redpacket_by_id[id]; require(rp.packed1 != 0 && rp.packed2 != 0, "Already Refunded"); require(uint256(keccak256(abi.encodePacked(msg.sender)) >> 192) == unbox(rp.packed2, 160, 64, "msg.sender"), "Creator Only"); require(unbox(rp.packed1, 224, 32, "duration") <= block.timestamp, "Not expired yet"); uint256 remaining_tokens = unbox(rp.packed1, 128, 96, "remaining_tokens"); require(remaining_tokens != 0, "None left in the red packet"); uint256 token_type = unbox(rp.packed2, 254, 1, "token_type"); address token_address = address(unbox(rp.packed2, 0, 160, "token_address")); if (token_type == 0) { msg.sender.transfer(remaining_tokens); } else if (token_type == 1) { IERC20(token_address).approve(msg.sender, remaining_tokens); transfer_token(token_address, address(this), msg.sender, remaining_tokens); } emit RefundSuccess(id, token_address, remaining_tokens); // Gas Refund rp.packed1 = 0; rp.packed2 = 0; } //------------------------------------------------------------------ function box (uint16 position, uint16 size, uint256 data, string memory require_msg_prefix) internal pure returns (uint256 boxed) { string memory require_msg_suffix = " out of range BOX"; validRange(size, data, string(abi.encodePacked(require_msg_prefix, require_msg_suffix))); return data << (256 - size - position); } function unbox (uint256 base, uint16 position, uint16 size, string memory require_msg_prefix) internal pure returns (uint256 unboxed) { string memory require_msg_suffix = " out of range UNBOX"; validRange(256, base, string(abi.encodePacked(require_msg_prefix, require_msg_suffix))); return (base << position) >> (256 - size); } function validRange(uint16 size, uint256 data, string memory require_msg) internal pure { if (data > 2 ** uint256(size) - 1) require(false, require_msg); } function rewriteBox(uint256 _box, uint16 position, uint16 size, uint256 data, string memory require_msg_prefix) internal pure returns (uint256 boxed) { uint256 _boxData = box(position, size, data, require_msg_prefix); uint256 _mask = box(position, size, uint256(-1) >> (256 - size), require_msg_prefix); _box = (_box & ~_mask) | _boxData; return _box; } // Check the balance of the given token function transfer_token(address token_address, address sender_address, address recipient_address, uint amount) internal{ require(IERC20(token_address).balanceOf(sender_address) >= amount, "Balance too low"); IERC20(token_address).safeTransfer(recipient_address, amount); } // A boring wrapper function random(bytes32 _seed, uint32 nonce_rand) internal view returns (uint rand) { return uint(keccak256(abi.encodePacked(nonce_rand, msg.sender, _seed, block.timestamp))) + 1 ; } // https://ethereum.stackexchange.com/questions/884/how-to-convert-an-address-to-bytes-in-solidity // 695 gas consumed function toBytes(address a) internal pure returns (bytes memory b) { assembly { let m := mload(0x40) a := and(a, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a)) mstore(0x40, add(m, 52)) b := m } } function wrap1 (bytes32 _hash, uint _total_tokens, uint _duration) internal view returns (uint256 packed1) { uint256 _packed1 = 0; _packed1 |= box(0, 128, uint256(_hash) >> 128, "hash"); // hash = 128 bits (NEED TO CONFIRM THIS) _packed1 |= box(128, 96, _total_tokens, "total_tokens"); // total tokens = 80 bits = ~8 * 10^10 18 decimals _packed1 |= box(224, 32, (block.timestamp + _duration), "duration"); // expiration_time = 32 bits (until 2106) return _packed1; } function wrap2 (address _token_addr, uint _number, uint _token_type, uint _ifrandom) internal view returns (uint256 packed2) { uint256 _packed2 = 0; _packed2 |= box(0, 160, uint256(_token_addr), "token_address"); // token_address = 160 bits _packed2 |= box(160, 64, (uint256(keccak256(abi.encodePacked(msg.sender))) >> 192), "creator"); // creator.hash = 64 bit _packed2 |= box(224, 15, 0, "claimed_number"); // claimed_number = 14 bits 16384 _packed2 |= box(239, 15, _number, "total_number"); // total_number = 14 bits 16384 _packed2 |= box(254, 1, _token_type, "token_type"); // token_type = 1 bit 2 _packed2 |= box(255, 1, _ifrandom, "ifrandom"); // ifrandom = 1 bit 2 return _packed2; } }
claimed_number = 14 bits 16384
_packed2 |= box(224, 15, 0, "claimed_number");
978,087
[ 1, 14784, 329, 67, 2696, 273, 5045, 4125, 2872, 17295, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 2920, 329, 22, 5626, 3919, 12, 23622, 16, 4711, 16, 374, 16, 315, 14784, 329, 67, 2696, 8863, 10792, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x025992e54bB231DB0a594F9ba3CC7E673300d42E/sources/UniswapReward.sol
set fix time to start reward
{ require(_hasStart == false, "has started"); _hasStart = true; _startTime = startTime; update_initreward(); _rewardRate = _initReward.div(DURATION); _pros.mint(address(this), _initReward); _lastUpdateTime = _startTime; _periodFinish = _startTime.add(DURATION); emit RewardAdded(_initReward); }
4,251,652
[ 1, 542, 2917, 813, 358, 787, 19890, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 2583, 24899, 5332, 1685, 422, 629, 16, 315, 5332, 5746, 8863, 203, 3639, 389, 5332, 1685, 273, 638, 31, 203, 3639, 389, 1937, 950, 273, 8657, 31, 203, 3639, 1089, 67, 2738, 266, 2913, 5621, 203, 3639, 389, 266, 2913, 4727, 273, 389, 2738, 17631, 1060, 18, 2892, 12, 24951, 1769, 7010, 3639, 389, 685, 87, 18, 81, 474, 12, 2867, 12, 2211, 3631, 389, 2738, 17631, 1060, 1769, 203, 3639, 389, 2722, 1891, 950, 273, 389, 1937, 950, 31, 203, 3639, 389, 6908, 11641, 273, 389, 1937, 950, 18, 1289, 12, 24951, 1769, 203, 203, 3639, 3626, 534, 359, 1060, 8602, 24899, 2738, 17631, 1060, 1769, 203, 540, 202, 203, 540, 202, 203, 203, 203, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import "../../vault/contracts/interfaces/IVault.sol"; import "../../pool-utils/contracts/interfaces/IRelayedBasePool.sol"; import "../../solidity-utils/contracts/openzeppelin/IERC20.sol"; import "../../solidity-utils/contracts/math/Math.sol"; import "../../solidity-utils/contracts/math/FixedPoint.sol"; import "./IAssetManager.sol"; pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @title RewardsAssetManager * @dev RewardsAssetManager is owned by a single pool such that any * rewards received by the Asset Manager may be distributed to LPs * * Note: any behaviour to claim these rewards must be implemented in a derived contract */ abstract contract RewardsAssetManager is IAssetManager { using Math for uint256; IVault private immutable _vault; IERC20 private immutable _token; // RewardsAssetManager manages a single Pool, to which it allocates all rewards that it receives. bytes32 private _poolId; struct InvestmentConfig { uint64 targetPercentage; uint64 upperCriticalPercentage; uint64 lowerCriticalPercentage; } InvestmentConfig private _config; event InvestmentConfigSet(uint64 targetPercentage, uint64 lowerCriticalPercentage, uint64 upperCriticalPercentage); constructor( IVault vault, bytes32 poolId, IERC20 token ) { token.approve(address(vault), type(uint256).max); _vault = vault; _poolId = poolId; _token = token; } modifier onlyPoolContract() { require(msg.sender == getPoolAddress(), "Only callable by pool"); _; } modifier onlyPoolRebalancer() { require( msg.sender == address(IRelayedBasePool(getPoolAddress()).getRelayer()), "Only callable by authorized rebalancer" ); _; } modifier withCorrectPool(bytes32 pId) { require(pId == _poolId, "SinglePoolAssetManager called with incorrect poolId"); _; } function _initialize(bytes32 pId) internal { require(!isInitialized(), "Already initialised"); require(pId != bytes32(0), "Pool id cannot be empty"); _poolId = pId; } function getVault() public view returns (IVault) { return _vault; } function getPoolId() public view returns (bytes32) { return _poolId; } function getPoolAddress() public view returns (address) { return address(uint256(_poolId) >> (12 * 8)); } function isInitialized() public view returns (bool) { return getPoolId() != bytes32(0); } function getToken() public view override returns (IERC20) { return _token; } // Investment configuration function maxInvestableBalance(bytes32 pId) public view override withCorrectPool(pId) returns (int256) { return _maxInvestableBalance(_getAUM()); } function _maxInvestableBalance(uint256 aum) internal view returns (int256) { (uint256 poolCash, , , ) = getVault().getPoolTokenInfo(_poolId, getToken()); // Calculate the managed portion of funds locally as the Vault is unaware of returns return int256(FixedPoint.mulDown(poolCash.add(aum), _config.targetPercentage)) - int256(aum); } // Reporting function updateBalanceOfPool(bytes32 pId) public override withCorrectPool(pId) { uint256 managedBalance = _getAUM(); IVault.PoolBalanceOp memory transfer = IVault.PoolBalanceOp( IVault.PoolBalanceOpKind.UPDATE, pId, getToken(), managedBalance ); IVault.PoolBalanceOp[] memory ops = new IVault.PoolBalanceOp[](1); ops[0] = (transfer); getVault().managePoolBalance(ops); } // Deposit / Withdraw /** * @dev Transfers capital into the asset manager, and then invests it * @param amount - the amount of tokens being deposited */ function _capitalIn(uint256 amount) private { uint256 aum = _getAUM(); IVault.PoolBalanceOp[] memory ops = new IVault.PoolBalanceOp[](2); // Update the vault with new managed balance accounting for returns ops[0] = IVault.PoolBalanceOp(IVault.PoolBalanceOpKind.UPDATE, _poolId, getToken(), aum); // Pull funds from the vault ops[1] = IVault.PoolBalanceOp(IVault.PoolBalanceOpKind.WITHDRAW, _poolId, getToken(), amount); getVault().managePoolBalance(ops); _invest(amount, aum); } /** * @notice Divests capital back to the asset manager and then sends it to the vault * @param amount - the amount of tokens to withdraw to the vault */ function _capitalOut(uint256 amount) private { uint256 aum = _getAUM(); uint256 tokensOut = _divest(amount, aum); IVault.PoolBalanceOp[] memory ops = new IVault.PoolBalanceOp[](2); // Update the vault with new managed balance accounting for returns ops[0] = IVault.PoolBalanceOp(IVault.PoolBalanceOpKind.UPDATE, _poolId, getToken(), aum); // Send funds back to the vault ops[1] = IVault.PoolBalanceOp(IVault.PoolBalanceOpKind.DEPOSIT, _poolId, getToken(), tokensOut); getVault().managePoolBalance(ops); } /** * @dev Invests capital inside the asset manager * @param amount - the amount of tokens being deposited * @param aum - the assets under management * @return the number of tokens that were deposited */ function _invest(uint256 amount, uint256 aum) internal virtual returns (uint256); /** * @dev Divests capital back to the asset manager * @param amount - the amount of tokens being withdrawn * @return the number of tokens to return to the vault */ function _divest(uint256 amount, uint256 aum) internal virtual returns (uint256); function getAUM(bytes32 pId) public view virtual override withCorrectPool(pId) returns (uint256) { return _getAUM(); } function _getAUM() internal view virtual returns (uint256); function setConfig(bytes32 pId, bytes memory rawConfig) external override withCorrectPool(pId) onlyPoolContract { InvestmentConfig memory config = abi.decode(rawConfig, (InvestmentConfig)); require( config.upperCriticalPercentage <= FixedPoint.ONE, "Upper critical level must be less than or equal to 100%" ); require( config.targetPercentage <= config.upperCriticalPercentage, "Target must be less than or equal to upper critical level" ); require( config.lowerCriticalPercentage <= config.targetPercentage, "Lower critical level must be less than or equal to target" ); _config = config; emit InvestmentConfigSet( config.targetPercentage, config.lowerCriticalPercentage, config.upperCriticalPercentage ); } function getInvestmentConfig(bytes32 pId) external view withCorrectPool(pId) returns (InvestmentConfig memory) { return _config; } function getPoolBalances(bytes32 pId) public view override withCorrectPool(pId) returns (uint256 poolCash, uint256 poolManaged) { (poolCash, poolManaged) = _getPoolBalances(_getAUM()); } function _getPoolBalances(uint256 aum) internal view returns (uint256 poolCash, uint256 poolManaged) { (poolCash, , , ) = getVault().getPoolTokenInfo(_poolId, getToken()); // Calculate the managed portion of funds locally as the Vault is unaware of returns poolManaged = aum; } /** * @notice Determines whether the pool should rebalance given the provided balances */ function shouldRebalance(uint256 cash, uint256 managed) public view override returns (bool) { uint256 investedPercentage = cash.mul(FixedPoint.ONE).divDown(cash.add(managed)); InvestmentConfig memory config = _config; return investedPercentage > config.upperCriticalPercentage || investedPercentage < config.lowerCriticalPercentage; } /** * @notice Rebalances funds between pool and asset manager to maintain target investment percentage. */ function _rebalance( bytes32 /*pId*/ ) internal { uint256 aum = _getAUM(); (uint256 poolCash, uint256 poolManaged) = _getPoolBalances(aum); InvestmentConfig memory config = _config; uint256 targetInvestment = FixedPoint.mulDown(poolCash + poolManaged, config.targetPercentage); if (targetInvestment > poolManaged) { // Pool is under-invested so add more funds uint256 rebalanceAmount = targetInvestment - poolManaged; _capitalIn(rebalanceAmount); } else { // Pool is over-invested so remove some funds uint256 rebalanceAmount = poolManaged - targetInvestment; _capitalOut(rebalanceAmount); } emit Rebalance(_poolId); } function rebalance(bytes32 pId, bool force) external override withCorrectPool(pId) { if (force) { _rebalance(pId); } else { (uint256 poolCash, uint256 poolManaged) = _getPoolBalances(_getAUM()); if (shouldRebalance(poolCash, poolManaged)) { _rebalance(pId); } } } /** * @notice allows an authorized rebalancer to remove capital to facilitate large withdrawals * @param pId - the poolId of the pool to withdraw funds back to * @param amount - the amount of tokens to withdraw back to the pool */ function capitalOut(bytes32 pId, uint256 amount) external override withCorrectPool(pId) onlyPoolRebalancer { _capitalOut(amount); } }
* @notice allows an authorized rebalancer to remove capital to facilitate large withdrawals @param pId - the poolId of the pool to withdraw funds back to @param amount - the amount of tokens to withdraw back to the pool/
function capitalOut(bytes32 pId, uint256 amount) external override withCorrectPool(pId) onlyPoolRebalancer { _capitalOut(amount); }
2,501,068
[ 1, 5965, 87, 392, 10799, 283, 18770, 358, 1206, 12872, 358, 5853, 330, 305, 340, 7876, 598, 9446, 1031, 225, 293, 548, 300, 326, 2845, 548, 434, 326, 2845, 358, 598, 9446, 284, 19156, 1473, 358, 225, 3844, 300, 326, 3844, 434, 2430, 358, 598, 9446, 1473, 358, 326, 2845, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12872, 1182, 12, 3890, 1578, 293, 548, 16, 2254, 5034, 3844, 13, 3903, 3849, 598, 16147, 2864, 12, 84, 548, 13, 1338, 2864, 426, 18770, 288, 203, 3639, 389, 5909, 7053, 1182, 12, 8949, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.5; import "./interfaces/ICToken.sol"; import "./interfaces/ITrigger.sol"; /** * @notice Defines a trigger that is toggled if the Compound exchange rate decreases between consecutive checks. Under * normal operation, this value should only increase */ contract CompoundExchangeRate is ITrigger { uint256 internal constant WAD = 10**18; /// @notice Address of CToken market protected by this trigger ICToken public immutable market; /// @notice Last read exchangeRateStored uint256 public lastExchangeRate; /// @dev Due to rounding errors in the Compound Protocol, the exchangeRateStored may occassionally decrease by small /// amount even when nothing is wrong. A large, very conservative tolerance is applied to ensure we do not /// accidentally trigger in these cases. Even though a smaller tolerance would likely be ok, a non-trivial exploit /// will most likely cause the exchangeRateStored to decrease by more than 10,000 wei uint256 public constant tolerance = 10000; // 10,000 wei tolerance /** * @param _market Is the address of the Compound market this trigger should protect * @dev For definitions of other constructor parameters, see ITrigger.sol */ constructor( string memory _name, string memory _symbol, string memory _description, uint256[] memory _platformIds, address _recipient, address _market ) ITrigger(_name, _symbol, _description, _platformIds, _recipient) { // Set market market = ICToken(_market); // Save current exchange rate (immutables can't be read at construction, so we don't use `market` directly) lastExchangeRate = ICToken(_market).exchangeRateStored(); } /** * @dev Checks if a CToken's exchange rate decreased. The exchange rate should never decrease, but may occasionally * decrease slightly due to rounding errors * @return True if trigger condition occured (i.e. exchange rate decreased), false otherwise */ function checkTriggerCondition() internal override returns (bool) { // Read this blocks exchange rate uint256 _currentExchangeRate = market.exchangeRateStored(); // Check if current exchange rate is below current exchange rate, accounting for tolerance bool _status = _currentExchangeRate < (lastExchangeRate - tolerance); // Save the new exchange rate lastExchangeRate = _currentExchangeRate; // Return status return _status; } } pragma solidity ^0.8.5; interface ICToken { function totalReserves() external view returns (uint256); function totalBorrows() external view returns (uint256); function totalSupply() external view returns (uint256); function getCash() external view returns (uint256); function exchangeRateStored() external view returns (uint256); } pragma solidity ^0.8.5; /** * @notice Abstract contract for creating or interacting with a Trigger contract * @dev All trigger contracts created must inerit from this contract and conform to this interface */ abstract contract ITrigger { /// @notice Trigger name, analgous to an ERC-20 token's name string public name; /// @notice Trigger symbol, analgous to an ERC-20 token's symbol string public symbol; /// @notice Trigger description string public description; /// @notice Array of IDs of platforms covered by this trigger uint256[] public platformIds; /// @notice Returns address of recipient who receives subsidies for creating a protection market using this trigger address public immutable recipient; /// @notice Returns true if trigger condition has been met bool public isTriggered; /// @notice Emitted when the trigger is activated event TriggerActivated(); /** * @notice Returns array of IDs, where each ID corresponds to a platform covered by this trigger * @dev See documentation for mapping of ID numbers to platforms */ function getPlatformIds() external view returns (uint256[] memory) { return platformIds; } /** * @dev Executes trigger-specific logic to check if market has been triggered * @return True if trigger condition occured, false otherwise */ function checkTriggerCondition() internal virtual returns (bool); /** * @notice Checks trigger condition, sets isTriggered flag to true if condition is met, and returns the trigger status * @return True if trigger condition occured, false otherwise */ function checkAndToggleTrigger() external returns (bool) { // Return true if trigger already toggled if (isTriggered) return true; // Return false if market has not been triggered if (!checkTriggerCondition()) return false; // Otherwise, market has been triggered emit TriggerActivated(); isTriggered = true; return isTriggered; } constructor( string memory _name, string memory _symbol, string memory _description, uint256[] memory _platformIds, address _recipient ) { name = _name; description = _description; symbol = _symbol; platformIds = _platformIds; recipient = _recipient; } } pragma solidity ^0.8.5; import "./interfaces/IYVaultV2.sol"; import "./interfaces/ITrigger.sol"; /** * @notice Defines a trigger that is toggled if the price per share for the V2 yVault decreases between consecutive * checks. Under normal operation, this value should only increase */ contract YearnV2SharePrice is ITrigger { uint256 internal constant WAD = 10**18; /// @notice Vault this trigger is for IYVaultV2 public immutable market; /// @notice Last read pricePerShare uint256 public lastPricePerShare; /// @dev In Yearn V2 vaults, the pricePerShare decreases immediately after a harvest, and typically ramps up over the /// next six hours. Therefore we cannot simply check that the pricePerShare increases. Instead, we consider the vault /// triggered if the pricePerShare drops by more than 50% from it's previous value. This is conservative, but /// previous Yearn bugs resulted in pricePerShare drops of 0.5% – 10%, and were only temporary drops with users able /// to be made whole. Therefore this trigger requires a large 50% drop to minimize false positives. The tolerance /// is defined such that we trigger if: currentPricePerShare < lastPricePerShare * tolerance / 1e18. This means /// if you want to trigger after a 20% drop, you should set the tolerance to 1e18 - 0.2e18 = 0.8e18 = 8e17 uint256 public constant tolerance = 5e17; // 50%, represented on a scale where 1e18 = 100% /** * @param _market Is the address of the Yearn V2 vault this trigger should protect * @dev For definitions of other constructor parameters, see ITrigger.sol */ constructor( string memory _name, string memory _symbol, string memory _description, uint256[] memory _platformIds, address _recipient, address _market ) ITrigger(_name, _symbol, _description, _platformIds, _recipient) { // Set vault market = IYVaultV2(_market); // Save current share price (immutables can't be read at construction, so we don't use `market` directly) lastPricePerShare = IYVaultV2(_market).pricePerShare(); } /** * @dev Checks the yVault pricePerShare */ function checkTriggerCondition() internal override returns (bool) { // Read this blocks share price uint256 _currentPricePerShare = market.pricePerShare(); // Check if current share price is below current share price, accounting for tolerance bool _status = _currentPricePerShare < ((lastPricePerShare * tolerance) / 1e18); // Save the new share price lastPricePerShare = _currentPricePerShare; // Return status return _status; } } pragma solidity ^0.8.5; interface IYVaultV2 { function totalSupply() external view returns (uint256); function pricePerShare() external view returns (uint256); } pragma solidity ^0.8.6; import "./interfaces/ICurvePool.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/ITrigger.sol"; import "./interfaces/IYVaultV2.sol"; /** * @notice Defines a trigger that is toggled if any of the following conditions occur: * 1. The price per share for the V2 yVault significantly decreases between consecutive checks. Under normal * operation, this value should only increase. A decrease indicates something is wrong with the Yearn vault * 2. Curve Tricrypto token balances are significantly lower than what the pool expects them to be * 3. Curve Tricrypto virtual price drops significantly * @dev This trigger is for Yearn V2 Vaults that use a Curve pool with two underlying tokens */ contract YearnCrvTwoTokens is ITrigger { // --- Tokens --- // Token addresses IERC20 internal immutable token0; IERC20 internal immutable token1; // --- Tolerances --- /// @dev Scale used to define percentages. Percentages are defined as tolerance / scale uint256 public constant scale = 1000; /// @dev In Yearn V2 vaults, the pricePerShare decreases immediately after a harvest, and typically ramps up over the /// next six hours. Therefore we cannot simply check that the pricePerShare increases. Instead, we consider the vault /// triggered if the pricePerShare drops by more than 50% from it's previous value. This is conservative, but /// previous Yearn bugs resulted in pricePerShare drops of 0.5% – 10%, and were only temporary drops with users able /// to be made whole. Therefore this trigger requires a large 50% drop to minimize false positives. The tolerance /// is defined such that we trigger if: currentPricePerShare < lastPricePerShare * tolerance / 1000. This means /// if you want to trigger after a 20% drop, you should set the tolerance to 1000 - 200 = 800 uint256 public constant vaultTol = scale - 500; // 50% drop, represented on a scale where 1000 = 100% /// @dev Consider trigger toggled if Curve virtual price drops by more than this percentage. uint256 public constant virtualPriceTol = scale - 500; // 50% drop /// @dev Consider trigger toggled if Curve internal balances are lower than true balances by this percentage uint256 public constant balanceTol = scale - 500; // 50% drop // --- Trigger Data --- /// @notice Yearn vault this trigger is for IYVaultV2 public immutable vault; /// @notice Curve tricrypto pool used as a strategy by `vault` ICurvePool public immutable curve; /// @notice Last read pricePerShare uint256 public lastPricePerShare; /// @notice Last read curve virtual price uint256 public lastVirtualPrice; // --- Constructor --- /** * @param _vault Address of the Yearn V2 vault this trigger should protect * @param _curve Address of the Curve Tricrypto pool uses by the above Yearn vault * @dev For definitions of other constructor parameters, see ITrigger.sol */ constructor( string memory _name, string memory _symbol, string memory _description, uint256[] memory _platformIds, address _recipient, address _vault, address _curve ) ITrigger(_name, _symbol, _description, _platformIds, _recipient) { // Set trigger data vault = IYVaultV2(_vault); curve = ICurvePool(_curve); token0 = IERC20(ICurvePool(_curve).coins(0)); token1 = IERC20(ICurvePool(_curve).coins(1)); // Save current values (immutables can't be read at construction, so we don't use `vault` or `curve` directly) lastPricePerShare = IYVaultV2(_vault).pricePerShare(); lastVirtualPrice = ICurvePool(_curve).get_virtual_price(); } // --- Trigger condition --- /** * @dev Checks the yVault pricePerShare */ function checkTriggerCondition() internal override returns (bool) { // Read this blocks share price and virtual price uint256 _currentPricePerShare = vault.pricePerShare(); uint256 _currentVirtualPrice = curve.get_virtual_price(); // Check trigger conditions. We could check one at a time and return as soon as one is true, but it is convenient // to have the data that caused the trigger saved into the state, so we don't do that bool _statusVault = _currentPricePerShare < ((lastPricePerShare * vaultTol) / scale); bool _statusVirtualPrice = _currentVirtualPrice < ((lastVirtualPrice * virtualPriceTol) / scale); bool _statusBalances = checkCurveBalances(); // Save the new data lastPricePerShare = _currentPricePerShare; lastVirtualPrice = _currentVirtualPrice; // Return status return _statusVault || _statusVirtualPrice || _statusBalances; } /** * @dev Checks if the Curve internal balances are significantly lower than the true balances * @return True if balances are out of tolerance and trigger should be toggled */ function checkCurveBalances() internal view returns (bool) { return (token0.balanceOf(address(curve)) < ((curve.balances(0) * balanceTol) / scale)) || (token1.balanceOf(address(curve)) < ((curve.balances(1) * balanceTol) / scale)); } } pragma solidity ^0.8.5; interface ICurvePool { /// @notice Computes current virtual price function get_virtual_price() external view returns (uint256); /// @notice Cached virtual price, used internally function virtual_price() external view returns (uint256); /// @notice Current full profit function xcp_profit() external view returns (uint256); /// @notice Full profit at last claim of admin fees function xcp_profit_a() external view returns (uint256); /// @notice Pool admin fee function admin_fee() external view returns (uint256); /// @notice Returns balance for the token defined by the provided index function balances(uint256 index) external view returns (uint256); /// @notice Returns the address of the token for the provided index function coins(uint256 index) external view returns (address); } pragma solidity ^0.8.5; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.8.5; import "./interfaces/ICurvePool.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/ITrigger.sol"; import "./interfaces/IYVaultV2.sol"; /** * @notice Defines a trigger that is toggled if any of the following conditions occur: * 1. The price per share for the V2 yVault significantly decreases between consecutive checks. Under normal * operation, this value should only increase. A decrease indicates something is wrong with the Yearn vault * 2. Curve Tricrypto token balances are significantly lower than what the pool expects them to be * 3. Curve Tricrypto virtual price drops significantly */ contract YearnCrvTricrypto is ITrigger { // --- Tokens --- // Token addresses IERC20 internal constant usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 internal constant wbtc = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); IERC20 internal constant weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // Token indices in Curve pool arrays uint256 internal constant usdtIndex = 0; uint256 internal constant wbtcIndex = 1; uint256 internal constant wethIndex = 2; // --- Tolerances --- /// @dev Scale used to define percentages. Percentages are defined as tolerance / scale uint256 public constant scale = 1000; /// @dev In Yearn V2 vaults, the pricePerShare decreases immediately after a harvest, and typically ramps up over the /// next six hours. Therefore we cannot simply check that the pricePerShare increases. Instead, we consider the vault /// triggered if the pricePerShare drops by more than 50% from it's previous value. This is conservative, but /// previous Yearn bugs resulted in pricePerShare drops of 0.5% – 10%, and were only temporary drops with users able /// to be made whole. Therefore this trigger requires a large 50% drop to minimize false positives. The tolerance /// is defined such that we trigger if: currentPricePerShare < lastPricePerShare * tolerance / 1000. This means /// if you want to trigger after a 20% drop, you should set the tolerance to 1000 - 200 = 800 uint256 public constant vaultTol = scale - 500; // 50% drop, represented on a scale where 1000 = 100% /// @dev Consider trigger toggled if Curve virtual price drops by this percentage. Similar to the Yearn V2 price /// per share, the virtual price is expected to decrease during normal operation, but it can never decrease by /// more than 50% during normal operation. Therefore we check for a 51% drop uint256 public constant virtualPriceTol = scale - 510; // 51% drop, since 1000-510=490, and multiplying by 0.49 = 51% drop /// @dev Consider trigger toggled if Curve internal balances are lower than true balances by this percentage uint256 public constant balanceTol = scale - 500; // 50% drop // --- Trigger Data --- /// @notice Yearn vault this trigger is for IYVaultV2 public immutable vault; /// @notice Curve tricrypto pool used as a strategy by `vault` ICurvePool public immutable curve; /// @notice Last read pricePerShare uint256 public lastPricePerShare; /// @notice Last read curve virtual price uint256 public lastVirtualPrice; // --- Constructor --- /** * @param _vault Address of the Yearn V2 vault this trigger should protect * @param _curve Address of the Curve Tricrypto pool uses by the above Yearn vault * @dev For definitions of other constructor parameters, see ITrigger.sol */ constructor( string memory _name, string memory _symbol, string memory _description, uint256[] memory _platformIds, address _recipient, address _vault, address _curve ) ITrigger(_name, _symbol, _description, _platformIds, _recipient) { // Set vault vault = IYVaultV2(_vault); curve = ICurvePool(_curve); // Save current values (immutables can't be read at construction, so we don't use `vault` or `curve` directly) lastPricePerShare = IYVaultV2(_vault).pricePerShare(); lastVirtualPrice = ICurvePool(_curve).get_virtual_price(); } // --- Trigger condition --- /** * @dev Checks the yVault pricePerShare */ function checkTriggerCondition() internal override returns (bool) { // Read this blocks share price and virtual price uint256 _currentPricePerShare = vault.pricePerShare(); uint256 _currentVirtualPrice = curve.get_virtual_price(); // Check trigger conditions. We could check one at a time and return as soon as one is true, but it is convenient // to have the data that caused the trigger saved into the state, so we don't do that bool _statusVault = _currentPricePerShare < ((lastPricePerShare * vaultTol) / scale); bool _statusVirtualPrice = _currentVirtualPrice < ((lastVirtualPrice * virtualPriceTol) / scale); bool _statusBalances = checkCurveBalances(); // Save the new data lastPricePerShare = _currentPricePerShare; lastVirtualPrice = _currentVirtualPrice; // Return status return _statusVault || _statusVirtualPrice || _statusBalances; } /** * @dev Checks if the Curve internal balances are significantly lower than the true balances * @return True if balances are out of tolerance and trigger should be toggled */ function checkCurveBalances() internal view returns (bool) { return (usdt.balanceOf(address(curve)) < ((curve.balances(usdtIndex) * balanceTol) / scale)) || (wbtc.balanceOf(address(curve)) < ((curve.balances(wbtcIndex) * balanceTol) / scale)) || (weth.balanceOf(address(curve)) < ((curve.balances(wethIndex) * balanceTol) / scale)); } } pragma solidity ^0.8.5; import "../interfaces/ICurvePool.sol"; /** * @notice Mock Curve Tricrypto pool, containing the same interface but configurable parameters for testing */ contract MockCrvTricrypto is ICurvePool { uint256 public override get_virtual_price; uint256 public override virtual_price; uint256 public override xcp_profit; uint256 public override xcp_profit_a; uint256 public override admin_fee; constructor() { // Initializing the values based on the actual values on 2021-07-15 get_virtual_price = 1001041521509972624; virtual_price = 1001041521509972624; xcp_profit = 1001056295181177762; xcp_profit_a = 1001035776942422073; admin_fee = 5000000000; } /** * @notice Set the pricePerShare * @param _get_virtual_price New get_virtual_price value */ function set(uint256 _get_virtual_price) external { get_virtual_price = _get_virtual_price; } function balances(uint256 index) external pure override returns (uint256) { require(index == 0 || index == 1 || index == 2, "bad index"); return 1; } function coins(uint256 index) external pure override returns (address) { // This method is not used and is just to satisfy the interface this contract inherits from index; // silence compiler warning about unused variables return address(0); } } pragma solidity ^0.8.6; import "./interfaces/ISaddlePool.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/ITrigger.sol"; import "./interfaces/IYVaultV2.sol"; /** * @notice Defines a trigger that is toggled if any of the following conditions occur: * 1. Saddle token balances are significantly lower than what the pool expects them to be * 2. Saddle virtual price drops significantly * @dev This trigger is for Yearn V2 Vaults that use a Saddle pool with two underlying tokens */ contract SaddleThreeTokens is ITrigger { // --- Tokens --- // Token addresses IERC20 internal immutable token0; IERC20 internal immutable token1; IERC20 internal immutable token2; // --- Tolerances --- /// @dev Scale used to define percentages. Percentages are defined as tolerance / scale uint256 public constant scale = 1000; /// @dev Consider trigger toggled if Saddle virtual price drops by more than this percentage. uint256 public constant virtualPriceTol = scale - 500; // 50% drop /// @dev Consider trigger toggled if Saddle internal balances are lower than true balances by this percentage uint256 public constant balanceTol = scale - 500; // 50% drop // --- Trigger Data --- /// @notice Saddle pool to protect ISaddlePool public immutable saddle; /// @notice Last read Saddle virtual price uint256 public lastVirtualPrice; // --- Constructor --- /** * @param _saddle Address of the Saddle pool, must contain three underlying tokens * @dev For definitions of other constructor parameters, see ITrigger.sol */ constructor( string memory _name, string memory _symbol, string memory _description, uint256[] memory _platformIds, address _recipient, address _saddle ) ITrigger(_name, _symbol, _description, _platformIds, _recipient) { // Set trigger data saddle = ISaddlePool(_saddle); token0 = IERC20(ISaddlePool(_saddle).getToken(0)); token1 = IERC20(ISaddlePool(_saddle).getToken(1)); token2 = IERC20(ISaddlePool(_saddle).getToken(2)); // Save current values (immutables can't be read at construction, so we don't use `vault` or `saddle` directly) lastVirtualPrice = ISaddlePool(_saddle).getVirtualPrice(); } // --- Trigger condition --- /** * @dev Checks the yVault pricePerShare */ function checkTriggerCondition() internal override returns (bool) { // Read this blocks share price and virtual price uint256 _currentVirtualPrice = saddle.getVirtualPrice(); // Check trigger conditions. We could check one at a time and return as soon as one is true, but it is convenient // to have the data that caused the trigger saved into the state, so we don't do that bool _statusVirtualPrice = _currentVirtualPrice < ((lastVirtualPrice * virtualPriceTol) / scale); bool _statusBalances = checkSaddleBalances(); // Save the new data lastVirtualPrice = _currentVirtualPrice; // Return status return _statusVirtualPrice || _statusBalances; } /** * @dev Checks if the Saddle internal balances are significantly lower than the true balances * @return True if balances are out of tolerance and trigger should be toggled */ function checkSaddleBalances() internal view returns (bool) { return (token0.balanceOf(address(saddle)) < ((saddle.getTokenBalance(0) * balanceTol) / scale)) || (token1.balanceOf(address(saddle)) < ((saddle.getTokenBalance(1) * balanceTol) / scale)) || (token2.balanceOf(address(saddle)) < ((saddle.getTokenBalance(2) * balanceTol) / scale)); } } pragma solidity ^0.8.5; interface ISaddlePool { /// @notice Computes current virtual price function getVirtualPrice() external view returns (uint256); /// @notice Returns balance for the token defined by the provided index function getTokenBalance(uint8 index) external view returns (uint256); /// @notice Returns the address of the token for the provided index function getToken(uint8 index) external view returns (address); } pragma solidity ^0.8.5; import "../interfaces/IYVaultV2.sol"; /** * @notice Mock yVault, implemented the same way as a Yearn vault, but with configurable parameters for testing */ contract MockYVaultV2 is IYVaultV2 { uint256 public override pricePerShare; uint256 public underlyingDecimals = 6; // decimals of USDC underlying uint256 public override totalSupply; // not used, but needed so this is not an abstract contract constructor() { // Initializing the values based on the yUSDC values on 2021-06-03 pricePerShare = 1058448; } /** * @notice Set the pricePerShare * @param _pricePerShare New pricePerShare value */ function set(uint256 _pricePerShare) external { pricePerShare = _pricePerShare; } } pragma solidity ^0.8.5; import "../interfaces/ITrigger.sol"; /** * @notice Mock MockCozyToken, for testing the return value of a trigger's `checkAndToggleTrigger()` method */ contract MockCozyToken { /// @notice Trigger contract address address public immutable trigger; /// @notice In a real Cozy Token, this state variable is toggled when trigger event occues bool public isTriggered; constructor(address _trigger) { // Set the trigger address in the constructor trigger = _trigger; } /** * @notice Sufficiently mimics the implementation of a Cozy Token's `checkAndToggleTriggerInternal()` method */ function checkAndToggleTrigger() external { isTriggered = ITrigger(trigger).checkAndToggleTrigger(); } } pragma solidity ^0.8.5; import "./interfaces/ITrigger.sol"; contract MockTrigger is ITrigger { /// @notice If true, checkAndToggleTrigger will toggle the trigger on its next call bool public shouldToggle; constructor( string memory _name, string memory _symbol, string memory _description, uint256[] memory _platformIds, address _recipient, bool _shouldToggle ) ITrigger(_name, _symbol, _description, _platformIds, _recipient) { shouldToggle = _shouldToggle; // Verify market is not already triggered. require(!checkTriggerCondition(), "Already triggered"); } /** * @notice Special function for this mock trigger to set whether or not the trigger should toggle */ function setShouldToggle(bool _shouldToggle) external { require(!isTriggered, "Cannot set after trigger event"); shouldToggle = _shouldToggle; } /** * @notice Returns true if the market has been triggered, false otherwise */ function checkTriggerCondition() internal view override returns (bool) { return shouldToggle; } } pragma solidity ^0.8.5; import "../interfaces/ICToken.sol"; /** * @notice Mock CToken, implemented the same way as a Compound CToken, but with configurable parameters for testing */ contract MockCToken is ICToken { uint256 public override totalReserves; uint256 public override totalBorrows; uint256 public override totalSupply; uint256 public override exchangeRateStored; uint256 internal cash; // this is the balanceOf the underlying ERC20/ETH uint256 public underlyingDecimals = 6; // decimals of USDC underlying constructor() { // Initializing the values based on the cUSDC values on 2021-05-10 (around block 12,409,320) totalReserves = 5359893964073; // units of USDC totalBorrows = 3681673803163527; // units of USDC totalSupply = 20287132947568793418; // units of cUSDC exchangeRateStored = 219815665774648; // units of 10^(18 + underlyingDecimals - 8) cash = 783115726329188; // units of USDC } /** * @notice Set the value of a parameter * @param _name Name of the variable to set * @param _value Value to set the parameter to */ function set(bytes32 _name, uint256 _value) external { if (_name == "totalReserves") totalReserves = _value; if (_name == "totalBorrows") totalBorrows = _value; if (_name == "totalSupply") totalSupply = _value; if (_name == "exchangeRateStored") exchangeRateStored = _value; if (_name == "cash") cash = _value; } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view override returns (uint256) { return cash; } }
* @notice Set the pricePerShare @param _pricePerShare New pricePerShare value/
function set(uint256 _pricePerShare) external { pricePerShare = _pricePerShare; }
6,992,413
[ 1, 694, 326, 6205, 2173, 9535, 225, 389, 8694, 2173, 9535, 1166, 6205, 2173, 9535, 460, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 444, 12, 11890, 5034, 389, 8694, 2173, 9535, 13, 3903, 288, 203, 565, 6205, 2173, 9535, 273, 389, 8694, 2173, 9535, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xFcBfDa4Fa65f2a57cDa3B2d50A7244073bFd1f35/sources/PandaHead-Solo-2.sol
* @dev Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Clear approvals Clear metadata (if any)
function _burn(uint256 tokenId) internal virtual { _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); }
692,233
[ 1, 9378, 28599, 1375, 2316, 548, 8338, 1021, 23556, 353, 16054, 1347, 326, 1147, 353, 18305, 329, 18, 29076, 30, 300, 1375, 2316, 548, 68, 1297, 1005, 18, 7377, 1282, 279, 288, 5912, 97, 871, 18, 19, 10121, 6617, 4524, 10121, 1982, 261, 430, 1281, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 70, 321, 12, 11890, 5034, 1147, 548, 13, 2713, 5024, 288, 203, 7010, 3639, 389, 5771, 1345, 5912, 12, 8443, 16, 1758, 12, 20, 3631, 1147, 548, 1769, 203, 7010, 3639, 389, 12908, 537, 12, 2867, 12, 20, 3631, 1147, 548, 1769, 203, 7010, 3639, 309, 261, 3890, 24899, 2316, 1099, 2520, 63, 2316, 548, 65, 2934, 2469, 480, 374, 13, 288, 203, 5411, 1430, 389, 2316, 1099, 2520, 63, 2316, 548, 15533, 203, 3639, 289, 203, 7010, 3639, 389, 4505, 5157, 63, 8443, 8009, 4479, 12, 2316, 548, 1769, 203, 7010, 3639, 389, 2316, 5460, 414, 18, 4479, 12, 2316, 548, 1769, 203, 7010, 3639, 3626, 12279, 12, 8443, 16, 1758, 12, 20, 3631, 1147, 548, 1769, 203, 565, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x72AcF4c2d3dAA05d37eFCbaa90B8B6d4750919aC/sources/contracts/AtomicAntz.sol
* @dev Emitted when `saleActive` switches./
event SalesFlipped( bool saleActive );
12,294,094
[ 1, 1514, 11541, 1347, 1375, 87, 5349, 3896, 68, 28216, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 871, 25996, 28535, 1845, 12, 1426, 272, 5349, 3896, 11272, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x31275e27b38b74828bA886f0C63e494BCACA369c/sources/Spores.sol
* @notice Delegates votes from signatory to `delegatee` @param delegatee The address to delegate votes to @param nonce The contract state required to match the signature @param expiry The time at which to expire the signature @param v The recovery byte of the signature @param r Half of the ECDSA signature pair @param s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Spores::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Spores::delegateBySig: invalid nonce"); require(now <= expiry, "Spores::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
15,962,565
[ 1, 15608, 815, 19588, 628, 1573, 8452, 358, 1375, 22216, 73, 68, 225, 7152, 73, 1021, 1758, 358, 7152, 19588, 358, 225, 7448, 1021, 6835, 919, 1931, 358, 845, 326, 3372, 225, 10839, 1021, 813, 622, 1492, 358, 6930, 326, 3372, 225, 331, 1021, 11044, 1160, 434, 326, 3372, 225, 436, 670, 6186, 434, 326, 7773, 19748, 3372, 3082, 225, 272, 670, 6186, 434, 326, 7773, 19748, 3372, 3082, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7152, 858, 8267, 12, 203, 3639, 1758, 7152, 73, 16, 203, 3639, 2254, 7448, 16, 203, 3639, 2254, 10839, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 565, 262, 203, 3639, 3903, 203, 565, 288, 203, 3639, 1731, 1578, 2461, 6581, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 203, 7734, 27025, 67, 2399, 15920, 16, 203, 7734, 417, 24410, 581, 5034, 12, 3890, 12, 529, 10756, 3631, 203, 7734, 30170, 548, 9334, 203, 7734, 1758, 12, 2211, 13, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 1731, 1578, 1958, 2310, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 203, 7734, 2030, 19384, 2689, 67, 2399, 15920, 16, 203, 7734, 7152, 73, 16, 203, 7734, 7448, 16, 203, 7734, 10839, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 1731, 1578, 5403, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 1548, 92, 3657, 64, 92, 1611, 3113, 203, 7734, 2461, 6581, 16, 203, 7734, 1958, 2310, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 1758, 1573, 8452, 273, 425, 1793, 3165, 12, 10171, 16, 331, 16, 436, 16, 272, 1769, 203, 3639, 2583, 12, 2977, 8452, 480, 1758, 12, 20, 3631, 315, 55, 1631, 455, 2866, 22216, 858, 8267, 30, 2057, 3372, 8863, 203, 3639, 2583, 12, 12824, 422, 1661, 764, 63, 2977, 8452, 3737, 15, 16, 315, 55, 1631, 455, 2866, 22216, 2 ]
./full_match/11155111/0x44AAb0a83d65E4ea7b437013559790e4E379f6b7/sources/TrippleUp.sol
Customize the bonus round multiplier
uint256 payout = betAmount * bonusRoundMultiplier;
3,802,001
[ 1, 3802, 554, 326, 324, 22889, 3643, 15027, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 293, 2012, 273, 2701, 6275, 380, 324, 22889, 11066, 23365, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xABE46f13C833Ab07bf9e523F485B53c9a633DD60/sources/contracts/IdleCDO.sol
@dev Set last caller and block.number hash. This should be called at the beginning of the first function to protect
function _updateCallerBlock() internal { _lastCallerBlock = keccak256(abi.encodePacked(tx.origin, block.number)); }
8,321,953
[ 1, 694, 1142, 4894, 471, 1203, 18, 2696, 1651, 18, 1220, 1410, 506, 2566, 622, 326, 8435, 434, 326, 1122, 445, 358, 17151, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 2725, 11095, 1768, 1435, 2713, 288, 203, 565, 389, 2722, 11095, 1768, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 978, 18, 10012, 16, 1203, 18, 2696, 10019, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.20; /* * ====================================* * ____ ___ * * | | | | | | | | * * | | ___ |___| | | | | * * | /\ | |__ | | | | /\ | * * |/ \| |___ | |___| |/ \| * * ====================================* * -> What? * The original pyramid, improved: * [x] More stable than ever, having withstood severe testnet abuse and attack attempts from our community!. * [x] Audited, tested, and approved by known community security specialists such as tocsick and Arc. * [X] New functionality; you can now perform partial sell orders. If you succumb to weak hands, you don&#39;t have to dump all of your bags! * [x] New functionality; you can now transfer tokens between wallets. Trading is now possible from within the contract! * [x] New Feature: Masternodes! The first implementation of Ethereum Staking in the world! Vitalik is mad. * [x] Masternodes: Holding 100 WePOW Tokens allow you to generate a Masternode link, Masternode links are used as unique entry points to the contract! * [x] Masternodes: All players who enter the contract through your Masternode have 30% of their 10% dividends fee rerouted from the master-node, to the node-master! */ contract WePOW { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[keccak256(_customerAddress)]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won&#39;t reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "WePOW"; string public symbol = "WPW"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 5; // Look, strong Math uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 20 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(bytes32 => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function WePOW() public { // add administrators here administrators[0xa72c999fc5e51d833c6504bbece0d741c92b7b76] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller&#39;s dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there&#39;s a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(bytes32 _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can&#39;t give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn&#39;t deserve dividends for the tokens before they owned them; //really i know you think you do but you don&#39;t int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
ensures that the first tokens in the contract will be equally distributed meaning, no divine dump will be ever possible result: healthy longevity. are we still in the vulnerable phase? if so, enact anti early whale protocol is the customer in the ambassador list? does the customer purchase exceed the max ambassador quota? updated the accumulated quota execute in case the ether count drops low, the ambassador phase won&#39;t reinitiate
modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( ambassadors_[_customerAddress] == true && (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); _; onlyAmbassadors = false; _; } } ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); address indexed from, address indexed to, uint256 tokens ); =====================================*/ string public name = "WePOW"; string public symbol = "WPW"; uint8 constant public decimals = 18; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 20 ether; ================================*/ mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; =======================================*/
2,338,697
[ 1, 773, 1823, 716, 326, 1122, 2430, 316, 326, 6835, 903, 506, 1298, 1230, 16859, 12256, 16, 1158, 3739, 558, 4657, 903, 506, 14103, 3323, 563, 30, 28819, 4281, 908, 16438, 18, 854, 732, 4859, 316, 326, 331, 19063, 429, 6855, 35, 309, 1427, 16, 570, 621, 30959, 11646, 600, 5349, 1771, 353, 326, 6666, 316, 326, 13232, 428, 23671, 666, 35, 1552, 326, 6666, 23701, 9943, 326, 943, 13232, 428, 23671, 13257, 35, 3526, 326, 24893, 13257, 1836, 316, 648, 326, 225, 2437, 1056, 29535, 4587, 16, 326, 13232, 428, 23671, 6855, 8462, 10, 5520, 31, 88, 283, 2738, 3840, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 30959, 41, 20279, 2888, 5349, 12, 11890, 5034, 389, 8949, 951, 41, 18664, 379, 15329, 203, 3639, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 540, 203, 3639, 309, 12, 1338, 30706, 428, 361, 1383, 597, 14015, 4963, 41, 18664, 379, 13937, 1435, 300, 389, 8949, 951, 41, 18664, 379, 13, 1648, 13232, 428, 23671, 10334, 67, 8623, 95, 203, 5411, 2583, 12, 203, 7734, 13232, 428, 361, 1383, 67, 63, 67, 10061, 1887, 65, 422, 638, 597, 203, 1171, 203, 7734, 261, 2536, 428, 23671, 8973, 5283, 690, 10334, 67, 63, 67, 10061, 1887, 65, 397, 389, 8949, 951, 41, 18664, 379, 13, 1648, 13232, 428, 23671, 2747, 23164, 67, 203, 1171, 203, 5411, 11272, 203, 2398, 203, 5411, 13232, 428, 23671, 8973, 5283, 690, 10334, 67, 63, 67, 10061, 1887, 65, 273, 14060, 10477, 18, 1289, 12, 2536, 428, 23671, 8973, 5283, 690, 10334, 67, 63, 67, 10061, 1887, 6487, 389, 8949, 951, 41, 18664, 379, 1769, 203, 540, 203, 5411, 389, 31, 203, 5411, 1338, 30706, 428, 361, 1383, 273, 629, 31, 203, 5411, 389, 31, 377, 203, 3639, 289, 203, 540, 203, 565, 289, 203, 377, 203, 377, 203, 565, 28562, 14468, 5549, 203, 565, 871, 603, 1345, 23164, 12, 203, 3639, 1758, 8808, 6666, 1887, 16, 203, 3639, 2254, 5034, 6935, 41, 18664, 379, 16, 203, 3639, 2254, 5034, 2430, 49, 474, 329, 16, 203, 3639, 1758, 8808, 29230, 858, 203, 565, 11272, 203, 377, 203, 565, 871, 603, 1345, 55, 1165, 12, 203, 3639, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-04-01 */ // File: contracts/token/interfaces/IERC20Token.sol pragma solidity 0.4.26; /* ERC20 Standard Token interface */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {this;} function symbol() public view returns (string) {this;} function decimals() public view returns (uint8) {this;} function totalSupply() public view returns (uint256) {this;} function balanceOf(address _owner) public view returns (uint256) {_owner; this;} function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;} function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } // File: contracts/utility/Utils.sol pragma solidity 0.4.26; /** * @dev Utilities & Common Modifiers */ contract Utils { /** * constructor */ constructor() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } } // File: contracts/utility/SafeMath.sol pragma solidity 0.4.26; /** * @dev Library for basic math operations with overflow/underflow protection */ library SafeMath { /** * @dev returns the sum of _x and _y, reverts if the calculation overflows * * @param _x value 1 * @param _y value 2 * * @return sum */ function add(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; require(z >= _x); return z; } /** * @dev returns the difference of _x minus _y, reverts if the calculation underflows * * @param _x minuend * @param _y subtrahend * * @return difference */ function sub(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_x >= _y); return _x - _y; } /** * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows * * @param _x factor 1 * @param _y factor 2 * * @return product */ function mul(uint256 _x, uint256 _y) internal pure returns (uint256) { // gas optimization if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y); return z; } /** * ev Integer division of two numbers truncating the quotient, reverts on division by zero. * * aram _x dividend * aram _y divisor * * eturn quotient */ function div(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_y > 0); uint256 c = _x / _y; return c; } } // File: contracts/token/ERC20Token.sol pragma solidity 0.4.26; /** * @dev ERC20 Standard Token implementation */ contract ERC20Token is IERC20Token, Utils { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /** * @dev triggered when tokens are transferred between wallets * * @param _from source address * @param _to target address * @param _value transfer amount */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev triggered when a wallet allows another wallet to transfer tokens from on its behalf * * @param _owner wallet that approves the allowance * @param _spender wallet that receives the allowance * @param _value allowance amount */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @dev initializes a new ERC20Token instance * * @param _name token name * @param _symbol token symbol * @param _decimals decimal points, for display purposes * @param _totalSupply total supply of token units */ constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public { require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balanceOf[msg.sender] = _totalSupply; } /** * @dev send coins * throws on any error rather then return a false flag to minimize user errors * * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public validAddress(_to) returns (bool success) { balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev an account/contract attempts to get the coins * throws on any error rather then return a false flag to minimize user errors * * @param _from source address * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transferFrom(address _from, address _to, uint256 _value) public validAddress(_from) validAddress(_to) returns (bool success) { allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev allow another account/contract to spend some tokens on your behalf * throws on any error rather then return a false flag to minimize user errors * * also, to minimize the risk of the approve/transferFrom attack vector * (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice * in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value * * @param _spender approved address * @param _value allowance amount * * @return true if the approval was successful, false if it wasn't */ function approve(address _spender, uint256 _value) public validAddress(_spender) returns (bool success) { // if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal require(_value == 0 || allowance[msg.sender][_spender] == 0); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } } // File: contracts/utility/interfaces/IOwned.sol pragma solidity 0.4.26; /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public view returns (address) {this;} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } // File: contracts/token/interfaces/ISmartToken.sol pragma solidity 0.4.26; /* Smart Token interface */ contract ISmartToken is IOwned, IERC20Token { function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } // File: contracts/utility/Owned.sol pragma solidity 0.4.26; /** * @dev Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { require(msg.sender == owner); _; } /** * @dev allows transferring the contract ownership * the new owner still needs to accept the transfer * can only be called by the contract owner * * @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: contracts/utility/interfaces/ITokenHolder.sol pragma solidity 0.4.26; /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } // File: contracts/token/interfaces/INonStandardERC20.sol pragma solidity 0.4.26; /* ERC20 Standard Token interface which doesn't return true/false for transfer, transferFrom and approve */ contract INonStandardERC20 { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {this;} function symbol() public view returns (string) {this;} function decimals() public view returns (uint8) {this;} function totalSupply() public view returns (uint256) {this;} function balanceOf(address _owner) public view returns (uint256) {_owner; this;} function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;} function transfer(address _to, uint256 _value) public; function transferFrom(address _from, address _to, uint256 _value) public; function approve(address _spender, uint256 _value) public; } // File: contracts/utility/TokenHolder.sol pragma solidity 0.4.26; /** * @dev We consider every contract to be a 'token holder' since it's currently not possible * for a contract to deny receiving tokens. * * The TokenHolder's contract sole purpose is to provide a safety mechanism that allows * the owner to send tokens that were sent to the contract by mistake back to their sender. * * Note that we use the non standard ERC-20 interface which has no return value for transfer * in order to support both non standard as well as standard token contracts. * see https://github.com/ethereum/solidity/issues/4116 */ contract TokenHolder is ITokenHolder, Owned, Utils { /** * @dev initializes a new TokenHolder instance */ constructor() public { } /** * @dev withdraws tokens held by the contract and sends them to an account * can only be called by the owner * * @param _token ERC20 token contract address * @param _to account to receive the new amount * @param _amount amount to withdraw */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddress(_to) notThis(_to) { INonStandardERC20(_token).transfer(_to, _amount); } } // File: contracts/token/SmartToken.sol pragma solidity 0.4.26; /** * @dev Smart Token * * 'Owned' is specified here for readability reasons */ contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder { using SafeMath for uint256; string public version = '0.3'; bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not /** * @dev triggered when a smart token is deployed * the _token address is defined for forward compatibility, in case the event is trigger by a factory * * @param _token new smart token address */ event NewSmartToken(address _token); /** * @dev triggered when the total supply is increased * * @param _amount amount that gets added to the supply */ event Issuance(uint256 _amount); /** * @dev triggered when the total supply is decreased * * @param _amount amount that gets removed from the supply */ event Destruction(uint256 _amount); /** * @dev initializes a new SmartToken instance * * @param _name token name * @param _symbol token short symbol, minimum 1 character * @param _decimals for display purposes only */ constructor(string _name, string _symbol, uint8 _decimals) public ERC20Token(_name, _symbol, _decimals, 0) { emit NewSmartToken(address(this)); } // allows execution only when transfers aren't disabled modifier transfersAllowed { assert(transfersEnabled); _; } /** * @dev disables/enables transfers * can only be called by the contract owner * * @param _disable true to disable transfers, false to enable them */ function disableTransfers(bool _disable) public ownerOnly { transfersEnabled = !_disable; } /** * @dev increases the token supply and sends the new tokens to an account * can only be called by the contract owner * * @param _to account to receive the new amount * @param _amount amount to increase the supply by */ function issue(address _to, uint256 _amount) public ownerOnly validAddress(_to) notThis(_to) { totalSupply = totalSupply.add(_amount); balanceOf[_to] = balanceOf[_to].add(_amount); emit Issuance(_amount); emit Transfer(this, _to, _amount); } /** * @dev removes tokens from an account and decreases the token supply * can be called by the contract owner to destroy tokens from any account or by any holder to destroy tokens from his/her own account * * @param _from account to remove the amount from * @param _amount amount to decrease the supply by */ function destroy(address _from, uint256 _amount) public { require(msg.sender == _from || msg.sender == owner); // validate input balanceOf[_from] = balanceOf[_from].sub(_amount); totalSupply = totalSupply.sub(_amount); emit Transfer(_from, this, _amount); emit Destruction(_amount); } // ERC20 standard method overrides with some extra functionality /** * @dev send coins * throws on any error rather then return a false flag to minimize user errors * in addition to the standard checks, the function throws if transfers are disabled * * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) { assert(super.transfer(_to, _value)); return true; } /** * @dev an account/contract attempts to get the coins * throws on any error rather then return a false flag to minimize user errors * in addition to the standard checks, the function throws if transfers are disabled * * @param _from source address * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) { assert(super.transferFrom(_from, _to, _value)); return true; } }
* @dev triggered when tokens are transferred between wallets @param _from source address @param _to target address @param _value transfer amount/* @dev triggered when a wallet allows another wallet to transfer tokens from on its behalf @param _owner wallet that approves the allowance @param _spender wallet that receives the allowance @param _value allowance amount/* @dev initializes a new ERC20Token instance @param _name token name @param _symbol token symbol @param _decimals decimal points, for display purposes @param _totalSupply total supply of token units/
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public { name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balanceOf[msg.sender] = _totalSupply; }
2,415,131
[ 1, 10668, 329, 1347, 2430, 854, 906, 4193, 3086, 17662, 2413, 225, 389, 2080, 565, 1084, 1758, 225, 389, 869, 1377, 1018, 1758, 225, 389, 1132, 282, 7412, 3844, 19, 225, 10861, 1347, 279, 9230, 5360, 4042, 9230, 358, 7412, 2430, 628, 603, 2097, 12433, 6186, 225, 389, 8443, 282, 9230, 716, 6617, 3324, 326, 1699, 1359, 225, 389, 87, 1302, 264, 9230, 716, 17024, 326, 1699, 1359, 225, 389, 1132, 282, 1699, 1359, 3844, 19, 225, 11643, 279, 394, 4232, 39, 3462, 1345, 791, 225, 389, 529, 3639, 1147, 508, 225, 389, 7175, 1377, 1147, 3273, 225, 389, 31734, 565, 6970, 3143, 16, 364, 2562, 13694, 225, 389, 4963, 3088, 1283, 2078, 14467, 434, 1147, 4971, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 1080, 389, 529, 16, 533, 389, 7175, 16, 2254, 28, 389, 31734, 16, 2254, 5034, 389, 4963, 3088, 1283, 13, 1071, 288, 203, 203, 3639, 508, 273, 389, 529, 31, 203, 3639, 3273, 273, 389, 7175, 31, 203, 3639, 15105, 273, 389, 31734, 31, 203, 3639, 2078, 3088, 1283, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x3CedB6966aF4316C9e746Bd7bD2EA6bB313b0509/sources/Storage.sol
* @dev Store value in variable @param num value to store/
function store(uint256 num) public payable { require(msg.value == 1 ether); number = num; }
5,320,834
[ 1, 2257, 460, 316, 2190, 225, 818, 460, 358, 1707, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1707, 12, 11890, 5034, 818, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 404, 225, 2437, 1769, 203, 3639, 1300, 273, 818, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-10-17 */ // Sources flattened with hardhat v2.6.4 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File @openzeppelin/contracts/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File contracts/interfaces/IKoansToken.sol pragma solidity ^0.8.6; interface IKoansToken is IERC721 { event KoanCreated(uint256 indexed tokenId); event KoanBurned(uint256 indexed tokenId); event FoundersDAOUpdated(address koansDAO); event MinterUpdated(address minter); event MinterLocked(); function setContractURIHash(string memory newContractURIHash) external; function setFoundersDAO(address _foundersDAO) external; function setMinter(address _minter) external; function lockMinter() external; function mintFoundersDAOKoan(string memory _foundersDAOMetadataURI) external; function mint() external returns (uint256); function burn(uint256 tokenId) external; function setMetadataURI(uint256 tokenId, string memory metadataURI) external; } // File contracts/interfaces/ISashoToken.sol pragma solidity ^0.8.6; interface ISashoToken is IERC20 { function mint(address account, uint256 rawAmount) external; function burn(uint256 tokenId) external; function delegate(address delegatee) external; function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external; function setMinter(address minter) external; function lockMinter() external; function getCurrentVotes(address account) external view returns (uint96); function getPriorVotes(address account, uint blockNumber) external view returns (uint96); } // File contracts/interfaces/IKoansAuctionHouse.sol pragma solidity ^0.8.6; interface IKoansAuctionHouse { struct Auction { // ID for the Koan (ERC721 token ID) uint256 koanId; // The current highest bid amount uint256 amount; // The time that the auction started uint256 startTime; // The time that the auction is scheduled to end uint256 endTime; // The address of the current highest bid address payable bidder; // Whether or not the auction has been settled bool settled; // The address to payout a portion of the auction's proceeds to. address payable payoutAddress; } event AuctionCreated(uint256 indexed koanId, uint256 startTime, uint256 endTime); event AuctionBid(uint256 indexed koanId, address sender, uint256 value, bool extended); event AuctionExtended(uint256 indexed koanId, uint256 endTime); event AuctionSettled(uint256 indexed koanId, address winner, uint256 amount); event AuctionTimeBufferUpdated(uint256 timeBuffer); event AuctionReservePriceUpdated(uint256 reservePrice); event AuctionMinBidIncrementPercentageUpdated(uint256 minBidIncrementPercentage); event PayoutRewardBPUpdated(uint256 artistRewardBP); event AuctionDurationUpdated(uint256 duration); function settleCurrentAndCreateNewAuction() external; function settleAuction() external; function createBid(uint256 koanId) external payable; function addOffer(string memory _uri, address _payoutAddress) external; function pause() external; function unpause() external; function setTimeBuffer(uint256 _timeBuffer) external; function setReservePrice(uint256 _reservePrice) external; function setMinBidIncrementPercentage(uint8 _minBidIncrementPercentage) external; function setPayoutRewardBP(uint256 _payoutRewardBP) external; function setDuration(uint256 _duration) external; function setOfferAddress(address _koanOfferAddress) external; } // File contracts/interfaces/IWETH.sol pragma solidity ^0.8.6; interface IWETH { function deposit() external payable; function withdraw(uint256 wad) external; function transfer(address to, uint256 value) external returns (bool); } // File contracts/KoansAuctionHouse.sol /// @title The Koans auction house. // KoansAuctionHouse.sol is a modified version of Nouns's AuctionHouse.sol: // https://etherscan.io/address/0xf15a943787014461d94da08ad4040f79cd7c124e#code pragma solidity ^0.8.6; contract KoansAuctionHouse is IKoansAuctionHouse, Pausable, ReentrancyGuard, Ownable { // The Koans ERC721 token contract IKoansToken public koans; // The Sashos ERC20 token contract. ISashoToken public sashos; // The address of the WETH contract address public weth; // The minimum amount of time left in an auction after a new bid is created uint256 public timeBuffer; // The minimum price accepted in an auction uint256 public reservePrice; // The minimum percentage difference between the last bid amount and the current bid uint8 public minBidIncrementPercentage; // The duration of a single auction uint256 public duration; // The active auction IKoansAuctionHouse.Auction public auction; // Vector of offered URIs. string[] public offerURIs; // Vector of the addresses to payout to for each of the offer URIs. address payable[] public offerPayoutAddresses; // The index of the next offer to be auctioned off. uint256 public nextOfferURIIndex; // Address of the Koan Offer contract. address public koanOfferAddress; // Basis points of the fraction of the auction to be sent to the a // payout address of an auction as a reward. uint256 public payoutRewardBP; // Address of the Koans founder's wallet. address public koansFoundersAddress; // Basis points of the fraction of the auction to be sent to the /** * @notice Initialize the auction house and base contracts, * populate configuration values, and pause the contract. * @dev This function can only be called once. */ constructor( IKoansToken _koans, ISashoToken _sashos, address _weth, uint256 _timeBuffer, uint256 _reservePrice, uint8 _minBidIncrementPercentage, uint256 _duration, address _koanOfferAddress, address _koansFoundersAddress ) { _pause(); koans = _koans; sashos = _sashos; weth = _weth; timeBuffer = _timeBuffer; reservePrice = _reservePrice; minBidIncrementPercentage = _minBidIncrementPercentage; duration = _duration; koanOfferAddress = _koanOfferAddress; payoutRewardBP = 5000; nextOfferURIIndex = 0; koansFoundersAddress = _koansFoundersAddress; } /** * @notice Settle the current auction, mint a new Koan, and put it up for auction. */ function settleCurrentAndCreateNewAuction() external override nonReentrant whenNotPaused { _settleAuction(); _createAuction(); } /** * @notice Settle the current auction. * @dev This function can only be called when the contract is paused. */ function settleAuction() external override whenPaused nonReentrant { _settleAuction(); } /** * @notice Create a bid for a Koan, with a given amount. * @dev This contract only accepts payment in ETH. */ function createBid(uint256 koanId) external payable override nonReentrant { IKoansAuctionHouse.Auction memory _auction = auction; require(_auction.koanId == koanId, "Koan not up for auction"); require(block.timestamp < _auction.endTime, "Auction expired"); require(msg.value >= reservePrice, "Must send at least reservePrice"); require( msg.value >= _auction.amount + ((_auction.amount * minBidIncrementPercentage) / 100), "Insufficient bid." ); address payable lastBidder = _auction.bidder; // Refund the last bidder, if applicable if (lastBidder != address(0)) { _safeTransferETHWithFallback(lastBidder, _auction.amount); } auction.amount = msg.value; auction.bidder = payable(msg.sender); // Extend the auction if the bid was received within `timeBuffer` of the auction end time bool extended = _auction.endTime - block.timestamp < timeBuffer; if (extended) { auction.endTime = _auction.endTime = block.timestamp + timeBuffer; } emit AuctionBid(_auction.koanId, msg.sender, msg.value, extended); if (extended) { emit AuctionExtended(_auction.koanId, _auction.endTime); } } /** * @notice Add an offer to the queue of offers to be auctioned. */ function addOffer(string memory _uri, address _payoutAddress) external override nonReentrant { require(msg.sender == koanOfferAddress, "Must be Offer contract"); offerURIs.push(_uri); offerPayoutAddresses.push(payable(_payoutAddress)); } /** * @notice Pause the Koans auction house. * @dev This function can only be called by the owner when the * contract is unpaused. While no new auctions can be started when paused, * anyone can settle an ongoing auction. */ function pause() external override onlyOwner { _pause(); } /** * @notice Unpause the Koans auction house. * @dev This function can only be called by the owner when the * contract is paused. If required, this function will start a new auction. */ function unpause() external override onlyOwner { _unpause(); if (auction.startTime == 0 || auction.settled) { _createAuction(); } } /** * @notice Set the auction time buffer. * @dev Only callable by the owner. */ function setTimeBuffer(uint256 _timeBuffer) external override onlyOwner { timeBuffer = _timeBuffer; emit AuctionTimeBufferUpdated(_timeBuffer); } /** * @notice Set the auction reserve price. * @dev Only callable by the owner. */ function setReservePrice(uint256 _reservePrice) external override onlyOwner { reservePrice = _reservePrice; emit AuctionReservePriceUpdated(_reservePrice); } /** * @notice Set the auction minimum bid increment percentage. * @dev Only callable by the owner. */ function setMinBidIncrementPercentage(uint8 _minBidIncrementPercentage) external override onlyOwner { minBidIncrementPercentage = _minBidIncrementPercentage; emit AuctionMinBidIncrementPercentageUpdated(_minBidIncrementPercentage); } /** * @notice Set the percent of the auction proceeds that are sent to the payout address. * @dev Only callable by the owner. */ function setPayoutRewardBP(uint256 _payoutRewardBP) external override onlyOwner { require(_payoutRewardBP <= 10000, "BP greater than 10000"); if (auction.koanId < 100) { require(_payoutRewardBP <= 9000, "BP greather than 9000"); } payoutRewardBP = _payoutRewardBP; emit PayoutRewardBPUpdated(_payoutRewardBP); } /** * @notice Set the duration of the auction in seconds. * @dev Only callable by the owner. */ function setDuration(uint256 _duration) external override onlyOwner { duration = _duration; emit AuctionDurationUpdated(_duration); } /** * @notice Set the address of the offer contract. * @dev Only callable by the owner. */ function setOfferAddress(address _koanOfferAddress) external override onlyOwner { koanOfferAddress = _koanOfferAddress; } /** * @notice Create an auction. * @dev Store the auction details in the `auction` state variable and emit an AuctionCreated event. * If the mint reverts, the minter was updated without pausing this contract first. To remedy this, * catch the revert and pause this contract. */ function _createAuction() internal { require(nextOfferURIIndex < offerURIs.length, "No proposed URIs ready."); try koans.mint() returns (uint256 koanId) { uint256 startTime = block.timestamp; uint256 endTime = startTime + duration; koans.setMetadataURI(koanId, offerURIs[nextOfferURIIndex]); auction = Auction({ koanId: koanId, amount: 0, startTime: startTime, endTime: endTime, bidder: payable(0), settled: false, payoutAddress: offerPayoutAddresses[nextOfferURIIndex] }); nextOfferURIIndex += 1; emit AuctionCreated(koanId, startTime, endTime); } catch Error(string memory) { _pause(); } } /** * @notice Settle an auction, finalizing the bid and paying out to the owner. * @dev If there are no bids, the Koan is burned. */ function _settleAuction() internal { IKoansAuctionHouse.Auction memory _auction = auction; require(_auction.startTime != 0, "Auction hasn't begun"); require(!_auction.settled, "Auction has already been settled"); require(block.timestamp >= _auction.endTime, "Auction hasn't completed"); auction.settled = true; if (_auction.bidder == address(0)) { koans.burn(_auction.koanId); } else { koans.transferFrom(address(this), _auction.bidder, _auction.koanId); } if (_auction.amount > 0) { uint256 koansFoundersReward = 0; if (auction.koanId < 100) { koansFoundersReward = _auction.amount * 1000 / 10000; _safeTransferETHWithFallback(koansFoundersAddress, koansFoundersReward); } uint256 payoutReward = _auction.amount * payoutRewardBP / 10000; _safeTransferETHWithFallback(_auction.payoutAddress, payoutReward); _safeTransferETHWithFallback(owner(), (_auction.amount - koansFoundersReward) - payoutReward); } sashos.mint(owner(), 1000000 ether); emit AuctionSettled(_auction.koanId, _auction.bidder, _auction.amount); } /** * @notice Transfer ETH. If the ETH transfer fails, wrap the ETH and try send it as WETH. */ function _safeTransferETHWithFallback(address to, uint256 amount) internal { if (!_safeTransferETH(to, amount)) { IWETH(weth).deposit{ value: amount }(); IERC20(weth).transfer(to, amount); } } /** * @notice Transfer ETH and return the success status. * @dev This function only forwards 30,000 gas to the callee. */ function _safeTransferETH(address to, uint256 value) internal returns (bool) { (bool success, ) = to.call{ value: value, gas: 30_000 }(new bytes(0)); return success; } }
* @notice Create an auction. @dev Store the auction details in the `auction` state variable and emit an AuctionCreated event. If the mint reverts, the minter was updated without pausing this contract first. To remedy this, catch the revert and pause this contract./
function _createAuction() internal { require(nextOfferURIIndex < offerURIs.length, "No proposed URIs ready."); try koans.mint() returns (uint256 koanId) { uint256 startTime = block.timestamp; uint256 endTime = startTime + duration; koans.setMetadataURI(koanId, offerURIs[nextOfferURIIndex]); auction = Auction({ koanId: koanId, amount: 0, startTime: startTime, endTime: endTime, bidder: payable(0), settled: false, payoutAddress: offerPayoutAddresses[nextOfferURIIndex] }); nextOfferURIIndex += 1; emit AuctionCreated(koanId, startTime, endTime); _pause(); } }
10,857,619
[ 1, 1684, 392, 279, 4062, 18, 225, 4994, 326, 279, 4062, 3189, 316, 326, 1375, 69, 4062, 68, 919, 2190, 471, 3626, 392, 432, 4062, 6119, 871, 18, 971, 326, 312, 474, 15226, 87, 16, 326, 1131, 387, 1703, 3526, 2887, 6790, 9940, 333, 6835, 1122, 18, 2974, 849, 24009, 333, 16, 1044, 326, 15226, 471, 11722, 333, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2640, 37, 4062, 1435, 2713, 288, 203, 3639, 2583, 12, 4285, 10513, 3098, 1016, 411, 10067, 1099, 2520, 18, 2469, 16, 315, 2279, 20084, 24565, 5695, 1199, 1769, 203, 3639, 775, 417, 83, 634, 18, 81, 474, 1435, 1135, 261, 11890, 5034, 417, 83, 304, 548, 13, 288, 203, 5411, 2254, 5034, 8657, 273, 1203, 18, 5508, 31, 203, 5411, 2254, 5034, 13859, 273, 8657, 397, 3734, 31, 203, 5411, 417, 83, 634, 18, 542, 2277, 3098, 12, 28179, 304, 548, 16, 10067, 1099, 2520, 63, 4285, 10513, 3098, 1016, 19226, 203, 5411, 279, 4062, 273, 432, 4062, 12590, 203, 7734, 417, 83, 304, 548, 30, 417, 83, 304, 548, 16, 203, 7734, 3844, 30, 374, 16, 203, 7734, 8657, 30, 8657, 16, 203, 7734, 13859, 30, 13859, 16, 203, 7734, 9949, 765, 30, 8843, 429, 12, 20, 3631, 203, 7734, 26319, 1259, 30, 629, 16, 203, 7734, 293, 2012, 1887, 30, 10067, 52, 2012, 7148, 63, 4285, 10513, 3098, 1016, 65, 203, 5411, 15549, 203, 203, 5411, 1024, 10513, 3098, 1016, 1011, 404, 31, 203, 203, 5411, 3626, 432, 4062, 6119, 12, 28179, 304, 548, 16, 8657, 16, 13859, 1769, 203, 5411, 389, 19476, 5621, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/80001/0x636C4701Fdd1C46e47177cef7032b26402Bf7251/sources/minter1.sol
* @dev Returns the downcasted uint64 from uint256, reverting on overflow (when the input is greater than largest uint64). Counterpart to Solidity's `uint64` operator. Requirements: - input must fit into 64 bits _Available since v2.5._/
function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); }
8,818,476
[ 1, 1356, 326, 2588, 4155, 329, 2254, 1105, 628, 2254, 5034, 16, 15226, 310, 603, 9391, 261, 13723, 326, 810, 353, 6802, 2353, 12756, 2254, 1105, 2934, 9354, 2680, 358, 348, 7953, 560, 1807, 1375, 11890, 1105, 68, 3726, 18, 29076, 30, 300, 810, 1297, 4845, 1368, 5178, 4125, 389, 5268, 3241, 331, 22, 18, 25, 6315, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 358, 5487, 1105, 12, 11890, 5034, 460, 13, 2713, 16618, 1135, 261, 11890, 1105, 13, 288, 203, 5411, 2583, 12, 1132, 1648, 618, 12, 11890, 1105, 2934, 1896, 16, 315, 9890, 9735, 30, 460, 3302, 1404, 4845, 316, 5178, 4125, 8863, 203, 5411, 327, 2254, 1105, 12, 1132, 1769, 203, 3639, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import 'openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol'; import 'openzeppelin-solidity/contracts/token/ERC20/IERC20.sol'; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import 'openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol'; contract EndlessCrowdsale is MintedCrowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 constant public minContribution = 1000000000000000; uint256 constant public rateDecimals = 18; uint256 constant private rateDecimalsMultiply = 10 ** rateDecimals; constructor (IERC20 token) public Crowdsale(1000000000000000000000000, msg.sender, token) {} function getTokenAmount(uint256 weiAmount) external view returns (uint256) { return _getTokenAmount(weiAmount); } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { super._preValidatePurchase(beneficiary, weiAmount); require( weiAmount >= minContribution, 'Contribution must be at least 0.001 ETH' ); } function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { uint256 aInverse = rate().mul(2); uint256 b = getLinearCoefficient(aInverse); uint256 tokenAmount = getRoot(aInverse, b, weiAmount); return tokenAmount; } function getLinearCoefficient(uint256 aInverse) private view returns (uint256) { // Adjust for decimal places uint256 start = token().totalSupply().mul(rateDecimalsMultiply); uint256 oneDecimals = rateDecimalsMultiply; uint256 b = start.mul(2).add(oneDecimals).div(aInverse); return b; } function getRoot(uint256 aInverse, uint256 b, uint256 cNegative) private pure returns (uint256) { uint256 discriminant = getDiscriminant(aInverse, b, cNegative); // Adjust for decimal places uint256 discriminantDecimals = discriminant.mul(rateDecimalsMultiply); uint256 root = sqrt(discriminantDecimals).sub(b).div(2).mul(aInverse); // Adjust for decimal places root = root.div(rateDecimalsMultiply); return root; } function getDiscriminant(uint256 aInverse, uint256 b, uint256 cNegative) private pure returns (uint256) { // Adjust for decimal places uint256 bSquaredDecimals = b.mul(b).div(rateDecimalsMultiply); uint256 cNegativeDecimals = cNegative.mul(rateDecimalsMultiply); return bSquaredDecimals.add(cNegativeDecimals.mul(4).div(aInverse)); } function sqrt(uint256 x) private pure returns (uint256) { uint256 z = x.add(1).div(2); uint y = x; while (z < y) { y = z; z = x.div(z).add(z).div(2); } return y; } }
Adjust for decimal places
function getLinearCoefficient(uint256 aInverse) private view returns (uint256) { uint256 start = token().totalSupply().mul(rateDecimalsMultiply); uint256 oneDecimals = rateDecimalsMultiply; uint256 b = start.mul(2).add(oneDecimals).div(aInverse); return b; }
13,046,279
[ 1, 10952, 364, 6970, 12576, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9851, 297, 4249, 25403, 12, 11890, 5034, 279, 16376, 13, 203, 3639, 3238, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 787, 273, 1147, 7675, 4963, 3088, 1283, 7675, 16411, 12, 5141, 31809, 26040, 1769, 203, 3639, 2254, 5034, 1245, 31809, 273, 4993, 31809, 26040, 31, 203, 203, 3639, 2254, 5034, 324, 273, 787, 18, 16411, 12, 22, 2934, 1289, 12, 476, 31809, 2934, 2892, 12, 69, 16376, 1769, 203, 203, 3639, 327, 324, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.2; library SafeMath { function MUL162(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV641(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB622(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD574(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD960(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } interface IERC20 { function TRANSFER171(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE729(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM43(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY1000() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF11(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE189(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER893(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL326(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY1000() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF11(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE189(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER171(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER88(msg.sender, to, value); return true; } function APPROVE729(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE787(msg.sender, spender, value); return true; } function TRANSFERFROM43(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER88(from, to, value); _APPROVE787(from, msg.sender, _allowed[from][msg.sender].SUB622(value)); return true; } function INCREASEALLOWANCE340(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE787(msg.sender, spender, _allowed[msg.sender][spender].ADD574(addedValue)); return true; } function DECREASEALLOWANCE920(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE787(msg.sender, spender, _allowed[msg.sender][spender].SUB622(subtractedValue)); return true; } function _TRANSFER88(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB622(value); _balances[to] = _balances[to].ADD574(value); emit TRANSFER893(from, to, value); } function _MINT877(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD574(value); _balances[account] = _balances[account].ADD574(value); emit TRANSFER893(address(0), account, value); } function _BURN466(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB622(value); _balances[account] = _balances[account].SUB622(value); emit TRANSFER893(account, address(0), value); } function _APPROVE787(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit APPROVAL326(owner, spender, value); } function _BURNFROM510(address account, uint256 value) internal { //inject NONSTANDARD NAMING _BURN466(account, value); _APPROVE787(account, msg.sender, _allowed[account][msg.sender].SUB622(value)); } } contract Controller { address private _owner; bool private _paused; event OWNERSHIPTRANSFERRED948(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING event PAUSED527(address account); //inject NONSTANDARD NAMING event UNPAUSED105(address account); //inject NONSTANDARD NAMING mapping(address => bool) private owners; constructor() internal { SETOWNER969(msg.sender); } modifier ONLYOWNER408() { //inject NONSTANDARD NAMING require(owners[msg.sender]); _; } function SETOWNER969(address addr) internal returns(bool) { //inject NONSTANDARD NAMING if (!owners[addr]) { owners[addr] = true; _owner = addr; return true; } } function CHANGEOWNER929(address newOwner) ONLYOWNER408 public returns(bool) { //inject NONSTANDARD NAMING require (!owners[newOwner]); owners[newOwner]; _owner = newOwner; emit OWNERSHIPTRANSFERRED948(_owner, newOwner); return true; } function OWNER670() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } function PAUSED195() public view returns(bool) { //inject NONSTANDARD NAMING return _paused; } modifier WHENNOTPAUSED721() { //inject NONSTANDARD NAMING require(!_paused); _; } modifier WHENPAUSED463() { //inject NONSTANDARD NAMING require(_paused); _; } function PAUSE136() public ONLYOWNER408 WHENNOTPAUSED721 { //inject NONSTANDARD NAMING _paused = true; emit PAUSED527(msg.sender); } function UNPAUSE780() public ONLYOWNER408 WHENPAUSED463 { //inject NONSTANDARD NAMING _paused = false; emit UNPAUSED105(msg.sender); } } contract LobefyToken is ERC20, Controller { using SafeMath for uint256; string private _name = "Lobefy Token"; string private _symbol = "CRWD"; uint256 private _decimals = 18; address private team = 0xDA19316953D19f5f8C6361d68C6D0078c06285d3; uint256 private team1Balance = 50 * (10 ** 6) * (10 ** 18); constructor() public { MINT940(team, team1Balance); } function NAME85() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL530() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS786() public view returns (uint256) { //inject NONSTANDARD NAMING return _decimals; } function BURN283(uint256 value) public { //inject NONSTANDARD NAMING _BURN466(msg.sender, value); } function BURNFROM445(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM510(from, value); } function MINT940(address to, uint256 value) public ONLYOWNER408 returns (bool) { //inject NONSTANDARD NAMING _MINT877(to, value); return true; } function TRANSFER171(address to, uint256 value) public WHENNOTPAUSED721 returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFER171(to, value); } function TRANSFERFROM43(address from, address to, uint256 value) public WHENNOTPAUSED721 returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFERFROM43(from, to, value); } function APPROVE729(address spender, uint256 value) public WHENNOTPAUSED721 returns (bool) { //inject NONSTANDARD NAMING return super.APPROVE729(spender, value); } function INCREASEALLOWANCE340(address spender, uint addedValue) public WHENNOTPAUSED721 returns (bool success) { //inject NONSTANDARD NAMING return super.INCREASEALLOWANCE340(spender, addedValue); } function DECREASEALLOWANCE920(address spender, uint subtractedValue) public WHENNOTPAUSED721 returns (bool success) { //inject NONSTANDARD NAMING return super.DECREASEALLOWANCE920(spender, subtractedValue); } }
inject NONSTANDARD NAMING
function ADD574(uint256 a, uint256 b) internal pure returns (uint256) {
7,272,408
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11689, 25, 5608, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.21 <0.7.1; import "./Context.sol"; import "./Pausable.sol"; import "./Ownable.sol"; import "./AccessControl.sol"; import "./ERC20.sol"; import "./ExternallyTransferable.sol"; contract StableCoin is ContextAware, // provides _msgSender(), _msgData() Pausable, // provides _pause(), _unpause() Ownable, // Ownable, Claimable AccessControl, // RBAC for KYC, Frozen ERC20, // ERC20 Functions (transfer, balance, allowance, mint, burn) ExternallyTransferable // Supports External Transfers { // Defined Roles bytes32 private constant KYC_PASSED = keccak256("KYC_PASSED"); bytes32 private constant FROZEN = keccak256("FROZEN"); // Special People address private _supplyManager; address private _complianceManager; address private _enforcementManager; // Events Emitted event Constructed( string tokenName, string tokenSymbol, uint8 tokenDecimal, uint256 totalSupply, address supplyManager, address complianceManager, address enforcementManager ); // Privileged Roles event ChangeSupplyManager(address newSupplyManager); event ChangeComplianceManager(address newComplianceManager); event ChangeEnforcementManager(address newEnforcementManager); // ERC20+ event Wipe(address account, uint256 amount); event Mint(address account, uint256 amount); event Burn(address account, uint256 amount); event Transfer(address sender, address recipient, uint256 amount); event Approve(address sender, address spender, uint256 amount); event IncreaseAllowance(address sender, address spender, uint256 amount); event DecreaseAllowance(address sender, address spender, uint256 amount); // KYC event Freeze(address account); // Freeze: Freeze this account event Unfreeze(address account); event SetKycPassed(address account); event UnsetKycPassed(address account); // Halt event Pause(address sender); // Pause: Pause entire contract event Unpause(address sender); // "External Transfer" // Signify to the coin bridge to perform external transfer event ApproveExternalTransfer( address from, string networkURI, bytes to, uint256 amount ); event ExternalTransfer( address from, string networkURI, bytes to, uint256 amount ); event ExternalTransferFrom( bytes from, string networkURI, address to, uint256 amount ); constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimal, uint256 totalSupply, address supplyManager, address complianceManager, address enforcementManager ) public ERC20(tokenName, tokenSymbol, tokenDecimal) { _supplyManager = supplyManager; _complianceManager = complianceManager; _enforcementManager = enforcementManager; // Owner has Admin Privileges on all roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); // sudo role // Give CM ability to grant/revoke roles (but not admin of this role) grantRole(DEFAULT_ADMIN_ROLE, complianceManager); // KYC accounts grantRole(KYC_PASSED, _msgSender()); grantRole(KYC_PASSED, supplyManager); grantRole(KYC_PASSED, complianceManager); grantRole(KYC_PASSED, enforcementManager); // Give supply manager all tokens mint(totalSupply); // Emits Mint // Did it emit Constructed( tokenName, tokenSymbol, tokenDecimal, totalSupply, supplyManager, complianceManager, enforcementManager ); } /* * RBAC */ function supplyManager() public view returns (address) { return _supplyManager; } modifier onlySupplyManager() { require( _msgSender() == supplyManager() || _msgSender() == owner(), "Only the supply manager can call this function." ); _; } function changeSupplyManager(address newSupplyManager) public onlyOwner { require( newSupplyManager != address(0), "Cannot change supply manager to 0x0." ); revokeRole(KYC_PASSED, _supplyManager); _supplyManager = newSupplyManager; grantRole(KYC_PASSED, _supplyManager); revokeRole(FROZEN, _supplyManager); emit ChangeSupplyManager(newSupplyManager); } function complianceManager() public view returns (address) { return _complianceManager; } modifier onlyComplianceManager() { require( _msgSender() == complianceManager() || _msgSender() == owner(), "Only the Compliance Manager can call this function." ); _; } function changeComplianceManager(address newComplianceManager) public onlyOwner { require( newComplianceManager != address(0), "Cannot change compliance manager to 0x0." ); revokeRole(KYC_PASSED, _complianceManager); _complianceManager = newComplianceManager; grantRole(KYC_PASSED, _complianceManager); revokeRole(FROZEN, _complianceManager); emit ChangeComplianceManager(newComplianceManager); } function enforcementManager() public view returns (address) { return _enforcementManager; } modifier onlyEnforcementManager() { require( _msgSender() == enforcementManager() || _msgSender() == owner(), "Only the Enforcement Manager can call this function." ); _; } function changeEnforcementManager(address newEnforcementManager) public onlyOwner { require( newEnforcementManager != address(0), "Cannot change enforcement manager to 0x0" ); revokeRole(KYC_PASSED, _enforcementManager); _enforcementManager = newEnforcementManager; grantRole(KYC_PASSED, _enforcementManager); revokeRole(FROZEN, _enforcementManager); emit ChangeEnforcementManager(newEnforcementManager); } function isPrivilegedRole(address account) public view returns (bool) { return account == supplyManager() || account == complianceManager() || account == enforcementManager() || account == owner(); } modifier requiresKYC() { require( hasRole(KYC_PASSED, _msgSender()), "Calling this function requires KYC approval." ); _; } function isKycPassed(address account) public view returns (bool) { return hasRole(KYC_PASSED, account); } // KYC: only CM function setKycPassed(address account) public onlyComplianceManager { grantRole(KYC_PASSED, account); emit SetKycPassed(account); } // Un-KYC: only CM, only non-privileged accounts function unsetKycPassed(address account) public onlyComplianceManager { require( !isPrivilegedRole(account), "Cannot unset KYC for administrator account." ); require(account != address(0), "Cannot unset KYC for address 0x0."); revokeRole(KYC_PASSED, account); emit UnsetKycPassed(account); } modifier requiresNotFrozen() { require( !hasRole(FROZEN, _msgSender()), "Your account has been frozen, cannot call function." ); _; } function isFrozen(address account) public view returns (bool) { return hasRole(FROZEN, account); } // Freeze an account: only CM, only non-privileged accounts function freeze(address account) public onlyComplianceManager { require( !isPrivilegedRole(account), "Cannot freeze administrator account." ); require(account != address(0), "Cannot freeze address 0x0."); grantRole(FROZEN, account); emit Freeze(account); } // Unfreeze an account: only CM function unfreeze(address account) public onlyComplianceManager { revokeRole(FROZEN, account); emit Unfreeze(account); } // Check Transfer Allowed (user facing) function checkTransferAllowed(address account) public view returns (bool) { return isKycPassed(account) && !isFrozen(account); } // Pause: Only CM function pause() public onlyComplianceManager { _pause(); emit Pause(_msgSender()); } // Unpause: Only CM function unpause() public onlyComplianceManager { _unpause(); emit Unpause(_msgSender()); } // Claim Ownership function claimOwnership() public override(Ownable) onlyProposedOwner { address prevOwner = owner(); super.claimOwnership(); // emits ClaimOwnership _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(KYC_PASSED, _msgSender()); revokeRole(FROZEN, _msgSender()); revokeRole(KYC_PASSED, prevOwner); } // Wipe function wipe(address account, uint256 amount) public onlyEnforcementManager { uint256 balance = balanceOf(account); require( amount <= balance, "Amount cannot be greater than balance" ); super._transfer(account, _supplyManager, amount); _burn(_supplyManager, amount); emit Wipe(account, amount); } /* * Transfers */ // Mint function mint(uint256 amount) public onlySupplyManager { _mint(supplyManager(), amount); emit Mint(_msgSender(), amount); } // Burn function burn(uint256 amount) public onlySupplyManager { _burn(_supplyManager, amount); emit Burn(_msgSender(), amount); } // Check Transfer Allowed (internal) function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20) requiresKYC requiresNotFrozen whenNotPaused { if (from == supplyManager() && to == address(0)) { // allowed (burn) super._beforeTokenTransfer(from, to, amount); return; } if (to == supplyManager() && from == address(0)) { // allowed (mint) super._beforeTokenTransfer(from, to, amount); return; } if ( to == supplyManager() && hasRole(FROZEN, from) && amount == balanceOf(from) ) { // allowed (wipe account) super._beforeTokenTransfer(from, to, amount); return; } // All other transfers require(isKycPassed(from), "Sender account requires KYC to continue."); require(isKycPassed(to), "Receiver account requires KYC to continue."); require(!isFrozen(from), "Sender account is frozen."); require(!isFrozen(to), "Receiver account is frozen."); super._beforeTokenTransfer(from, to, amount); // callbacks from above (if any) } function transfer(address to, uint256 amount) public override(ERC20) { super._transfer(_msgSender(), to, amount); emit Transfer(_msgSender(), to, amount); } /* * External Transfers */ // approve an allowance for transfer to an external network function approveExternalTransfer( string memory networkURI, bytes memory externalAddress, uint256 amount ) public override(ExternallyTransferable) requiresKYC requiresNotFrozen whenNotPaused { require( amount <= balanceOf(_msgSender()), "Cannot approve more than balance." ); super.approveExternalTransfer(networkURI, externalAddress, amount); emit ApproveExternalTransfer( _msgSender(), networkURI, externalAddress, amount ); } function externalTransfer( address from, string memory networkURI, bytes memory to, uint256 amount ) public override(ExternallyTransferable) onlySupplyManager whenNotPaused { require(isKycPassed(from), "Spender account requires KYC to continue."); require(!isFrozen(from), "Spender account is frozen."); uint256 exAllowance = externalAllowanceOf(from, networkURI, to); require(amount <= exAllowance, "Amount greater than allowance."); super._transfer(from, _supplyManager, amount); _burn(_supplyManager, amount); _approveExternalAllowance( from, networkURI, to, exAllowance.sub(amount) ); emit ExternalTransfer(from, networkURI, to, amount); } function externalTransferFrom( bytes memory from, string memory networkURI, address to, uint256 amount ) public override(ExternallyTransferable) onlySupplyManager whenNotPaused { require(isKycPassed(to), "Recipient account requires KYC to continue."); require(!isFrozen(to), "Recipient account is frozen."); _mint(_supplyManager, amount); super._transfer(_supplyManager, to, amount); emit ExternalTransferFrom(from, networkURI, to, amount); } /* * Allowances */ // Check Allowance Allowed (internal) function _beforeTokenAllowance( address sender, address spender, uint256 amount ) internal override(ERC20) requiresKYC requiresNotFrozen whenNotPaused { require(isKycPassed(spender), "Spender account requires KYC to continue."); require(isKycPassed(sender), "Sender account requires KYC to continue."); require(!isFrozen(spender), "Spender account is frozen."); require(!isFrozen(sender), "Sender account is frozen."); require(amount >= 0, "Allowance must be greater than 0."); } // Transfer From (allowance --> user) function transferFrom( address from, address to, uint256 amount ) public override(ERC20) requiresKYC requiresNotFrozen { super.transferFrom(from, to, amount); emit Transfer(from, to, amount); emit Approve(from, _msgSender(), allowance(from, _msgSender())); } // Approve Allowance function approveAllowance(address spender, uint256 amount) public override(ERC20) requiresKYC requiresNotFrozen { super._approve(_msgSender(), spender, amount); emit Approve(_msgSender(), spender, amount); } // Increase Allowance function increaseAllowance(address spender, uint256 amount) public override(ERC20) requiresKYC requiresNotFrozen { uint256 newAllowance = allowance(_msgSender(), spender).add(amount); _approve(_msgSender(), spender, newAllowance); emit IncreaseAllowance(_msgSender(), spender, newAllowance); } // Decrease Allowance function decreaseAllowance(address spender, uint256 amount) public override(ERC20) requiresKYC requiresNotFrozen { uint256 newAllowance = allowance(_msgSender(), spender).sub( amount, "Amount greater than allowance." ); _approve(_msgSender(), spender, newAllowance); emit DecreaseAllowance(_msgSender(), spender, newAllowance); } }
Pause: Pause entire contract
event Pause(address sender);
5,392,042
[ 1, 19205, 30, 31357, 7278, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 31357, 12, 2867, 5793, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xc258fF338322b6852C281936D4EdEff8AdfF23eE/sources/src/CommunalFarm.sol
For fast token address -> token ID lookups later Initialize the stored rewards Initialize the reward managers
) Owned(_owner){ stakingToken = IERC20(_stakingToken); rewardTokens = _rewardTokens; rewardRates = _rewardRates; rewardSymbols = _rewardSymbols; for (uint256 i = 0; i < _rewardTokens.length; i++){ rewardTokenAddrToIdx[_rewardTokens[i]] = i; rewardsPerTokenStored.push(0); rewardManagers[_rewardTokens[i]] = _rewardManagers[i]; } periodFinish = block.timestamp.add(rewardsDuration); }
4,833,471
[ 1, 1290, 4797, 1147, 1758, 317, 1147, 1599, 20286, 5137, 9190, 326, 4041, 283, 6397, 9190, 326, 19890, 21103, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 14223, 11748, 24899, 8443, 15329, 203, 3639, 384, 6159, 1345, 273, 467, 654, 39, 3462, 24899, 334, 6159, 1345, 1769, 203, 203, 3639, 19890, 5157, 273, 389, 266, 2913, 5157, 31, 203, 3639, 19890, 20836, 273, 389, 266, 2913, 20836, 31, 203, 3639, 19890, 14821, 273, 389, 266, 2913, 14821, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 266, 2913, 5157, 18, 2469, 31, 277, 27245, 95, 7010, 5411, 19890, 1345, 3178, 774, 4223, 63, 67, 266, 2913, 5157, 63, 77, 13563, 273, 277, 31, 203, 203, 5411, 283, 6397, 2173, 1345, 18005, 18, 6206, 12, 20, 1769, 203, 203, 5411, 19890, 17570, 63, 67, 266, 2913, 5157, 63, 77, 13563, 273, 389, 266, 2913, 17570, 63, 77, 15533, 203, 3639, 289, 203, 203, 203, 3639, 3879, 11641, 273, 1203, 18, 5508, 18, 1289, 12, 266, 6397, 5326, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-02-21 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // Part: IAddressResolver interface IAddressResolver { function key2address(bytes32 key) external view returns(address); function address2key(address addr) external view returns(bytes32); function requireAndKey2Address(bytes32 name, string calldata reason) external view returns(address); function setAddress(bytes32 key, address addr) external; function setMultiAddress(bytes32[] memory keys, address[] memory addrs) external; function setKkAddr(bytes32 k1, bytes32 k2, address addr) external; function setMultiKKAddr(bytes32[] memory k1s, bytes32[] memory k2s, address[] memory addrs) external; function kk2addr(bytes32 k1, bytes32 k2) external view returns(address); function requireKKAddrs(bytes32 k1, bytes32 k2, string calldata reason) external view returns(address); } // Part: IBoringDAO interface IBoringDAO { // function openTunnel(bytes32 tunnelKey) external; function pledge(bytes32 tunnelKey, uint _amount) external; function redeem(bytes32 tunnelKey, uint _amount) external; function approveMint(bytes32 tunnelKey, string memory _txid, uint _amount, address account, string memory assetAddress) external; function burnBToken(bytes32 _tunnelKey, uint _amount, string memory assetAddress) external; // function getTrustee(uint index) external view returns(address); // function getTrusteeCount() external view returns(uint); } // Part: IMintProposal interface IMintProposal { function approve( bytes32 _tunnelKey, string memory _txid, uint256 _amount, address to, address trustee, uint256 trusteeCount ) external returns (bool); } // Part: IOracle interface IOracle { function setPrice(bytes32 _symbol, uint _price) external; function getPrice(bytes32 _symbol) external view returns (uint); } // Part: IPaused interface IPaused { function paused() external view returns (bool); } // Part: ITrusteeFeePool interface ITrusteeFeePool { function exit(address account) external; function enter(address account) external; function notifyReward(uint reward) external; } // Part: ITunnel interface ITunnel { function pledge(address account, uint amount) external; function redeem(address account, uint amount) external; function issue(address account, uint amount) external; function burn(address account, uint amount, string memory assetAddress) external; function totalValuePledge() external view returns(uint); function canIssueAmount() external view returns(uint); function oTokenKey() external view returns(bytes32); } // Part: ITunnelV2 interface ITunnelV2 { function pledge(address account, uint amount) external; function redeem(address account, uint amount) external; function issue(address account, uint amount) external; function burn(address account, uint amount, string memory assetAddress) external; function totalValuePledge() external view returns(uint); function canIssueAmount() external view returns(uint); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Part: OpenZeppelin/[email protected]/EnumerableSet /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: OpenZeppelin/[email protected]/AccessControl /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // Part: OpenZeppelin/[email protected]/Ownable /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Part: OpenZeppelin/[email protected]/Pausable /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // Part: SafeDecimalMath // https://docs.synthetix.io/contracts/SafeDecimalMath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } // Part: ParamBook contract ParamBook is Ownable { mapping(bytes32 => uint256) public params; mapping(bytes32 => mapping(bytes32 => uint256)) public params2; function setParams(bytes32 name, uint256 value) public onlyOwner { params[name] = value; } function setMultiParams(bytes32[] memory names, uint[] memory values) public onlyOwner { require(names.length == values.length, "ParamBook::setMultiParams:param length not match"); for (uint i=0; i < names.length; i++ ) { params[names[i]] = values[i]; } } function setParams2( bytes32 name1, bytes32 name2, uint256 value ) public onlyOwner { params2[name1][name2] = value; } function setMultiParams2(bytes32[] memory names1, bytes32[] memory names2, uint[] memory values) public onlyOwner { require(names1.length == names2.length, "ParamBook::setMultiParams2:param length not match"); require(names1.length == values.length, "ParamBook::setMultiParams2:param length not match"); for(uint i=0; i < names1.length; i++) { params2[names1[i]][names2[i]] = values[i]; } } } // File: BoringDAOV2.sol /** @notice The BoringDAO contract is the entrance to the entire system, providing the functions of pledge BOR, redeem BOR, mint bBTC, and destroy bBTC */ contract BoringDAOV2 is AccessControl, IBoringDAO, Pausable { using SafeDecimalMath for uint256; using SafeMath for uint256; uint256 public amountByMint; bytes32 public constant MONITOR_ROLE = "MONITOR_ROLE "; bytes32 public constant GOV_ROLE = "GOV_ROLE"; bytes32 public constant BOR = "BOR"; bytes32 public constant PARAM_BOOK = "ParamBook"; bytes32 public constant MINT_PROPOSAL = "MintProposal"; bytes32 public constant ORACLE = "Oracle"; bytes32 public constant TRUSTEE_FEE_POOL = "TrusteeFeePool"; bytes32 public constant OTOKEN = "oToken"; bytes32 public constant TUNNEL_MINT_FEE_RATE = "mint_fee"; bytes32 public constant NETWORK_FEE = "network_fee"; IAddressResolver public addrReso; // tunnels ITunnelV2[] public tunnels; uint256 public mintCap; address public mine; // The user may not provide the Ethereum address or the format of the Ethereum address is wrong when mint. // this is for a transaction mapping(string=>bool) public approveFlag; uint public reductionAmount=1000e18; constructor(IAddressResolver _addrReso, uint _mintCap, address _mine) public { // set up resolver addrReso = _addrReso; mintCap = _mintCap; mine = _mine; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MONITOR_ROLE, msg.sender); } function tunnel(bytes32 tunnelKey) internal view returns (ITunnel) { return ITunnel(addrReso.key2address(tunnelKey)); } function otoken(bytes32 _tunnelKey) internal view returns (IERC20) { return IERC20(addrReso.requireKKAddrs(_tunnelKey, OTOKEN, "oToken not exist")); } function borERC20() internal view returns (IERC20) { return IERC20(addrReso.key2address(BOR)); } function paramBook() internal view returns (ParamBook) { return ParamBook(addrReso.key2address(PARAM_BOOK)); } function mintProposal() internal view returns (IMintProposal) { return IMintProposal(addrReso.key2address(MINT_PROPOSAL)); } function oracle() internal view returns (IOracle) { return IOracle(addrReso.key2address(ORACLE)); } // trustee fee pool key function trusteeFeePool(bytes32 _tunnelKey) internal view returns (ITrusteeFeePool) { return ITrusteeFeePool(addrReso.requireKKAddrs(_tunnelKey, TRUSTEE_FEE_POOL, "BoringDAO::TrusteeFeePool is address(0)")); } // trustee fee pool key => tfpk function addTrustee(address account, bytes32 _tunnelKey) public onlyAdmin { _setupRole(_tunnelKey, account); trusteeFeePool(_tunnelKey).enter(account); } function addTrustees(address[] memory accounts, bytes32 _tunnelKey) external onlyAdmin{ for (uint256 i = 0; i < accounts.length; i++) { addTrustee(accounts[i], _tunnelKey); } } function removeTrustee(address account, bytes32 _tunnelKey) public onlyAdmin { revokeRole(_tunnelKey, account); trusteeFeePool(_tunnelKey).exit(account); } function setMine(address _mine) public onlyAdmin { mine = _mine; } function setMintCap(uint256 amount) public onlyAdmin { mintCap = amount; } /** @notice tunnelKey is byte32("symbol"), eg. bytes32("BTC") */ function pledge(bytes32 _tunnelKey, uint256 _amount) public override whenNotPaused whenContractExist(_tunnelKey) { require( borERC20().allowance(msg.sender, address(this)) >= _amount, "not allow enough bor" ); borERC20().transferFrom( msg.sender, address(tunnel(_tunnelKey)), _amount ); tunnel(_tunnelKey).pledge(msg.sender, _amount); } /** @notice redeem bor from tunnel */ function redeem(bytes32 _tunnelKey, uint256 _amount) public override whenNotPaused whenContractExist(_tunnelKey) { tunnel(_tunnelKey).redeem(msg.sender, _amount); } function burnBToken(bytes32 _tunnelKey, uint256 amount, string memory assetAddress) public override whenNotPaused whenContractExist(_tunnelKey) whenTunnelNotPause(_tunnelKey) { tunnel(_tunnelKey).burn(msg.sender, amount, assetAddress); } /** @notice trustee will call the function to approve mint bToken @param _txid the transaction id of bitcoin @param _amount the amount to mint, 1BTC = 1bBTC = 1*10**18 weibBTC @param to mint to the address */ function approveMint( bytes32 _tunnelKey, string memory _txid, uint256 _amount, address to, string memory assetAddress ) public override whenNotPaused whenTunnelNotPause(_tunnelKey) onlyTrustee(_tunnelKey) { if(to == address(0)) { if (approveFlag[_txid] == false) { approveFlag[_txid] = true; emit ETHAddressNotExist(_tunnelKey, _txid, _amount, to, msg.sender, assetAddress); } return; } uint256 trusteeCount = getRoleMemberCount(_tunnelKey); bool shouldMint = mintProposal().approve( _tunnelKey, _txid, _amount, to, msg.sender, trusteeCount ); if (!shouldMint) { return; } uint256 canIssueAmount = tunnel(_tunnelKey).canIssueAmount(); if (_amount.add(otoken(_tunnelKey).totalSupply()) > canIssueAmount) { emit NotEnoughPledgeValue( _tunnelKey, _txid, _amount, to, msg.sender, assetAddress ); return; } // fee calculate in tunnel tunnel(_tunnelKey).issue(to, _amount); uint borMintAmount = calculateMintBORAmount(_tunnelKey, _amount); if(borMintAmount != 0) { amountByMint = amountByMint.add(borMintAmount); borERC20().transferFrom(mine, to, borMintAmount); } emit ApproveMintSuccess(_tunnelKey, _txid, _amount, to, assetAddress); } function calculateMintBORAmount(bytes32 _tunnelKey, uint _amount) public view returns (uint) { if (amountByMint >= mintCap || _amount == 0) { return 0; } uint256 assetPrice = oracle().getPrice(_tunnelKey); uint256 borPrice = oracle().getPrice(BOR); //LTC for 1000 uint256 reductionTimes = amountByMint.div(reductionAmount); uint256 mintFeeRate = paramBook().params2( _tunnelKey, TUNNEL_MINT_FEE_RATE ); // for decimal calculation, so mul 1e18 uint256 reductionFactor = (4**reductionTimes).mul(1e18).div(5**reductionTimes); uint networkFee = paramBook().params2(_tunnelKey, NETWORK_FEE); uint baseAmount = _amount.multiplyDecimalRound(mintFeeRate).mul(2).add(networkFee); uint borAmount = assetPrice.multiplyDecimalRound(baseAmount).multiplyDecimalRound(reductionFactor).divideDecimalRound(borPrice); if (amountByMint.add(borAmount) >= mintCap) { borAmount = mintCap.sub(amountByMint); } return borAmount; } function pause() public onlyMonitor{ _pause(); } function unpause() public onlyMonitor{ _unpause(); } modifier onlyTrustee(bytes32 _tunnelKey) { require(hasRole(_tunnelKey, msg.sender), "Caller is not trustee"); _; } modifier onlyAdmin { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "BoringDAO::caller is not admin"); _; } modifier onlyMonitor { require( hasRole(MONITOR_ROLE, msg.sender), "Caller is not monitor" ); _; } modifier whenContractExist(bytes32 key) { require( addrReso.key2address(key) != address(0), "Contract not exist" ); _; } modifier whenTunnelNotPause(bytes32 _tunnelKey) { address tunnelAddress = addrReso.requireAndKey2Address(_tunnelKey, "tunnel not exist"); require(IPaused(tunnelAddress).paused() == false, "tunnel is paused"); _; } event NotEnoughPledgeValue( bytes32 indexed _tunnelKey, string indexed _txid, uint256 _amount, address to, address trustee, string assetAddress ); event ApproveMintSuccess( bytes32 _tunnelKey, string _txid, uint256 _amount, address to, string assetAddress ); event ETHAddressNotExist( bytes32 _tunnelKey, string _txid, uint256 _amount, address to, address trustee, string assetAddress ); }
/ tunnels The user may not provide the Ethereum address or the format of the Ethereum address is wrong when mint. this is for a transaction
contract BoringDAOV2 is AccessControl, IBoringDAO, Pausable { using SafeDecimalMath for uint256; using SafeMath for uint256; uint256 public amountByMint; bytes32 public constant MONITOR_ROLE = "MONITOR_ROLE "; bytes32 public constant GOV_ROLE = "GOV_ROLE"; bytes32 public constant BOR = "BOR"; bytes32 public constant PARAM_BOOK = "ParamBook"; bytes32 public constant MINT_PROPOSAL = "MintProposal"; bytes32 public constant ORACLE = "Oracle"; bytes32 public constant TRUSTEE_FEE_POOL = "TrusteeFeePool"; bytes32 public constant OTOKEN = "oToken"; bytes32 public constant TUNNEL_MINT_FEE_RATE = "mint_fee"; bytes32 public constant NETWORK_FEE = "network_fee"; IAddressResolver public addrReso; ITunnelV2[] public tunnels; uint256 public mintCap; address public mine; mapping(string=>bool) public approveFlag; uint public reductionAmount=1000e18; @notice The BoringDAO contract is the entrance to the entire system, providing the functions of pledge BOR, redeem BOR, mint bBTC, and destroy bBTC constructor(IAddressResolver _addrReso, uint _mintCap, address _mine) public { addrReso = _addrReso; mintCap = _mintCap; mine = _mine; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MONITOR_ROLE, msg.sender); } function tunnel(bytes32 tunnelKey) internal view returns (ITunnel) { return ITunnel(addrReso.key2address(tunnelKey)); } function otoken(bytes32 _tunnelKey) internal view returns (IERC20) { return IERC20(addrReso.requireKKAddrs(_tunnelKey, OTOKEN, "oToken not exist")); } function borERC20() internal view returns (IERC20) { return IERC20(addrReso.key2address(BOR)); } function paramBook() internal view returns (ParamBook) { return ParamBook(addrReso.key2address(PARAM_BOOK)); } function mintProposal() internal view returns (IMintProposal) { return IMintProposal(addrReso.key2address(MINT_PROPOSAL)); } function oracle() internal view returns (IOracle) { return IOracle(addrReso.key2address(ORACLE)); } function trusteeFeePool(bytes32 _tunnelKey) internal view returns (ITrusteeFeePool) { return ITrusteeFeePool(addrReso.requireKKAddrs(_tunnelKey, TRUSTEE_FEE_POOL, "BoringDAO::TrusteeFeePool is address(0)")); } function addTrustee(address account, bytes32 _tunnelKey) public onlyAdmin { _setupRole(_tunnelKey, account); trusteeFeePool(_tunnelKey).enter(account); } function addTrustees(address[] memory accounts, bytes32 _tunnelKey) external onlyAdmin{ for (uint256 i = 0; i < accounts.length; i++) { addTrustee(accounts[i], _tunnelKey); } } function addTrustees(address[] memory accounts, bytes32 _tunnelKey) external onlyAdmin{ for (uint256 i = 0; i < accounts.length; i++) { addTrustee(accounts[i], _tunnelKey); } } function removeTrustee(address account, bytes32 _tunnelKey) public onlyAdmin { revokeRole(_tunnelKey, account); trusteeFeePool(_tunnelKey).exit(account); } function setMine(address _mine) public onlyAdmin { mine = _mine; } function setMintCap(uint256 amount) public onlyAdmin { mintCap = amount; } @notice tunnelKey is byte32("symbol"), eg. bytes32("BTC") function pledge(bytes32 _tunnelKey, uint256 _amount) public override whenNotPaused whenContractExist(_tunnelKey) { require( borERC20().allowance(msg.sender, address(this)) >= _amount, "not allow enough bor" ); borERC20().transferFrom( msg.sender, address(tunnel(_tunnelKey)), _amount ); tunnel(_tunnelKey).pledge(msg.sender, _amount); } @notice redeem bor from tunnel function redeem(bytes32 _tunnelKey, uint256 _amount) public override whenNotPaused whenContractExist(_tunnelKey) { tunnel(_tunnelKey).redeem(msg.sender, _amount); } function burnBToken(bytes32 _tunnelKey, uint256 amount, string memory assetAddress) public override whenNotPaused whenContractExist(_tunnelKey) whenTunnelNotPause(_tunnelKey) { tunnel(_tunnelKey).burn(msg.sender, amount, assetAddress); } @notice trustee will call the function to approve mint bToken @param _txid the transaction id of bitcoin @param _amount the amount to mint, 1BTC = 1bBTC = 1*10**18 weibBTC @param to mint to the address function approveMint( bytes32 _tunnelKey, string memory _txid, uint256 _amount, address to, string memory assetAddress ) public override whenNotPaused whenTunnelNotPause(_tunnelKey) onlyTrustee(_tunnelKey) { if(to == address(0)) { if (approveFlag[_txid] == false) { approveFlag[_txid] = true; emit ETHAddressNotExist(_tunnelKey, _txid, _amount, to, msg.sender, assetAddress); } return; } uint256 trusteeCount = getRoleMemberCount(_tunnelKey); bool shouldMint = mintProposal().approve( _tunnelKey, _txid, _amount, to, msg.sender, trusteeCount ); if (!shouldMint) { return; } uint256 canIssueAmount = tunnel(_tunnelKey).canIssueAmount(); if (_amount.add(otoken(_tunnelKey).totalSupply()) > canIssueAmount) { emit NotEnoughPledgeValue( _tunnelKey, _txid, _amount, to, msg.sender, assetAddress ); return; } uint borMintAmount = calculateMintBORAmount(_tunnelKey, _amount); if(borMintAmount != 0) { amountByMint = amountByMint.add(borMintAmount); borERC20().transferFrom(mine, to, borMintAmount); } emit ApproveMintSuccess(_tunnelKey, _txid, _amount, to, assetAddress); } @notice trustee will call the function to approve mint bToken @param _txid the transaction id of bitcoin @param _amount the amount to mint, 1BTC = 1bBTC = 1*10**18 weibBTC @param to mint to the address function approveMint( bytes32 _tunnelKey, string memory _txid, uint256 _amount, address to, string memory assetAddress ) public override whenNotPaused whenTunnelNotPause(_tunnelKey) onlyTrustee(_tunnelKey) { if(to == address(0)) { if (approveFlag[_txid] == false) { approveFlag[_txid] = true; emit ETHAddressNotExist(_tunnelKey, _txid, _amount, to, msg.sender, assetAddress); } return; } uint256 trusteeCount = getRoleMemberCount(_tunnelKey); bool shouldMint = mintProposal().approve( _tunnelKey, _txid, _amount, to, msg.sender, trusteeCount ); if (!shouldMint) { return; } uint256 canIssueAmount = tunnel(_tunnelKey).canIssueAmount(); if (_amount.add(otoken(_tunnelKey).totalSupply()) > canIssueAmount) { emit NotEnoughPledgeValue( _tunnelKey, _txid, _amount, to, msg.sender, assetAddress ); return; } uint borMintAmount = calculateMintBORAmount(_tunnelKey, _amount); if(borMintAmount != 0) { amountByMint = amountByMint.add(borMintAmount); borERC20().transferFrom(mine, to, borMintAmount); } emit ApproveMintSuccess(_tunnelKey, _txid, _amount, to, assetAddress); } @notice trustee will call the function to approve mint bToken @param _txid the transaction id of bitcoin @param _amount the amount to mint, 1BTC = 1bBTC = 1*10**18 weibBTC @param to mint to the address function approveMint( bytes32 _tunnelKey, string memory _txid, uint256 _amount, address to, string memory assetAddress ) public override whenNotPaused whenTunnelNotPause(_tunnelKey) onlyTrustee(_tunnelKey) { if(to == address(0)) { if (approveFlag[_txid] == false) { approveFlag[_txid] = true; emit ETHAddressNotExist(_tunnelKey, _txid, _amount, to, msg.sender, assetAddress); } return; } uint256 trusteeCount = getRoleMemberCount(_tunnelKey); bool shouldMint = mintProposal().approve( _tunnelKey, _txid, _amount, to, msg.sender, trusteeCount ); if (!shouldMint) { return; } uint256 canIssueAmount = tunnel(_tunnelKey).canIssueAmount(); if (_amount.add(otoken(_tunnelKey).totalSupply()) > canIssueAmount) { emit NotEnoughPledgeValue( _tunnelKey, _txid, _amount, to, msg.sender, assetAddress ); return; } uint borMintAmount = calculateMintBORAmount(_tunnelKey, _amount); if(borMintAmount != 0) { amountByMint = amountByMint.add(borMintAmount); borERC20().transferFrom(mine, to, borMintAmount); } emit ApproveMintSuccess(_tunnelKey, _txid, _amount, to, assetAddress); } @notice trustee will call the function to approve mint bToken @param _txid the transaction id of bitcoin @param _amount the amount to mint, 1BTC = 1bBTC = 1*10**18 weibBTC @param to mint to the address function approveMint( bytes32 _tunnelKey, string memory _txid, uint256 _amount, address to, string memory assetAddress ) public override whenNotPaused whenTunnelNotPause(_tunnelKey) onlyTrustee(_tunnelKey) { if(to == address(0)) { if (approveFlag[_txid] == false) { approveFlag[_txid] = true; emit ETHAddressNotExist(_tunnelKey, _txid, _amount, to, msg.sender, assetAddress); } return; } uint256 trusteeCount = getRoleMemberCount(_tunnelKey); bool shouldMint = mintProposal().approve( _tunnelKey, _txid, _amount, to, msg.sender, trusteeCount ); if (!shouldMint) { return; } uint256 canIssueAmount = tunnel(_tunnelKey).canIssueAmount(); if (_amount.add(otoken(_tunnelKey).totalSupply()) > canIssueAmount) { emit NotEnoughPledgeValue( _tunnelKey, _txid, _amount, to, msg.sender, assetAddress ); return; } uint borMintAmount = calculateMintBORAmount(_tunnelKey, _amount); if(borMintAmount != 0) { amountByMint = amountByMint.add(borMintAmount); borERC20().transferFrom(mine, to, borMintAmount); } emit ApproveMintSuccess(_tunnelKey, _txid, _amount, to, assetAddress); } @notice trustee will call the function to approve mint bToken @param _txid the transaction id of bitcoin @param _amount the amount to mint, 1BTC = 1bBTC = 1*10**18 weibBTC @param to mint to the address function approveMint( bytes32 _tunnelKey, string memory _txid, uint256 _amount, address to, string memory assetAddress ) public override whenNotPaused whenTunnelNotPause(_tunnelKey) onlyTrustee(_tunnelKey) { if(to == address(0)) { if (approveFlag[_txid] == false) { approveFlag[_txid] = true; emit ETHAddressNotExist(_tunnelKey, _txid, _amount, to, msg.sender, assetAddress); } return; } uint256 trusteeCount = getRoleMemberCount(_tunnelKey); bool shouldMint = mintProposal().approve( _tunnelKey, _txid, _amount, to, msg.sender, trusteeCount ); if (!shouldMint) { return; } uint256 canIssueAmount = tunnel(_tunnelKey).canIssueAmount(); if (_amount.add(otoken(_tunnelKey).totalSupply()) > canIssueAmount) { emit NotEnoughPledgeValue( _tunnelKey, _txid, _amount, to, msg.sender, assetAddress ); return; } uint borMintAmount = calculateMintBORAmount(_tunnelKey, _amount); if(borMintAmount != 0) { amountByMint = amountByMint.add(borMintAmount); borERC20().transferFrom(mine, to, borMintAmount); } emit ApproveMintSuccess(_tunnelKey, _txid, _amount, to, assetAddress); } tunnel(_tunnelKey).issue(to, _amount); @notice trustee will call the function to approve mint bToken @param _txid the transaction id of bitcoin @param _amount the amount to mint, 1BTC = 1bBTC = 1*10**18 weibBTC @param to mint to the address function approveMint( bytes32 _tunnelKey, string memory _txid, uint256 _amount, address to, string memory assetAddress ) public override whenNotPaused whenTunnelNotPause(_tunnelKey) onlyTrustee(_tunnelKey) { if(to == address(0)) { if (approveFlag[_txid] == false) { approveFlag[_txid] = true; emit ETHAddressNotExist(_tunnelKey, _txid, _amount, to, msg.sender, assetAddress); } return; } uint256 trusteeCount = getRoleMemberCount(_tunnelKey); bool shouldMint = mintProposal().approve( _tunnelKey, _txid, _amount, to, msg.sender, trusteeCount ); if (!shouldMint) { return; } uint256 canIssueAmount = tunnel(_tunnelKey).canIssueAmount(); if (_amount.add(otoken(_tunnelKey).totalSupply()) > canIssueAmount) { emit NotEnoughPledgeValue( _tunnelKey, _txid, _amount, to, msg.sender, assetAddress ); return; } uint borMintAmount = calculateMintBORAmount(_tunnelKey, _amount); if(borMintAmount != 0) { amountByMint = amountByMint.add(borMintAmount); borERC20().transferFrom(mine, to, borMintAmount); } emit ApproveMintSuccess(_tunnelKey, _txid, _amount, to, assetAddress); } function calculateMintBORAmount(bytes32 _tunnelKey, uint _amount) public view returns (uint) { if (amountByMint >= mintCap || _amount == 0) { return 0; } uint256 assetPrice = oracle().getPrice(_tunnelKey); uint256 borPrice = oracle().getPrice(BOR); uint256 mintFeeRate = paramBook().params2( _tunnelKey, TUNNEL_MINT_FEE_RATE ); uint networkFee = paramBook().params2(_tunnelKey, NETWORK_FEE); uint baseAmount = _amount.multiplyDecimalRound(mintFeeRate).mul(2).add(networkFee); uint borAmount = assetPrice.multiplyDecimalRound(baseAmount).multiplyDecimalRound(reductionFactor).divideDecimalRound(borPrice); if (amountByMint.add(borAmount) >= mintCap) { borAmount = mintCap.sub(amountByMint); } return borAmount; } function calculateMintBORAmount(bytes32 _tunnelKey, uint _amount) public view returns (uint) { if (amountByMint >= mintCap || _amount == 0) { return 0; } uint256 assetPrice = oracle().getPrice(_tunnelKey); uint256 borPrice = oracle().getPrice(BOR); uint256 mintFeeRate = paramBook().params2( _tunnelKey, TUNNEL_MINT_FEE_RATE ); uint networkFee = paramBook().params2(_tunnelKey, NETWORK_FEE); uint baseAmount = _amount.multiplyDecimalRound(mintFeeRate).mul(2).add(networkFee); uint borAmount = assetPrice.multiplyDecimalRound(baseAmount).multiplyDecimalRound(reductionFactor).divideDecimalRound(borPrice); if (amountByMint.add(borAmount) >= mintCap) { borAmount = mintCap.sub(amountByMint); } return borAmount; } uint256 reductionTimes = amountByMint.div(reductionAmount); uint256 reductionFactor = (4**reductionTimes).mul(1e18).div(5**reductionTimes); function calculateMintBORAmount(bytes32 _tunnelKey, uint _amount) public view returns (uint) { if (amountByMint >= mintCap || _amount == 0) { return 0; } uint256 assetPrice = oracle().getPrice(_tunnelKey); uint256 borPrice = oracle().getPrice(BOR); uint256 mintFeeRate = paramBook().params2( _tunnelKey, TUNNEL_MINT_FEE_RATE ); uint networkFee = paramBook().params2(_tunnelKey, NETWORK_FEE); uint baseAmount = _amount.multiplyDecimalRound(mintFeeRate).mul(2).add(networkFee); uint borAmount = assetPrice.multiplyDecimalRound(baseAmount).multiplyDecimalRound(reductionFactor).divideDecimalRound(borPrice); if (amountByMint.add(borAmount) >= mintCap) { borAmount = mintCap.sub(amountByMint); } return borAmount; } function pause() public onlyMonitor{ _pause(); } function unpause() public onlyMonitor{ _unpause(); } modifier onlyTrustee(bytes32 _tunnelKey) { require(hasRole(_tunnelKey, msg.sender), "Caller is not trustee"); _; } modifier onlyAdmin { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "BoringDAO::caller is not admin"); _; } modifier onlyMonitor { require( hasRole(MONITOR_ROLE, msg.sender), "Caller is not monitor" ); _; } modifier whenContractExist(bytes32 key) { require( addrReso.key2address(key) != address(0), "Contract not exist" ); _; } modifier whenTunnelNotPause(bytes32 _tunnelKey) { address tunnelAddress = addrReso.requireAndKey2Address(_tunnelKey, "tunnel not exist"); require(IPaused(tunnelAddress).paused() == false, "tunnel is paused"); _; } event NotEnoughPledgeValue( bytes32 indexed _tunnelKey, string indexed _txid, uint256 _amount, address to, address trustee, string assetAddress ); event ApproveMintSuccess( bytes32 _tunnelKey, string _txid, uint256 _amount, address to, string assetAddress ); event ETHAddressNotExist( bytes32 _tunnelKey, string _txid, uint256 _amount, address to, address trustee, string assetAddress ); }
2,079,248
[ 1, 19, 14825, 87, 1021, 729, 2026, 486, 5615, 326, 512, 18664, 379, 1758, 578, 326, 740, 434, 326, 512, 18664, 379, 1758, 353, 7194, 1347, 312, 474, 18, 333, 353, 364, 279, 2492, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 6053, 18485, 58, 22, 353, 24349, 16, 23450, 6053, 18485, 16, 21800, 16665, 288, 203, 565, 1450, 14060, 5749, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2254, 5034, 1071, 3844, 858, 49, 474, 31, 203, 203, 565, 1731, 1578, 1071, 5381, 30215, 30153, 67, 16256, 273, 315, 17667, 30153, 67, 16256, 13636, 203, 565, 1731, 1578, 1071, 5381, 12389, 58, 67, 16256, 273, 315, 16387, 58, 67, 16256, 14432, 203, 203, 565, 1731, 1578, 1071, 5381, 605, 916, 273, 315, 38, 916, 14432, 203, 565, 1731, 1578, 1071, 5381, 4655, 67, 28163, 273, 315, 786, 9084, 14432, 203, 565, 1731, 1578, 1071, 5381, 490, 3217, 67, 3373, 7057, 1013, 273, 315, 49, 474, 14592, 14432, 203, 565, 1731, 1578, 1071, 5381, 4869, 2226, 900, 273, 315, 23601, 14432, 203, 565, 1731, 1578, 1071, 5381, 4235, 5996, 9383, 67, 8090, 41, 67, 20339, 273, 315, 14146, 1340, 14667, 2864, 14432, 203, 565, 1731, 1578, 1071, 5381, 531, 8412, 273, 315, 83, 1345, 14432, 203, 203, 565, 1731, 1578, 1071, 5381, 399, 2124, 50, 2247, 67, 49, 3217, 67, 8090, 41, 67, 24062, 273, 315, 81, 474, 67, 21386, 14432, 203, 565, 1731, 1578, 1071, 5381, 15351, 10566, 67, 8090, 41, 273, 315, 5185, 67, 21386, 14432, 203, 203, 565, 467, 1887, 4301, 1071, 3091, 607, 83, 31, 203, 203, 565, 467, 20329, 58, 22, 8526, 1071, 14825, 87, 31, 203, 203, 565, 2254, 5034, 1071, 312, 474, 4664, 31, 203, 203, 565, 1758, 2 ]
pragma solidity ^0.4.16; /* * Abstract Token Smart Contract. Created in 2017 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.4.16; /* * ERC-20 Standard Token Smart Contract Interface. * Created in 2016–2017 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.4.16; /** * ERC-20 standard token interface, as defined * <a href="http://github.com/ethereum/EIPs/issues/20">here</a>. */ contract Token { /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () constant returns (uint256 supply); /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf (address _owner) constant returns (uint256 balance); /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) returns (bool success); /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) returns (bool success); /** * Allow given spender to transfer given number of tokens from message sender. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success); /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance (address _owner, address _spender) constant returns (uint256 remaining); /** * Logged when tokens were transferred from one owner to another. * * @param _from address of the owner, tokens were transferred from * @param _to address of the owner, tokens were transferred to * @param _value number of tokens transferred */ event Transfer (address indexed _from, address indexed _to, uint256 _value); /** * Logged when owner approved his tokens to be transferred by some spender. * * @param _owner owner who approved his tokens to be transferred * @param _spender spender who were allowed to transfer the tokens belonging * to the owner * @param _value number of tokens belonging to the owner, approved to be * transferred by the spender */ event Approval ( address indexed _owner, address indexed _spender, uint256 _value); } /* * Safe Math Smart Contract. Created in 2016–2017 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.4.16; /** * Provides methods to safely add, subtract and multiply uint256 numbers. */ contract SafeMath { uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Add two uint256 values, throw in case of overflow. * * @param x first value to add * @param y second value to add * @return x + y */ function safeAdd (uint256 x, uint256 y) constant internal returns (uint256 z) { assert (x <= MAX_UINT256 - y); return x + y; } /** * Subtract one uint256 value from another, throw in case of underflow. * * @param x value to subtract from * @param y value to subtract * @return x - y */ function safeSub (uint256 x, uint256 y) constant internal returns (uint256 z) { assert (x >= y); return x - y; } /** * Multiply two uint256 values, throw in case of overflow. * * @param x first value to multiply * @param y second value to multiply * @return x * y */ function safeMul (uint256 x, uint256 y) constant internal returns (uint256 z) { if (y == 0) return 0; // Prevent division by zero at the next line assert (x <= MAX_UINT256 / y); return x * y; } } /** * Abstract Token Smart Contract that could be used as a base contract for * ERC-20 token contracts. */ contract AbstractToken is Token, SafeMath { /** * Create new Abstract Token contract. */ function AbstractToken () { // Do nothing } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf (address _owner) constant returns (uint256 balance) { return accounts [_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) returns (bool success) { if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } Transfer (msg.sender, _to, _value); return true; } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) returns (bool success) { if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); if (_value > 0 && _from != _to) { accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } Transfer (_from, _to, _value); return true; } /** * Allow given spender to transfer given number of tokens from message sender. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance (address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; } /** * 1World Online2 token smart contract. */ contract OneWorldOnlineToken is AbstractToken { /** * Address of the owner of this smart contract. */ address private owner; /** * Total number of tokens in circulation. */ uint256 tokenCount; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new 1World Online2 token smart contract, with given number of tokens issued * and given to msg.sender, and make msg.sender the owner of this smart * contract. * * @param _tokenCount number of tokens to issue and give to msg.sender */ function OneWorldOnlineToken (uint256 _tokenCount) { owner = msg.sender; tokenCount = _tokenCount; accounts [msg.sender] = _tokenCount; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () constant returns (uint256 supply) { return tokenCount; } /** * Get name of this token. * * @return name of this token */ function name () constant returns (string result) { return "1World"; } /** * Get symbol of this token. * * @return symbol of this token */ function symbol () constant returns (string result) { return "1WO"; } /** * Get number of decimals for this token. * * @return number of decimals for this token */ function decimals () constant returns (uint8 result) { return 8; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) returns (bool success) { if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) returns (bool success) { if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, this method * receives assumed current allowance value as an argument. If actual * allowance differs from an assumed one, this method just returns false. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _currentValue assumed number of tokens currently allowed to be * transferred * @param _newValue number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _currentValue, uint256 _newValue) returns (bool success) { if (allowance (msg.sender, _spender) == _currentValue) return approve (_spender, _newValue); else return false; } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner (address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Freeze token transfers. * May only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; Freeze (); } } /** * Unfreeze token transfers. * May only be called by smart contract owner. */ function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; Unfreeze (); } } /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); }
* Address of the owner of this smart contract./* Total number of tokens in circulation./* True if tokens transfers are currently frozen, false otherwise./* Create new 1World Online2 token smart contract, with given number of tokens issued and given to msg.sender, and make msg.sender the owner of this smart contract. @param _tokenCount number of tokens to issue and give to msg.sender/
function OneWorldOnlineToken (uint256 _tokenCount) { owner = msg.sender; tokenCount = _tokenCount; accounts [msg.sender] = _tokenCount; }
1,003,142
[ 1, 1887, 434, 326, 3410, 434, 333, 13706, 6835, 18, 19, 10710, 1300, 434, 2430, 316, 5886, 1934, 367, 18, 19, 1053, 309, 2430, 29375, 854, 4551, 12810, 16, 629, 3541, 18, 19, 1788, 394, 404, 18071, 2755, 1369, 22, 1147, 13706, 6835, 16, 598, 864, 1300, 434, 2430, 16865, 471, 864, 358, 1234, 18, 15330, 16, 471, 1221, 1234, 18, 15330, 326, 3410, 434, 333, 13706, 6835, 18, 225, 389, 2316, 1380, 1300, 434, 2430, 358, 5672, 471, 8492, 358, 1234, 18, 15330, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 6942, 18071, 16860, 1345, 261, 11890, 5034, 389, 2316, 1380, 13, 288, 203, 565, 3410, 273, 1234, 18, 15330, 31, 203, 565, 1147, 1380, 273, 389, 2316, 1380, 31, 203, 565, 9484, 306, 3576, 18, 15330, 65, 273, 389, 2316, 1380, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x4ceda7906a5ed2179785cd3a40a69ee8bc99c466 //Contract name: Token //Balance: 0 Ether //Verification Date: 10/11/2017 //Transacion Count: 79391 // CODE STARTS HERE pragma solidity >=0.4.10; // from Zeppelin contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns (uint) { require(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; require(c>=a && c>=b); return c; } } contract Owned { address public owner; address newOwner; function Owned() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address _newOwner) onlyOwner { newOwner = _newOwner; } function acceptOwnership() { if (msg.sender == newOwner) { owner = newOwner; } } } contract IToken { function transfer(address _to, uint _value) returns (bool); function balanceOf(address owner) returns(uint); } // In case someone accidentally sends token to one of these contracts, // add a way to get them back out. contract TokenReceivable is Owned { function claimTokens(address _token, address _to) onlyOwner returns (bool) { IToken token = IToken(_token); return token.transfer(_to, token.balanceOf(this)); } } contract EventDefinitions { event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); event Burn(address indexed from, bytes32 indexed to, uint value); event Claimed(address indexed claimer, uint value); } contract Pausable is Owned { bool public paused; function pause() onlyOwner { paused = true; } function unpause() onlyOwner { paused = false; } modifier notPaused() { require(!paused); _; } } contract Finalizable is Owned { bool public finalized; function finalize() onlyOwner { finalized = true; } modifier notFinalized() { require(!finalized); _; } } contract Ledger is Owned, SafeMath, Finalizable { Controller public controller; mapping(address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint public totalSupply; uint public mintingNonce; bool public mintingStopped; /** * Used for updating the contract with proofs. Note that the logic * for guarding against unwanted actions happens in the controller. We only * specify onlyController here. * @notice: not yet used */ mapping(uint256 => bytes32) public proofs; /** * If bridge delivers currency back from the other network, it may be that we * want to lock it until the user is able to "claim" it. This mapping would store the * state of the unclaimed currency. * @notice: not yet used */ mapping(address => uint256) public locked; /** * As a precautionary measure, we may want to include a structure to store necessary * data should we find that we require additional information. * @notice: not yet used */ mapping(bytes32 => bytes32) public metadata; /** * Set by the controller to indicate where the transfers should go to on a burn */ address public burnAddress; /** * Mapping allowing us to identify the bridge nodes, in the current setup * manipulation of this mapping is only accessible by the parameter. */ mapping(address => bool) public bridgeNodes; // functions below this line are onlyOwner function Ledger() { } function setController(address _controller) onlyOwner notFinalized { controller = Controller(_controller); } /** * @dev To be called once minting is complete, disables minting. */ function stopMinting() onlyOwner { mintingStopped = true; } /** * @dev Used to mint a batch of currency at once. * * @notice This gives us a maximum of 2^96 tokens per user. * @notice Expected packed structure is [ADDR(20) | VALUE(12)]. * * @param nonce The minting nonce, an incorrect nonce is rejected. * @param bits An array of packed bytes of address, value mappings. * */ function multiMint(uint nonce, uint256[] bits) onlyOwner { require(!mintingStopped); if (nonce != mintingNonce) return; mintingNonce += 1; uint256 lomask = (1 << 96) - 1; uint created = 0; for (uint i=0; i<bits.length; i++) { address a = address(bits[i]>>96); uint value = bits[i]&lomask; balanceOf[a] = balanceOf[a] + value; controller.ledgerTransfer(0, a, value); created += value; } totalSupply += created; } // functions below this line are onlyController modifier onlyController() { require(msg.sender == address(controller)); _; } function transfer(address _from, address _to, uint _value) onlyController returns (bool success) { if (balanceOf[_from] < _value) return false; balanceOf[_from] = safeSub(balanceOf[_from], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); return true; } function transferFrom(address _spender, address _from, address _to, uint _value) onlyController returns (bool success) { if (balanceOf[_from] < _value) return false; var allowed = allowance[_from][_spender]; if (allowed < _value) return false; balanceOf[_to] = safeAdd(balanceOf[_to], _value); balanceOf[_from] = safeSub(balanceOf[_from], _value); allowance[_from][_spender] = safeSub(allowed, _value); return true; } function approve(address _owner, address _spender, uint _value) onlyController returns (bool success) { // require user to set to zero before resetting to nonzero if ((_value != 0) && (allowance[_owner][_spender] != 0)) { return false; } allowance[_owner][_spender] = _value; return true; } function increaseApproval (address _owner, address _spender, uint _addedValue) onlyController returns (bool success) { uint oldValue = allowance[_owner][_spender]; allowance[_owner][_spender] = safeAdd(oldValue, _addedValue); return true; } function decreaseApproval (address _owner, address _spender, uint _subtractedValue) onlyController returns (bool success) { uint oldValue = allowance[_owner][_spender]; if (_subtractedValue > oldValue) { allowance[_owner][_spender] = 0; } else { allowance[_owner][_spender] = safeSub(oldValue, _subtractedValue); } return true; } function setProof(uint256 _key, bytes32 _proof) onlyController { proofs[_key] = _proof; } function setLocked(address _key, uint256 _value) onlyController { locked[_key] = _value; } function setMetadata(bytes32 _key, bytes32 _value) onlyController { metadata[_key] = _value; } /** * Burn related functionality */ /** * @dev sets the burn address to the new value * * @param _address The address * */ function setBurnAddress(address _address) onlyController { burnAddress = _address; } function setBridgeNode(address _address, bool enabled) onlyController { bridgeNodes[_address] = enabled; } } contract ControllerEventDefinitions { /** * An internal burn event, emitted by the controller contract * which the bridges could be listening to. */ event ControllerBurn(address indexed from, bytes32 indexed to, uint value); } /** * @title Controller for business logic between the ERC20 API and State * * Controller is responsible for the business logic that sits in between * the Ledger (model) and the Token (view). Presently, adherence to this model * is not strict, but we expect future functionality (Burning, Claiming) to adhere * to this model more closely. * * The controller must be linked to a Token and Ledger to become functional. * */ contract Controller is Owned, Finalizable, ControllerEventDefinitions { Ledger public ledger; Token public token; address public burnAddress; function Controller() { } // functions below this line are onlyOwner function setToken(address _token) onlyOwner { token = Token(_token); } function setLedger(address _ledger) onlyOwner { ledger = Ledger(_ledger); } /** * @dev Sets the burn address burn values get moved to. Only call * after token and ledger contracts have been hooked up. Ensures * that all three values are set atomically. * * @notice New Functionality * * @param _address desired address * */ function setBurnAddress(address _address) onlyOwner { burnAddress = _address; ledger.setBurnAddress(_address); token.setBurnAddress(_address); } modifier onlyToken() { require(msg.sender == address(token)); _; } modifier onlyLedger() { require(msg.sender == address(ledger)); _; } function totalSupply() constant returns (uint) { return ledger.totalSupply(); } function balanceOf(address _a) constant returns (uint) { return ledger.balanceOf(_a); } function allowance(address _owner, address _spender) constant returns (uint) { return ledger.allowance(_owner, _spender); } // functions below this line are onlyLedger // let the ledger send transfer events (the most obvious case // is when we mint directly to the ledger and need the Transfer() // events to appear in the token) function ledgerTransfer(address from, address to, uint val) onlyLedger { token.controllerTransfer(from, to, val); } // functions below this line are onlyToken function transfer(address _from, address _to, uint _value) onlyToken returns (bool success) { return ledger.transfer(_from, _to, _value); } function transferFrom(address _spender, address _from, address _to, uint _value) onlyToken returns (bool success) { return ledger.transferFrom(_spender, _from, _to, _value); } function approve(address _owner, address _spender, uint _value) onlyToken returns (bool success) { return ledger.approve(_owner, _spender, _value); } function increaseApproval (address _owner, address _spender, uint _addedValue) onlyToken returns (bool success) { return ledger.increaseApproval(_owner, _spender, _addedValue); } function decreaseApproval (address _owner, address _spender, uint _subtractedValue) onlyToken returns (bool success) { return ledger.decreaseApproval(_owner, _spender, _subtractedValue); } /** * End Original Contract * Below is new functionality */ /** * @dev Enables burning on the token contract */ function enableBurning() onlyOwner { token.enableBurning(); } /** * @dev Disables burning on the token contract */ function disableBurning() onlyOwner { token.disableBurning(); } // public functions /** * @dev * * @param _from account the value is burned from * @param _to the address receiving the value * @param _amount the value amount * * @return success operation successful or not. */ function burn(address _from, bytes32 _to, uint _amount) onlyToken returns (bool success) { if (ledger.transfer(_from, burnAddress, _amount)) { ControllerBurn(_from, _to, _amount); token.controllerBurn(_from, _to, _amount); return true; } return false; } /** * @dev Implementation for claim mechanism. Note that this mechanism has not yet * been implemented. This function is only here for future expansion capabilities. * Presently, just returns false to indicate failure. * * @notice Only one of claimByProof() or claim() will potentially be activated in the future. * Depending on the functionality required and route selected. * * @param _claimer The individual claiming the tokens (also the recipient of said tokens). * @param data The input data required to release the tokens. * @param success The proofs associated with the data, to indicate the legitimacy of said data. * @param number The block number the proofs and data correspond to. * * @return success operation successful or not. * */ function claimByProof(address _claimer, bytes32[] data, bytes32[] proofs, uint256 number) onlyToken returns (bool success) { return false; } /** * @dev Implementation for an alternative claim mechanism, in which the participant * is not required to confirm through proofs. Note that this mechanism has not * yet been implemented. * * @notice Only one of claimByProof() or claim() will potentially be activated in the future. * Depending on the functionality required and route selected. * * @param _claimer The individual claiming the tokens (also the recipient of said tokens). * * @return success operation successful or not. */ function claim(address _claimer) onlyToken returns (bool success) { return false; } } contract Token is Finalizable, TokenReceivable, SafeMath, EventDefinitions, Pausable { // Set these appropriately before you deploy string constant public name = "AION"; uint8 constant public decimals = 8; string constant public symbol = "AION"; Controller public controller; string public motd; event Motd(string message); address public burnAddress; //@ATTENTION: set this to a correct value bool public burnable = false; // functions below this line are onlyOwner // set "message of the day" function setMotd(string _m) onlyOwner { motd = _m; Motd(_m); } function setController(address _c) onlyOwner notFinalized { controller = Controller(_c); } // functions below this line are public function balanceOf(address a) constant returns (uint) { return controller.balanceOf(a); } function totalSupply() constant returns (uint) { return controller.totalSupply(); } function allowance(address _owner, address _spender) constant returns (uint) { return controller.allowance(_owner, _spender); } function transfer(address _to, uint _value) notPaused returns (bool success) { if (controller.transfer(msg.sender, _to, _value)) { Transfer(msg.sender, _to, _value); return true; } return false; } function transferFrom(address _from, address _to, uint _value) notPaused returns (bool success) { if (controller.transferFrom(msg.sender, _from, _to, _value)) { Transfer(_from, _to, _value); return true; } return false; } function approve(address _spender, uint _value) notPaused returns (bool success) { // promote safe user behavior if (controller.approve(msg.sender, _spender, _value)) { Approval(msg.sender, _spender, _value); return true; } return false; } function increaseApproval (address _spender, uint _addedValue) notPaused returns (bool success) { if (controller.increaseApproval(msg.sender, _spender, _addedValue)) { uint newval = controller.allowance(msg.sender, _spender); Approval(msg.sender, _spender, newval); return true; } return false; } function decreaseApproval (address _spender, uint _subtractedValue) notPaused returns (bool success) { if (controller.decreaseApproval(msg.sender, _spender, _subtractedValue)) { uint newval = controller.allowance(msg.sender, _spender); Approval(msg.sender, _spender, newval); return true; } return false; } // modifier onlyPayloadSize(uint numwords) { // assert(msg.data.length >= numwords * 32 + 4); // _; // } // functions below this line are onlyController modifier onlyController() { assert(msg.sender == address(controller)); _; } // In the future, when the controller supports multiple token // heads, allow the controller to reconstitute the transfer and // approval history. function controllerTransfer(address _from, address _to, uint _value) onlyController { Transfer(_from, _to, _value); } function controllerApprove(address _owner, address _spender, uint _value) onlyController { Approval(_owner, _spender, _value); } /** * @dev Burn event possibly called by the controller on a burn. This is * the public facing event that anyone can track, the bridges listen * to an alternative event emitted by the controller. * * @param _from address that coins are burned from * @param _to address (on other network) that coins are received by * @param _value amount of value to be burned * * @return { description_of_the_return_value } */ function controllerBurn(address _from, bytes32 _to, uint256 _value) onlyController { Burn(_from, _to, _value); } function controllerClaim(address _claimer, uint256 _value) onlyController { Claimed(_claimer, _value); } /** * @dev Sets the burn address to a new value * * @param _address The address * */ function setBurnAddress(address _address) onlyController { burnAddress = _address; } /** * @dev Enables burning through burnable bool * */ function enableBurning() onlyController { burnable = true; } /** * @dev Disables burning through burnable bool * */ function disableBurning() onlyController { burnable = false; } /** * @dev Indicates that burning is enabled */ modifier burnEnabled() { require(burnable == true); _; } /** * @dev burn function, changed from original implementation. Public facing API * indicating who the token holder wants to burn currency to and the amount. * * @param _amount The amount * */ function burn(bytes32 _to, uint _amount) notPaused burnEnabled returns (bool success) { return controller.burn(msg.sender, _to, _amount); } /** * @dev claim (quantumReceive) allows the user to "prove" some an ICT to the contract * thereby thereby releasing the tokens into their account * */ function claimByProof(bytes32[] data, bytes32[] proofs, uint256 number) notPaused burnEnabled returns (bool success) { return controller.claimByProof(msg.sender, data, proofs, number); } /** * @dev Simplified version of claim, just requires user to call to claim. * No proof is needed, which version is chosen depends on our bridging model. * * @return */ function claim() notPaused burnEnabled returns (bool success) { return controller.claim(msg.sender); } }
* @dev Disables burning through burnable bool/
function disableBurning() onlyController { burnable = false; }
2,529,436
[ 1, 1669, 1538, 18305, 310, 3059, 18305, 429, 1426, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4056, 38, 321, 310, 1435, 1338, 2933, 288, 203, 3639, 18305, 429, 273, 629, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xcc000017BeEDCBc7fAb3e57FAB3Cb72c2D00a343/sources/@gearbox-protocol/core-v2/contracts/interfaces/ICreditFacade.sol
CREDIT ACCOUNT MANAGEMENT GETTERS
{ function openCreditAccount( uint256 amount, address onBehalfOf, uint16 leverageFactor, uint16 referralCode ) external payable; function openCreditAccountMulticall( uint256 borrowedAmount, address onBehalfOf, MultiCall[] calldata calls, uint16 referralCode ) external payable; function closeCreditAccount( address to, uint256 skipTokenMask, MultiCall[] calldata calls ) external payable; function closeCreditAccount( address to, uint256 skipTokenMask, bool convertWETH, MultiCall[] calldata calls ) external payable; function liquidateCreditAccount( address borrower, address to, uint256 skipTokenMask, MultiCall[] calldata calls ) external payable; function liquidateCreditAccount( address borrower, address to, uint256 skipTokenMask, bool convertWETH, MultiCall[] calldata calls ) external payable; function liquidateExpiredCreditAccount( address borrower, address to, uint256 skipTokenMask, MultiCall[] calldata calls ) external payable; function liquidateExpiredCreditAccount( address borrower, address to, uint256 skipTokenMask, bool convertWETH, MultiCall[] calldata calls ) external payable; function addCollateral( address onBehalfOf, address token, uint256 amount ) external payable; function multicall(MultiCall[] calldata calls) external payable; function hasOpenedCreditAccount(address borrower) external view returns (bool); function approveAccountTransfer(address from, bool state) external; function transferAccountOwnership(address to) external; function calcTotalValue(address creditAccount) external view returns (uint256 total, uint256 twv); function calcCreditAccountHealthFactor(address creditAccount) external view returns (uint256 hf); function isTokenAllowed(address token) external view returns (bool); function creditManager() external view returns (ICreditManagerV2); function transfersAllowed(address from, address to) external view returns (bool); function params() external view returns ( uint128 maxBorrowedAmountPerBlock, bool isIncreaseDebtForbidden, uint40 expirationDate, uint16 emergencyLiquidationDiscount ); function limits() external view returns (uint128 minBorrowedAmount, uint128 maxBorrowedAmount); function lossParams() external view returns (uint128 currentCumulativeLoss, uint128 maxCumulativeLoss); function totalDebt() external view returns (uint128 currentTotalDebt, uint128 totalDebtLimit); function degenNFT() external view returns (address); function underlying() external view returns (address); function blacklistHelper() external view returns (address); function isBlacklistableUnderlying() external view returns (bool); } }
4,897,392
[ 1, 5458, 40, 1285, 29437, 20972, 2833, 3212, 17788, 1470, 11367, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 203, 565, 445, 1696, 16520, 3032, 12, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1758, 603, 1919, 20222, 951, 16, 203, 3639, 2254, 2313, 884, 5682, 6837, 16, 203, 3639, 2254, 2313, 1278, 370, 23093, 203, 565, 262, 3903, 8843, 429, 31, 203, 203, 565, 445, 1696, 16520, 3032, 5049, 335, 454, 12, 203, 3639, 2254, 5034, 29759, 329, 6275, 16, 203, 3639, 1758, 603, 1919, 20222, 951, 16, 203, 3639, 5991, 1477, 8526, 745, 892, 4097, 16, 203, 3639, 2254, 2313, 1278, 370, 23093, 203, 565, 262, 3903, 8843, 429, 31, 203, 203, 565, 445, 1746, 16520, 3032, 12, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 2488, 1345, 5796, 16, 203, 3639, 5991, 1477, 8526, 745, 892, 4097, 203, 565, 262, 3903, 8843, 429, 31, 203, 203, 565, 445, 1746, 16520, 3032, 12, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 2488, 1345, 5796, 16, 203, 3639, 1426, 1765, 59, 1584, 44, 16, 203, 3639, 5991, 1477, 8526, 745, 892, 4097, 203, 565, 262, 3903, 8843, 429, 31, 203, 203, 565, 445, 4501, 26595, 340, 16520, 3032, 12, 203, 3639, 1758, 29759, 264, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 2488, 1345, 5796, 16, 203, 3639, 5991, 1477, 8526, 745, 892, 4097, 203, 565, 262, 3903, 8843, 429, 31, 203, 203, 565, 445, 4501, 26595, 340, 16520, 3032, 12, 203, 3639, 1758, 29759, 264, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 2488, 1345, 5796, 16, 203, 3639, 1426, 1765, 59, 1584, 2 ]
./full_match/3/0x8FFd8D83CF3eE5b72E93DEf6d1745187F802cf33/sources/https_/github.com/fifikobayashi/Robin-Hood-Attack/blob/main/Interfaces.sol
* @title LendingPoolAddressesProvider contract @dev Main registry of addresses part of or connected to the protocol, including permissioned roles - Acting also as factory of proxies and admin of those, so with right to change its implementations - Owned by the Aave Governance @author Aave/ Funcoes novas
interface ILendingPoolAddressesProvider { event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getLendingPoolCore() external view returns (address payable); function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; }
8,247,167
[ 1, 48, 2846, 2864, 7148, 2249, 6835, 225, 12740, 4023, 434, 6138, 1087, 434, 578, 5840, 358, 326, 1771, 16, 6508, 4132, 329, 4900, 300, 4603, 310, 2546, 487, 3272, 434, 13263, 471, 3981, 434, 5348, 16, 1427, 598, 2145, 358, 2549, 2097, 16164, 300, 14223, 11748, 635, 326, 432, 836, 611, 1643, 82, 1359, 225, 432, 836, 19, 131, 259, 2622, 83, 281, 1158, 4423, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 48, 2846, 2864, 7148, 2249, 288, 203, 225, 871, 511, 2846, 2864, 7381, 12, 2867, 8808, 394, 1887, 1769, 203, 225, 871, 4659, 4446, 7381, 12, 2867, 8808, 394, 1887, 1769, 203, 225, 871, 512, 6592, 75, 2075, 4446, 7381, 12, 2867, 8808, 394, 1887, 1769, 203, 225, 871, 511, 2846, 2864, 17182, 7381, 12, 2867, 8808, 394, 1887, 1769, 203, 225, 871, 511, 2846, 2864, 13535, 2045, 287, 1318, 7381, 12, 2867, 8808, 394, 1887, 1769, 203, 225, 871, 20137, 23601, 7381, 12, 2867, 8808, 394, 1887, 1769, 203, 225, 871, 511, 2846, 4727, 23601, 7381, 12, 2867, 8808, 394, 1887, 1769, 203, 225, 871, 7659, 6119, 12, 3890, 1578, 612, 16, 1758, 8808, 394, 1887, 1769, 203, 225, 871, 5267, 694, 12, 3890, 1578, 612, 16, 1758, 8808, 394, 1887, 16, 1426, 711, 3886, 1769, 203, 203, 225, 445, 9014, 2846, 2864, 4670, 1435, 3903, 1476, 1135, 261, 2867, 8843, 429, 1769, 203, 21281, 225, 445, 444, 1887, 12, 3890, 1578, 612, 16, 1758, 394, 1887, 13, 3903, 31, 203, 203, 225, 445, 444, 1887, 1463, 3886, 12, 3890, 1578, 612, 16, 1758, 9380, 13, 3903, 31, 203, 203, 225, 445, 14808, 12, 3890, 1578, 612, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 225, 445, 9014, 2846, 2864, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 225, 445, 444, 48, 2846, 2864, 2828, 12, 2867, 2845, 13, 3903, 31, 203, 203, 225, 445, 9014, 2846, 2864, 17182, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 225, 2 ]
./full_match/1/0xD3CEbEBd69AC363856808828562e08f8F6Cc7e94/sources/contracts/test.sol
Clear approvals from the previous owner
if(!_exists(tokenId)) { _mint(to, tokenId); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); }
3,212,623
[ 1, 9094, 6617, 4524, 628, 326, 2416, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 12, 5, 67, 1808, 12, 2316, 548, 3719, 288, 203, 5411, 389, 81, 474, 12, 869, 16, 1147, 548, 1769, 203, 5411, 389, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 377, 203, 5411, 389, 12908, 537, 12, 2867, 12, 20, 3631, 1147, 548, 1769, 203, 377, 203, 5411, 389, 4505, 5157, 63, 2080, 8009, 4479, 12, 2316, 548, 1769, 203, 5411, 389, 4505, 5157, 63, 869, 8009, 1289, 12, 2316, 548, 1769, 203, 377, 203, 5411, 389, 2316, 5460, 414, 18, 542, 12, 2316, 548, 16, 358, 1769, 203, 377, 203, 5411, 3626, 12279, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 3639, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; contract GgwpToken { //ERC-20 Token Standard: function name() public view returns (string) string public name = "GGWP Token"; //ERC-20 Token Standard: function symbol() public view returns (string) string public symbol = "GGWP"; //ERC-20 Token Standard: function decimals() public view returns (uint8) uint8 public decimals = 8; uint256 public totalGGWP; address private admin; event Transfer( address indexed _ggFrom, address indexed _ggTo, uint256 _value ); event Approval( address indexed _ggGranter, address indexed _ggBenefactor, uint256 _value ); //ERC-20 Token Standard: function balanceOf(address _owner) public view returns (uint256 balance) mapping(address => uint256) public balanceOf; //ERC-20 Token Standard: function allowance(address _owner, address _spender) public view returns (uint256 remaining) mapping(address => mapping(address => uint256)) public allowance; constructor(uint256 _initialSupply) public { admin = msg.sender; balanceOf[admin] = _initialSupply; totalGGWP = _initialSupply; } //ERC-20 Token Standard: function totalSupply() public view returns (uint256) function totalSupply() public view returns (uint256) { return totalGGWP; } //ERC-20 Token Standard: function transfer(address _to, uint256 _value) public returns (bool success) function transfer(address _to, uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } //ERC-20 Token Standard: function approve(address _spender, uint256 _value) public returns (bool success) function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } //ERC-20 Token Standard: function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= balanceOf[_from]); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } //custom implementation function grant(uint256 _value) public returns (bool success) { require(balanceOf[admin] >= _value); balanceOf[admin] -= _value; balanceOf[msg.sender] += _value; emit Transfer(admin, msg.sender, _value); return true; } }
ERC-20 Token Standard: function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= balanceOf[_from]); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; }
1,783,867
[ 1, 654, 39, 17, 3462, 3155, 8263, 30, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 24899, 1132, 1648, 11013, 951, 63, 67, 2080, 19226, 203, 3639, 2583, 24899, 1132, 1648, 1699, 1359, 63, 67, 2080, 6362, 3576, 18, 15330, 19226, 203, 203, 3639, 11013, 951, 63, 67, 2080, 65, 3947, 389, 1132, 31, 203, 3639, 11013, 951, 63, 67, 869, 65, 1011, 389, 1132, 31, 203, 203, 3639, 1699, 1359, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 3947, 389, 1132, 31, 203, 203, 3639, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xe4339363BEE0Be9C23f10179A00D7Ff2241263eb/sources/EtherFreeToken.sol
* @dev transfer token for a specified address @param _to The address to transfer to. @param _value The amount to be transferred./ SafeMath.sub will throw if there is not enough balance.
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); address addr = msg.sender; require(addr!= address(0)); require(_value <= balances[addr]); uint256 transBlalance = balances[addr].sub(lockValues[addr]); require(_value <= transBlalance); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
4,378,357
[ 1, 13866, 1147, 364, 279, 1269, 1758, 225, 389, 869, 1021, 1758, 358, 7412, 358, 18, 225, 389, 1132, 1021, 3844, 358, 506, 906, 4193, 18, 19, 14060, 10477, 18, 1717, 903, 604, 309, 1915, 353, 486, 7304, 11013, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 565, 1758, 3091, 273, 1234, 18, 15330, 31, 203, 565, 2583, 12, 4793, 5, 33, 1758, 12, 20, 10019, 203, 565, 2583, 24899, 1132, 1648, 324, 26488, 63, 4793, 19226, 203, 565, 2254, 5034, 906, 4802, 6112, 273, 324, 26488, 63, 4793, 8009, 1717, 12, 739, 1972, 63, 4793, 19226, 203, 565, 2583, 24899, 1132, 1648, 906, 4802, 6112, 1769, 203, 565, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 565, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 565, 3626, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 203, 225, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; contract DecentralizationSmartGames{ using SafeMath for uint256; string public constant name = "Decentralization Smart Games"; string public constant symbol = "DSG"; uint8 public constant decimals = 18; uint256 public constant tokenPrice = 0.00065 ether; uint256 public totalSupply; /* Total number of existing DSG tokens */ uint256 public divPerTokenPool; /* Trigger for calculating dividends on "Pool dividends" program */ uint256 public divPerTokenGaming; /* Trigger for calculating dividends on "Gaming dividends" program */ uint256 public developmentBalance; /* Balance that is used to support the project and games development */ uint256 public charityBalance; /* Balance that is used for charity */ address[2] public owners; /* Addresses of the contract owners */ address[2] public candidates; /* Addresses of the future contract owners */ /**Fee public fee - Structure where all percentages of the distribution of incoming funds are stored * uint8 fee.r0 - First referrer - 6% * uint8 fee.r1 - Second referrer - 4% * uint8 fee.r2 - Third referrer - 3% * uint8 fee.r3 - Fourth referrer - 2% * uint8 fee.r4 - Fifth referrer - 1% * uint8 fee.charity - Charity - 1% * uint8 fee.development - For game development and project support - 18% * uint8 fee.buy - For buying DSG tokens - 65% */ Fee public fee = Fee(6,4,3,2,1,1,18,65); /**Dividends public totalDividends - Structure where general dividend payments are kept * uint256 totalDividends.referrer - Referrer Dividends * uint256 totalDividends.gaming - Gaming Dividends * uint256 totalDividends.pool - Pool Dividends */ Dividends public totalDividends = Dividends(0,0,0); mapping (address => mapping (address => uint256)) private allowed; /**mapping (address => Account) private account - Investors accounts data * uint256 account[address].tokenBalance - Number of DSG tokens on balance * uint256 account[address].ethereumBalance - The amount of ETH on balance (dividends) * uint256 account[address].lastDivPerTokenPool - The trigger of last dividend payment upon the "Pool dividends" program * uint256 account[address].lastDivPerTokenGaming - The trigger of last dividend payment upon the "Gaming dividends" program * uint256 account[address].totalDividendsReferrer - Total amount of dividends upon the "Referrer dividends" program * uint256 account[address].totalDividendsGaming - Total amount of dividends upon the "Gaming dividends" program * uint256 account[address].totalDividendsPool -Total amount of dividends upon the "Pool dividends" program * address[5] account[address].referrer - Array of all the referrers * bool account[address].active - True, if the account is active */ mapping (address => Account) public account; mapping (address => bool) public games; /* The list of contracts from which dividends are allowed */ struct Account { uint256 tokenBalance; uint256 ethereumBalance; uint256 lastDivPerTokenPool; uint256 lastDivPerTokenGaming; uint256 totalDividendsReferrer; uint256 totalDividendsGaming; uint256 totalDividendsPool; address[5] referrer; bool active; } struct Fee{ uint8 r1; uint8 r2; uint8 r3; uint8 r4; uint8 r5; uint8 charity; uint8 development; uint8 buy; } struct Dividends{ uint256 referrer; uint256 gaming; uint256 pool; } /* Allowed if the address is not 0x */ modifier check0x(address address0x) { require(address0x != address(0), "Address is 0x"); _; } /* Allowed if on balance of DSG tokens >= amountDSG */ modifier checkDSG(uint256 amountDSG) { require(account[msg.sender].tokenBalance >= amountDSG, "You don't have enough DSG on balance"); _; } /* Allowed if on balance ETH >= amountETH */ modifier checkETH(uint256 amountETH) { require(account[msg.sender].ethereumBalance >= amountETH, "You don't have enough ETH on balance"); _; } /* Allowed if the function is called by one the contract owners */ modifier onlyOwners() { require(msg.sender == owners[0] || msg.sender == owners[1], "You are not owner"); _; } /* Allowed if the sale is still active */ modifier sellTime() { require(now <= 1560211200, "The sale is over"); _; } /* Dividends upon the "Pool Dividends" program are being paid */ /* Dividends upon the "Gaming Dividends" program are being paid */ modifier payDividends(address sender) { uint256 poolDividends = getPoolDividends(); uint256 gamingDividends = getGamingDividends(); if(poolDividends > 0 && account[sender].active == true){ account[sender].totalDividendsPool = account[sender].totalDividendsPool.add(poolDividends); account[sender].ethereumBalance = account[sender].ethereumBalance.add(poolDividends); } if(gamingDividends > 0 && account[sender].active == true){ account[sender].totalDividendsGaming = account[sender].totalDividendsGaming.add(gamingDividends); account[sender].ethereumBalance = account[sender].ethereumBalance.add(gamingDividends); } _; account[sender].lastDivPerTokenPool = divPerTokenPool; account[sender].lastDivPerTokenGaming = divPerTokenGaming; } /**We assign two contract owners, whose referrers are from the same address * In the same manner we activate their accounts */ constructor(address owner2) public{ address owner1 = msg.sender; owners[0] = owner1; owners[1] = owner2; account[owner1].active = true; account[owner2].active = true; account[owner1].referrer = [owner1, owner1, owner1, owner1, owner1]; account[owner2].referrer = [owner2, owner2, owner2, owner2, owner2]; } /**buy() - the function of buying DSG tokens. * It is active only during the time interval specified in sellTime() * Dividends upon Pool Dividends program are being paid * Dividends upon the Gaming Dividends program are being paid * address referrerAddress - The address of the referrer who invited to the program * require - Minimum purchase is 100 DSG or 0.1 ETH */ function buy(address referrerAddress) payDividends(msg.sender) sellTime public payable { require(msg.value >= 0.1 ether, "Minimum investment is 0.1 ETH"); uint256 forTokensPurchase = msg.value.mul(fee.buy).div(100); /* 65% */ uint256 forDevelopment = msg.value.mul(fee.development).div(100); /* 18% */ uint256 forCharity = msg.value.mul(fee.charity).div(100); /* 1% */ uint256 tokens = forTokensPurchase.mul(10 ** uint(decimals)).div(tokenPrice); /* The number of DSG tokens is counted (1ETH = 1000 DSG) */ _setReferrer(referrerAddress, msg.sender); /* Assigning of referrers */ _mint(msg.sender, tokens); /* We create new DSG tokens and add to balance */ _setProjectDividends(forDevelopment, forCharity); /* ETH is accrued to the project balances (18%, 1%) */ _distribution(msg.sender, msg.value.mul(fee.r1).div(100), 0); /* Dividends are accrued to the first refferer - 6% */ _distribution(msg.sender, msg.value.mul(fee.r2).div(100), 1); /* Dividends are accrued to the second refferer - 4% */ _distribution(msg.sender, msg.value.mul(fee.r3).div(100), 2); /* Dividends are accrued to the third refferer - 3% */ _distribution(msg.sender, msg.value.mul(fee.r4).div(100), 3); /* Dividends are accrued to the fourth refferer - 2% */ _distribution(msg.sender, msg.value.mul(fee.r5).div(100), 4); /* Dividends are accrued to the fifth referrer - 1% */ emit Buy(msg.sender, msg.value, tokens, totalSupply, now); } /**reinvest() - dividends reinvestment function. * It is active only during the time interval specified in sellTime() * Dividends upon the Pool Dividends and Gaming Dividends programs are being paid - payDividends(msg.sender) * Checking whether the investor has a given amount of ETH in the contract - checkETH(amountEthereum) * address amountEthereum - The amount of ETH sent for reinvestment (dividends) */ function reinvest(uint256 amountEthereum) payDividends(msg.sender) checkETH(amountEthereum) sellTime public { uint256 tokens = amountEthereum.mul(10 ** uint(decimals)).div(tokenPrice); /* The amount of DSG tokens is counted (1ETH = 1000 DSG) */ _mint(msg.sender, tokens); /* We create DSG tokens and add to the balance */ account[msg.sender].ethereumBalance = account[msg.sender].ethereumBalance.sub(amountEthereum);/* The amount of ETH from the investor is decreased */ emit Reinvest(msg.sender, amountEthereum, tokens, totalSupply, now); } /**reinvest() - dividends reinvestment function. * Checking whether there are enough DSG tokens on balance - checkDSG(amountTokens) * Dividends upon the Pool Dividends and Gaming Dividends program are being paid - payDividends(msg.sender) * address amountEthereum - The amount of ETH sent for reinvestment (dividends) * require - Checking whether the investor has a given amount of ETH in the contract */ function sell(uint256 amountTokens) payDividends(msg.sender) checkDSG(amountTokens) public { uint256 ethereum = amountTokens.mul(tokenPrice).div(10 ** uint(decimals));/* Counting the number of ETH (1000 DSG = 1ETH) */ account[msg.sender].ethereumBalance = account[msg.sender].ethereumBalance.add(ethereum); _burn(msg.sender, amountTokens);/* Tokens are burnt */ emit Sell(msg.sender, amountTokens, ethereum, totalSupply, now); } /**withdraw() - the function of ETH withdrawal from the contract * Dividends upon the Pool Dividends and Gaming Dividends programs are being paid - payDividends(msg.sender) * Checking whether the investor has a given amount of ETH in the contract - checkETH(amountEthereum) * address amountEthereum - The amount of ETH requested for withdrawal */ function withdraw(uint256 amountEthereum) payDividends(msg.sender) checkETH(amountEthereum) public { msg.sender.transfer(amountEthereum); /* ETH is sent */ account[msg.sender].ethereumBalance = account[msg.sender].ethereumBalance.sub(amountEthereum);/* Decreasing the amount of ETH from the investor */ emit Withdraw(msg.sender, amountEthereum, now); } /**gamingDividendsReception() - function that receives and distributes dividends upon the "Gaming Dividends" program * require - if the address of the game is not registered in mapping games, the transaction will be declined */ function gamingDividendsReception() payable external{ require(getGame(msg.sender) == true, "Game not active"); uint256 eth = msg.value; uint256 forDevelopment = eth.mul(19).div(100); /* To support the project - 19% */ uint256 forInvesotrs = eth.mul(80).div(100); /* To all DSG holders - 80% */ uint256 forCharity = eth.div(100); /* For charity - 1% */ _setProjectDividends(forDevelopment, forCharity); /* Dividends for supporting the projects are distributed */ _setGamingDividends(forInvesotrs); /* Gaming dividends are distributed */ } /**_distribution() - function of dividends distribution upon the "Referrer Dividends" program * With a mimimum purchase ranging from 100 to 9999 DSG * Only the first level of the referral program is open and a floating percentage is offered, which depends on the amount of investment. * Formula - ETH * DSG / 10000 = % * ETH - the amount of Ethereum, which the investor should have received if the balance had been >= 10000 DSG (6%) * DSG - the amount of tokens on the referrer's balance, which accrues interest * 10000 - minimum amount of tokens when all the percentage levels are open * - The first level is a floating percentage depending on the amount of holding * - The second level - for all upon the "Pool dividends" program * - The third level - for all upon the "Pool dividends" program * - The fourth level - for all upon the "Pool dividends" program * - The fifth level - for all upon the "Pool dividends" program * With 10000 DSG on balance and more the entire referral system will be activated and the investor will receive all interest from all levels * The function automatically checks the investor's DSG balance at the time of dividends distribution, this that referral * program can be fully activated or deactivated automatically depending on the DSG balance at the time of distribution * address senderAddress - the address of referral that sends dividends to his referrer * uint256 eth - the amount of ETH which referrer should send to the referrer * uint8 k - the number of referrer */ function _distribution(address senderAddress, uint256 eth, uint8 k) private{ address referrer = account[senderAddress].referrer[k]; uint256 referrerBalance = account[referrer].tokenBalance; uint256 senderTokenBalance = account[senderAddress].tokenBalance; uint256 minReferrerBalance = 10000e18; if(referrerBalance >= minReferrerBalance){ _setReferrerDividends(referrer, eth);/* The interest is sent to the referrer */ } else if(k == 0 && referrerBalance < minReferrerBalance && referrer != address(0)){ uint256 forReferrer = eth.mul(referrerBalance).div(minReferrerBalance);/* The floating percentage is counted */ uint256 forPool = eth.sub(forReferrer);/* Amount for Pool Dividends (all DSG holders) */ _setReferrerDividends(referrer, forReferrer);/* The referrer is sent his interest */ _setPoolDividends(forPool, senderTokenBalance);/* Dividends are paid to all the DSG token holders */ } else{ _setPoolDividends(eth, senderTokenBalance);/* If the refferal is 0x - Dividends are paid to all the DSG token holders */ } } /* _setReferrerDividends() - the function which sends referrer his dividends */ function _setReferrerDividends(address referrer, uint256 eth) private { account[referrer].ethereumBalance = account[referrer].ethereumBalance.add(eth); account[referrer].totalDividendsReferrer = account[referrer].totalDividendsReferrer.add(eth); totalDividends.referrer = totalDividends.referrer.add(eth); } /**_setReferrer() - the function which assigns referrers to the buyer * address referrerAddress - the address of referrer who invited the investor to the project * address senderAddress - the buyer's address * The function assigns referrers only once when buying tokens * Referrers can not be changed * require(referrerAddress != senderAddress) - Checks whether the buyer is not a referrer himself * require(account[referrerAddress].active == true || referrerAddress == address(0)) * Checks whether the referrer exists in the project */ function _setReferrer(address referrerAddress, address senderAddress) private { if(account[senderAddress].active == false){ require(referrerAddress != senderAddress, "You can't be referrer for yourself"); require(account[referrerAddress].active == true || referrerAddress == address(0), "Your referrer was not found in the contract"); account[senderAddress].referrer = [ referrerAddress, /* The referrer who invited the investor */ account[referrerAddress].referrer[0], account[referrerAddress].referrer[1], account[referrerAddress].referrer[2], account[referrerAddress].referrer[3] ]; account[senderAddress].active = true; /* The account is activated */ emit Referrer( senderAddress, account[senderAddress].referrer[0], account[senderAddress].referrer[1], account[senderAddress].referrer[2], account[senderAddress].referrer[3], account[senderAddress].referrer[4], now ); } } /**setRef_setProjectDividendserrer() - the function of dividends payment to support the project * uint256 forDevelopment - To support the project - 18% * uint256 forCharity - For charity - 1% */ function _setProjectDividends(uint256 forDevelopment, uint256 forCharity) private{ developmentBalance = developmentBalance.add(forDevelopment); charityBalance = charityBalance.add(forCharity); } /**_setPoolDividends() - the function of uniform distribution of dividends to all DSG holders upon the "Pool Dividends" program * During the distribution of dividends, the amount of tokens that are on the buyer's balance is not taken into account, * since he does not participate in the distribution of dividends * uint256 amountEthereum - the amount of ETH which should be distributed to all DSG holders * uint256 userTokens - the amount of DSG that is on the buyer's balance */ function _setPoolDividends(uint256 amountEthereum, uint256 userTokens) private{ if(amountEthereum > 0){ divPerTokenPool = divPerTokenPool.add(amountEthereum.mul(10 ** uint(decimals)).div(totalSupply.sub(userTokens))); totalDividends.pool = totalDividends.pool.add(amountEthereum); } } /**_setGamingDividends() - the function of uniform distribution of dividends to all DSG holders upon the "Gaming Dividends" program * uint256 amountEthereum - the amount of ETH which should be distributed to all DSG holders */ function _setGamingDividends(uint256 amountEthereum) private{ if(amountEthereum > 0){ divPerTokenGaming = divPerTokenGaming.add(amountEthereum.mul(10 ** uint(decimals)).div(totalSupply)); totalDividends.gaming = totalDividends.gaming.add(amountEthereum); } } /**setGame() - the function of adding a new address of the game contract, from which you can receive dividends * address gameAddress - the address of the game contract * bool active - if TRUE, the dividends can be received */ function setGame(address gameAddress, bool active) public onlyOwners returns(bool){ games[gameAddress] = active; return true; } /**getPoolDividends() - the function of calculating dividends for the investor upon the "Pool Dividends" program * returns(uint256) - the amount of ETH that was counted to the investor is returned * and which has not been paid to him yet */ function getPoolDividends() public view returns(uint256) { uint newDividendsPerToken = divPerTokenPool.sub(account[msg.sender].lastDivPerTokenPool); return account[msg.sender].tokenBalance.mul(newDividendsPerToken).div(10 ** uint(decimals)); } /**getGameDividends() - the function of calculating dividends for the investor upon the "Gaming Dividends" program * returns(uint256) - the amount of ETH that was counted to the investor is returned, * and which has not been paid to him yet */ function getGamingDividends() public view returns(uint256) { uint newDividendsPerToken = divPerTokenGaming.sub(account[msg.sender].lastDivPerTokenGaming); return account[msg.sender].tokenBalance.mul(newDividendsPerToken).div(10 ** uint(decimals)); } /* getAccountData() - the function that returns all the data of the investor */ function getAccountData() public view returns( uint256 tokenBalance, uint256 ethereumBalance, uint256 lastDivPerTokenPool, uint256 lastDivPerTokenGaming, uint256 totalDividendsPool, uint256 totalDividendsReferrer, uint256 totalDividendsGaming, address[5] memory referrer, bool active) { return( account[msg.sender].tokenBalance, account[msg.sender].ethereumBalance, account[msg.sender].lastDivPerTokenPool, account[msg.sender].lastDivPerTokenGaming, account[msg.sender].totalDividendsPool, account[msg.sender].totalDividendsReferrer, account[msg.sender].totalDividendsGaming, account[msg.sender].referrer, account[msg.sender].active ); } /* getContractBalance() - the function that returns a contract balance */ function getContractBalance() view public returns (uint256) { return address(this).balance; } /* getGame() - the function that checks whether the game is active or not. If TRUE - the game is active. If FALSE - the game is not active */ function getGame(address gameAddress) view public returns (bool) { return games[gameAddress]; } /* transferOwnership() - the function that assigns the future founder of the contract */ function transferOwnership(address candidate, uint8 k) check0x(candidate) onlyOwners public { candidates[k] = candidate; } /* confirmOwner() - the function that confirms the new founder of the contract and assigns him */ function confirmOwner(uint8 k) public { require(msg.sender == candidates[k], "You are not candidate"); owners[k] = candidates[k]; delete candidates[k]; } /* charitytWithdraw() - the function of withdrawal for charity */ function charitytWithdraw(address recipient) onlyOwners check0x(recipient) public { recipient.transfer(charityBalance); delete charityBalance; } /* developmentWithdraw() - the function of withdrawal for the project support */ function developmentWithdraw(address recipient) onlyOwners check0x(recipient) public { recipient.transfer(developmentBalance); delete developmentBalance; } /* balanceOf() - the function that returns the amount of DSG tokens on balance (ERC20 standart) */ function balanceOf(address owner) public view returns(uint256) { return account[owner].tokenBalance; } /* allowance() - the function that checks how much spender can spend tokens of the owner user (ERC20 standart) */ function allowance(address owner, address spender) public view returns(uint256) { return allowed[owner][spender]; } /* transferTo() - the function sends DSG tokens to another user (ERC20 standart) */ function transfer(address to, uint256 value) public returns(bool) { _transfer(msg.sender, to, value); return true; } /* transferTo() - the function that allows the user to spend n-number of tokens for spender (ERC20 standart) */ function approve(address spender, uint256 value) check0x(spender) checkDSG(value) public returns(bool) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /* transferFrom() - the function sends tokens from one address to another, only to the address that gave the permission (ERC20 standart) */ function transferFrom(address from, address to, uint256 value) public returns(bool) { allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, allowed[from][msg.sender]); return true; } /* _transfer() - the function of tokens sending (ERC20 standart) */ function _transfer(address from, address to, uint256 value) payDividends(from) payDividends(to) checkDSG(value) check0x(to) private { account[from].tokenBalance = account[from].tokenBalance.sub(value); account[to].tokenBalance = account[to].tokenBalance.add(value); if(account[to].active == false) account[to].active = true; emit Transfer(from, to, value); } /* transferFrom() - the function of tokens creating (ERC20 standart) */ function _mint(address customerAddress, uint256 value) check0x(customerAddress) private { totalSupply = totalSupply.add(value); account[customerAddress].tokenBalance = account[customerAddress].tokenBalance.add(value); emit Transfer(address(0), customerAddress, value); } /* transferFrom() - the function of tokens _burning (ERC20 standart) */ function _burn(address customerAddress, uint256 value) check0x(customerAddress) private { totalSupply = totalSupply.sub(value); account[customerAddress].tokenBalance = account[customerAddress].tokenBalance.sub(value); emit Transfer(customerAddress, address(0), value); } event Buy( address indexed customerAddress, uint256 inputEthereum, uint256 outputToken, uint256 totalSupply, uint256 timestamp ); event Sell( address indexed customerAddress, uint256 amountTokens, uint256 outputEthereum, uint256 totalSupply, uint256 timestamp ); event Reinvest( address indexed customerAddress, uint256 amountEthereum, uint256 outputToken, uint256 totalSupply, uint256 timestamp ); event Withdraw( address indexed customerAddress, uint256 indexed amountEthereum, uint256 timestamp ); event Referrer( address indexed customerAddress, address indexed referrer1, address referrer2, address referrer3, address referrer4, address referrer5, uint256 timestamp ); event Transfer( address indexed from, address indexed to, uint tokens ); event Approval( address indexed tokenOwner, address indexed spender, uint tokens ); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "Mul error"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "Div error"); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "Sub error"); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "Add error"); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Mod error"); return a % b; } }
getGame() - the function that checks whether the game is active or not. If TRUE - the game is active. If FALSE - the game is not active */
function getGame(address gameAddress) view public returns (bool) { return games[gameAddress]; }
5,399,467
[ 1, 588, 12496, 1435, 300, 326, 445, 716, 4271, 2856, 326, 7920, 353, 2695, 578, 486, 18, 971, 5383, 300, 326, 7920, 353, 2695, 18, 971, 4934, 300, 326, 7920, 353, 486, 2695, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7162, 339, 12, 2867, 7920, 1887, 13, 1476, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 327, 28422, 63, 13957, 1887, 15533, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library LibShare { // Defines the share of royalties for the address struct Share { address payable account; uint96 value; } }
Defines the share of royalties for the address
library LibShare { pragma solidity ^0.8.0; struct Share { address payable account; uint96 value; } }
929,880
[ 1, 15109, 326, 7433, 434, 721, 93, 2390, 606, 364, 326, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 10560, 9535, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 1958, 25805, 288, 203, 3639, 1758, 8843, 429, 2236, 31, 203, 3639, 2254, 10525, 460, 31, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Fund.sol"; import "../libraries/UniswapStyleLib.sol"; abstract contract BaseRouter { modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "Trade has expired"); _; } // **** SWAP **** /// @dev requires the initial amount to have already been sent to the first pair /// and for pairs to be vetted (which getAmountsIn / getAmountsOut do) function _swap( uint256[] memory amounts, address[] memory pairs, address[] memory tokens, address _to ) internal { for (uint256 i; i < pairs.length; i++) { (address input, address output) = (tokens[i], tokens[i + 1]); (address token0, ) = UniswapStyleLib.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < pairs.length - 1 ? pairs[i + 1] : _to; IUniswapV2Pair pair = IUniswapV2Pair(pairs[i]); pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/IWETH.sol"; import "./RoleAware.sol"; /// @title Manage funding contract Fund is RoleAware { using SafeERC20 for IERC20; /// wrapped ether address public immutable WETH; constructor(address _WETH, address _roles) RoleAware(_roles) { WETH = _WETH; } /// Deposit an active token function deposit(address depositToken, uint256 depositAmount) external { IERC20(depositToken).safeTransferFrom( msg.sender, address(this), depositAmount ); } /// Deposit token on behalf of `sender` function depositFor( address sender, address depositToken, uint256 depositAmount ) external { require(isFundTransferer(msg.sender), "Unauthorized deposit"); IERC20(depositToken).safeTransferFrom( sender, address(this), depositAmount ); } /// Deposit to wrapped ether function depositToWETH() external payable { IWETH(WETH).deposit{value: msg.value}(); } // withdrawers role function withdraw( address withdrawalToken, address recipient, uint256 withdrawalAmount ) external { require(isFundTransferer(msg.sender), "Unauthorized withdraw"); IERC20(withdrawalToken).safeTransfer(recipient, withdrawalAmount); } // withdrawers role function withdrawETH(address recipient, uint256 withdrawalAmount) external { require(isFundTransferer(msg.sender), "Unauthorized withdraw"); IWETH(WETH).withdraw(withdrawalAmount); Address.sendValue(payable(recipient), withdrawalAmount); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Roles.sol"; /// @title Role management behavior /// Main characters are for service discovery /// Whereas roles are for access control contract RoleAware { Roles public immutable roles; mapping(uint256 => address) public mainCharacterCache; mapping(address => mapping(uint256 => bool)) public roleCache; constructor(address _roles) { require(_roles != address(0), "Please provide valid roles address"); roles = Roles(_roles); } modifier noIntermediary() { require( msg.sender == tx.origin, "Currently no intermediaries allowed for this function call" ); _; } // @dev Throws if called by any account other than the owner or executor modifier onlyOwnerExec() { require( owner() == msg.sender || executor() == msg.sender, "Roles: caller is not the owner" ); _; } modifier onlyOwnerExecDisabler() { require( owner() == msg.sender || executor() == msg.sender || disabler() == msg.sender, "Caller is not the owner, executor or authorized disabler" ); _; } modifier onlyOwnerExecActivator() { require( owner() == msg.sender || executor() == msg.sender || isTokenActivator(msg.sender), "Caller is not the owner, executor or authorized activator" ); _; } function updateRoleCache(uint256 role, address contr) public virtual { roleCache[contr][role] = roles.getRole(role, contr); } function updateMainCharacterCache(uint256 role) public virtual { mainCharacterCache[role] = roles.mainCharacters(role); } function owner() internal view returns (address) { return roles.owner(); } function executor() internal returns (address) { return roles.executor(); } function disabler() internal view returns (address) { return mainCharacterCache[DISABLER]; } function fund() internal view returns (address) { return mainCharacterCache[FUND]; } function lending() internal view returns (address) { return mainCharacterCache[LENDING]; } function marginRouter() internal view returns (address) { return mainCharacterCache[MARGIN_ROUTER]; } function crossMarginTrading() internal view returns (address) { return mainCharacterCache[CROSS_MARGIN_TRADING]; } function feeController() internal view returns (address) { return mainCharacterCache[FEE_CONTROLLER]; } function price() internal view returns (address) { return mainCharacterCache[PRICE_CONTROLLER]; } function admin() internal view returns (address) { return mainCharacterCache[ADMIN]; } function incentiveDistributor() internal view returns (address) { return mainCharacterCache[INCENTIVE_DISTRIBUTION]; } function tokenAdmin() internal view returns (address) { return mainCharacterCache[TOKEN_ADMIN]; } function isBorrower(address contr) internal view returns (bool) { return roleCache[contr][BORROWER]; } function isFundTransferer(address contr) internal view returns (bool) { return roleCache[contr][FUND_TRANSFERER]; } function isMarginTrader(address contr) internal view returns (bool) { return roleCache[contr][MARGIN_TRADER]; } function isFeeSource(address contr) internal view returns (bool) { return roleCache[contr][FEE_SOURCE]; } function isMarginCaller(address contr) internal view returns (bool) { return roleCache[contr][MARGIN_CALLER]; } function isLiquidator(address contr) internal view returns (bool) { return roleCache[contr][LIQUIDATOR]; } function isAuthorizedFundTrader(address contr) internal view returns (bool) { return roleCache[contr][AUTHORIZED_FUND_TRADER]; } function isIncentiveReporter(address contr) internal view returns (bool) { return roleCache[contr][INCENTIVE_REPORTER]; } function isTokenActivator(address contr) internal view returns (bool) { return roleCache[contr][TOKEN_ACTIVATOR]; } function isStakePenalizer(address contr) internal view returns (bool) { return roleCache[contr][STAKE_PENALIZER]; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IDependencyController.sol"; // we chose not to go with an enum // to make this list easy to extend uint256 constant FUND_TRANSFERER = 1; uint256 constant MARGIN_CALLER = 2; uint256 constant BORROWER = 3; uint256 constant MARGIN_TRADER = 4; uint256 constant FEE_SOURCE = 5; uint256 constant LIQUIDATOR = 6; uint256 constant AUTHORIZED_FUND_TRADER = 7; uint256 constant INCENTIVE_REPORTER = 8; uint256 constant TOKEN_ACTIVATOR = 9; uint256 constant STAKE_PENALIZER = 10; uint256 constant FUND = 101; uint256 constant LENDING = 102; uint256 constant MARGIN_ROUTER = 103; uint256 constant CROSS_MARGIN_TRADING = 104; uint256 constant FEE_CONTROLLER = 105; uint256 constant PRICE_CONTROLLER = 106; uint256 constant ADMIN = 107; uint256 constant INCENTIVE_DISTRIBUTION = 108; uint256 constant TOKEN_ADMIN = 109; uint256 constant DISABLER = 1001; uint256 constant DEPENDENCY_CONTROLLER = 1002; /// @title Manage permissions of contracts and ownership of everything /// owned by a multisig wallet (0xEED9D1c6B4cdEcB3af070D85bfd394E7aF179CBd) during /// beta and will then be transfered to governance /// https://github.com/marginswap/governance contract Roles is Ownable { mapping(address => mapping(uint256 => bool)) public roles; mapping(uint256 => address) public mainCharacters; constructor() Ownable() { // token activation from the get-go roles[msg.sender][TOKEN_ACTIVATOR] = true; } /// @dev Throws if called by any account other than the owner. modifier onlyOwnerExecDepController() { require( owner() == msg.sender || executor() == msg.sender || mainCharacters[DEPENDENCY_CONTROLLER] == msg.sender, "Roles: caller is not the owner" ); _; } function giveRole(uint256 role, address actor) external onlyOwnerExecDepController { roles[actor][role] = true; } function removeRole(uint256 role, address actor) external onlyOwnerExecDepController { roles[actor][role] = false; } function setMainCharacter(uint256 role, address actor) external onlyOwnerExecDepController { mainCharacters[role] = actor; } function getRole(uint256 role, address contr) external view returns (bool) { return roles[contr][role]; } /// @dev current executor function executor() public returns (address exec) { address depController = mainCharacters[DEPENDENCY_CONTROLLER]; if (depController != address(0)) { exec = IDependencyController(depController).currentExecutor(); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "../libraries/UniswapStyleLib.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/IWETH.sol"; import "./BaseRouter.sol"; /// @title Router for spot trading on uniswap and sushiswap jointly /// the paramater amms represents the choice of amm pair along the route /// it is a bytes32 value where amms[i] == 0 for uniswap and amms[i] == 1 for sushi contract SpotRouter is BaseRouter { using SafeERC20 for IERC20; address public immutable WETH; constructor(address _WETH) { WETH = _WETH; } function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, bytes32 amms, address[] calldata tokens, address to, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsOut( amountIn, amms, tokens ); require( amounts[amounts.length - 1] >= amountOutMin, "SpotRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); IERC20(tokens[0]).safeTransferFrom(msg.sender, pairs[0], amounts[0]); _swap(amounts, pairs, tokens, to); } function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, bytes32 amms, address[] calldata tokens, address to, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsIn( amountOut, amms, tokens ); require( amounts[0] <= amountInMax, "SpotRouter: EXCESSIVE_INPUT_AMOUNT" ); IERC20(tokens[0]).safeTransferFrom(msg.sender, pairs[0], amounts[0]); _swap(amounts, pairs, tokens, to); } function swapExactETHForTokens( uint256 amountOutMin, bytes32 amms, address[] calldata tokens, address to, uint256 deadline ) external payable ensure(deadline) returns (uint256[] memory amounts) { require(tokens[0] == WETH, "SpotRouter: INVALID_PATH"); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsOut( msg.value, amms, tokens ); require( amounts[amounts.length - 1] >= amountOutMin, "SpotRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(pairs[0], msg.value)); _swap(amounts, pairs, tokens, to); } function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, bytes32 amms, address[] calldata tokens, address to, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { require(tokens[tokens.length - 1] == WETH, "SpotRouter: INVALID_PATH"); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsIn( amountOut, amms, tokens ); require( amounts[0] <= amountInMax, "SpotRouter: EXCESSIVE_INPUT_AMOUNT" ); IERC20(tokens[0]).safeTransferFrom(msg.sender, pairs[0], amounts[0]); _swap(amounts, pairs, tokens, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); Address.sendValue(payable(to), amounts[amounts.length - 1]); } function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, bytes32 amms, address[] calldata tokens, address to, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { require(tokens[tokens.length - 1] == WETH, "SpotRouter: INVALID_PATH"); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsOut( amountIn, amms, tokens ); require( amounts[amounts.length - 1] >= amountOutMin, "SpotRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); _swap(amounts, pairs, tokens, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); Address.sendValue(payable(to), amounts[amounts.length - 1]); } function swapETHForExactTokens( uint256 amountOut, bytes32 amms, address[] calldata tokens, address to, uint256 deadline ) external payable ensure(deadline) returns (uint256[] memory amounts) { require(tokens[0] == WETH, "SpotRouter: INVALID_PATH"); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsIn( amountOut, amms, tokens ); require(amounts[0] <= msg.value, "SpotRouter: EXCESSIVE_INPUT_AMOUNT"); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(pairs[0], amounts[0])); _swap(amounts, pairs, tokens, to); // refund dust eth, if any if (msg.value > amounts[0]) Address.sendValue(payable(msg.sender), msg.value - amounts[0]); } function getAmountsOut( uint256 inAmount, bytes32 amms, address[] calldata tokens ) external view returns (uint256[] memory amounts) { (amounts, ) = UniswapStyleLib.getAmountsOut(inAmount, amms, tokens); } function getAmountsIn( uint256 outAmount, bytes32 amms, address[] calldata tokens ) external view returns (uint256[] memory amounts) { (amounts, ) = UniswapStyleLib.getAmountsIn(outAmount, amms, tokens); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; interface IDependencyController { function currentExecutor() external returns (address); } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } pragma solidity >=0.5.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; library UniswapStyleLib { address constant UNISWAP_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address constant SUSHI_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "Identical address!"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "Zero address!"); } // fetches and sorts the reserves for a pair function getReserves( address pair, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pair).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = reserveIn * 1_000 + amountInWithFee; amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn * amountOut * 1_000; uint256 denominator = (reserveOut - amountOut) - 997; amountIn = (numerator / denominator) + 1; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( uint256 amountIn, bytes32 amms, address[] memory tokens ) internal view returns (uint256[] memory amounts, address[] memory pairs) { require(tokens.length >= 2, "token path too short"); amounts = new uint256[](tokens.length); amounts[0] = amountIn; pairs = new address[](tokens.length - 1); for (uint256 i; i < tokens.length - 1; i++) { address inToken = tokens[i]; address outToken = tokens[i + 1]; address pair = amms[i] == 0 ? pairForUni(inToken, outToken) : pairForSushi(inToken, outToken); pairs[i] = pair; (uint256 reserveIn, uint256 reserveOut) = getReserves(pair, inToken, outToken); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( uint256 amountOut, bytes32 amms, address[] memory tokens ) internal view returns (uint256[] memory amounts, address[] memory pairs) { require(tokens.length >= 2, "token path too short"); amounts = new uint256[](tokens.length); amounts[amounts.length - 1] = amountOut; pairs = new address[](tokens.length - 1); for (uint256 i = tokens.length - 1; i > 0; i--) { address inToken = tokens[i - 1]; address outToken = tokens[i]; address pair = amms[i - 1] == 0 ? pairForUni(inToken, outToken) : pairForSushi(inToken, outToken); pairs[i - 1] = pair; (uint256 reserveIn, uint256 reserveOut) = getReserves(pair, inToken, outToken); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } // calculates the CREATE2 address for a pair without making any external calls function pairForUni(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", UNISWAP_FACTORY, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ) ); } function pairForSushi(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", SUSHI_FACTORY, keccak256(abi.encodePacked(token0, token1)), hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash ) ) ) ) ); } }
Deposit token on behalf of `sender`
function depositFor( address sender, address depositToken, uint256 depositAmount ) external { require(isFundTransferer(msg.sender), "Unauthorized deposit"); IERC20(depositToken).safeTransferFrom( sender, address(this), depositAmount ); }
315,391
[ 1, 758, 1724, 1147, 603, 12433, 6186, 434, 1375, 15330, 68, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 1290, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 443, 1724, 1345, 16, 203, 3639, 2254, 5034, 443, 1724, 6275, 203, 565, 262, 3903, 288, 203, 3639, 2583, 12, 291, 42, 1074, 5912, 264, 12, 3576, 18, 15330, 3631, 315, 13981, 443, 1724, 8863, 203, 3639, 467, 654, 39, 3462, 12, 323, 1724, 1345, 2934, 4626, 5912, 1265, 12, 203, 5411, 5793, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 443, 1724, 6275, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-08-10 */ // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.4; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } library IterableMapping { // Iterable mapping from address to uint; struct Map { address[] keys; mapping(address => uint) values; mapping(address => uint) indexOf; mapping(address => bool) inserted; } function get(Map storage map, address key) public view returns (uint) { return map.values[key]; } function getIndexOfKey(Map storage map, address key) public view returns (int) { if(!map.inserted[key]) { return -1; } return int(map.indexOf[key]); } function getKeyAtIndex(Map storage map, uint index) public view returns (address) { return map.keys[index]; } function size(Map storage map) public view returns (uint) { return map.keys.length; } function set(Map storage map, address key, uint val) public { if (map.inserted[key]) { map.values[key] = val; } else { map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function remove(Map storage map, address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } } /// @title Dividend-Paying Token Optional Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev OPTIONAL functions for a dividend-paying token contract. interface DividendPayingTokenOptionalInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) external view returns(uint256); } /// @title Dividend-Paying Token Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev An interface for a dividend-paying token contract. interface DividendPayingTokenInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) external view returns(uint256); /// @notice Distributes ether to token holders as dividends. /// @dev SHOULD distribute the paid ether to token holders as dividends. /// SHOULD NOT directly transfer ether to token holders in this function. /// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0. function distributeDividends() external payable; /// @notice Withdraws the ether distributed to the sender. /// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer. /// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0. function withdrawDividend() external; /// @dev This event MUST emit when ether is distributed to token holders. /// @param from The address which sends ether to this contract. /// @param weiAmount The amount of distributed ether in wei. event DividendsDistributed( address indexed from, uint256 weiAmount ); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws ether from this contract. /// @param weiAmount The amount of withdrawn ether in wei. event DividendWithdrawn( address indexed to, uint256 weiAmount ); } /* MIT License Copyright (c) 2018 requestnetwork Copyright (c) 2018 Fragments, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } // File: contracts/SafeMathUint.sol /** * @title SafeMathUint * @dev Math operations with safety checks that revert on error */ library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } // File: contracts/SafeMath.sol library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: contracts/Ownable.sol contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0x0fe60E55a8C0700b47d4a2663079c445Fc4A5893), _msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/DividendPayingToken.sol /// @title Dividend-Paying Token /// @author Roger Wu (https://github.com/roger-wu) /// @dev A mintable ERC20 token that allows anyone to pay and distribute ether /// to token holders as dividends and allows token holders to withdraw their dividends. /// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code contract DividendPayingToken is ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant internal magnitude = 2**128; uint256 internal magnifiedDividendPerShare; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; // Need to make gas fee customizable to future-proof against Ethereum network upgrades. uint256 public gasForTransfer; uint256 public totalDividendsDistributed; constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) { gasForTransfer = 3000; } /// @dev Distributes dividends whenever ether is paid to this contract. receive() external payable { distributeDividends(); } /// @notice Distributes ether to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0. /// About undistributed ether: /// In each distribution, there is a small amount of ether not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether, so we don't do that. function distributeDividends() public override payable { require(totalSupply() > 0); if (msg.value > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add( (msg.value).mul(magnitude) / totalSupply() ); emit DividendsDistributed(msg.sender, msg.value); totalDividendsDistributed = totalDividendsDistributed.add(msg.value); } } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); (bool success,) = user.call{value: _withdrawableDividend, gas: gasForTransfer}(""); if(!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0; } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) public view override returns(uint256) { return withdrawableDividendOf(_owner); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) public view override returns(uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) public view override returns(uint256) { return withdrawnDividends[_owner]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) public view override returns(uint256) { return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe() .add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude; } /// @dev Internal function that transfer tokens from one address to another. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param value The amount to be transferred. function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); } /// @dev Internal function that mints tokens to an account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account that will receive the created tokens. /// @param value The amount that will be created. function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if(newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if(newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } } // File: contracts/EPRODividendTracker.sol contract EPRODividendTracker is DividendPayingToken, Ownable { using SafeMath for uint256; using SafeMathInt for int256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; uint256 public lastProcessedIndex; mapping (address => bool) public excludedFromDividends; mapping (address => uint256) public lastClaimTimes; uint256 public claimWait; uint256 public constant MIN_TOKEN_BALANCE_FOR_DIVIDENDS = 1000000 * (10**18); // Must hold 1 million tokens to receive eth rewards. event ExcludedFromDividends(address indexed account); event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue); event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Claim(address indexed account, uint256 amount, bool indexed automatic); constructor() DividendPayingToken("EPRO_Dividend_Tracker", "EPRO_Dividend_Tracker") { claimWait = 3600; } function _transfer(address, address, uint256) internal pure override { require(false, "EPRO_Dividend_Tracker: No transfers allowed"); } function withdrawDividend() public pure override { require(false, "EPRO_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main EPRO contract."); } function excludeFromDividends(address account) external onlyOwner { require(!excludedFromDividends[account]); excludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludedFromDividends(account); } function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner { require(newGasForTransfer != gasForTransfer, "EPRO_Dividend_Tracker: Cannot update gasForTransfer to same value"); emit GasForTransferUpdated(newGasForTransfer, gasForTransfer); gasForTransfer = newGasForTransfer; } function updateClaimWait(uint256 newClaimWait) external onlyOwner { require(newClaimWait >= 3600 && newClaimWait <= 86400, "EPRO_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours"); require(newClaimWait != claimWait, "EPRO_Dividend_Tracker: Cannot update claimWait to same value"); emit ClaimWaitUpdated(newClaimWait, claimWait); claimWait = newClaimWait; } function getLastProcessedIndex() external view returns(uint256) { return lastProcessedIndex; } function getNumberOfTokenHolders() external view returns(uint256) { return tokenHoldersMap.keys.length; } function getAccount(address _account) public view returns ( address account, int256 index, int256 iterationsUntilProcessed, uint256 withdrawableDividends, uint256 totalDividends, uint256 lastClaimTime, uint256 nextClaimTime, uint256 secondsUntilAutoClaimAvailable) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); iterationsUntilProcessed = -1; if (index >= 0) { if (uint256(index) > lastProcessedIndex) { iterationsUntilProcessed = index.sub(int256(lastProcessedIndex)); } else { uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0; iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray)); } } withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); lastClaimTime = lastClaimTimes[account]; nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0; secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0; } function getAccountAtIndex(uint256 index) public view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { if (index >= tokenHoldersMap.size()) { return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0); } address account = tokenHoldersMap.getKeyAtIndex(index); return getAccount(account); } function canAutoClaim(uint256 lastClaimTime) private view returns (bool) { if (lastClaimTime > block.timestamp) { return false; } return block.timestamp.sub(lastClaimTime) >= claimWait; } function setBalance(address payable account, uint256 newBalance) external onlyOwner { if (excludedFromDividends[account]) { return; } if (newBalance >= MIN_TOKEN_BALANCE_FOR_DIVIDENDS) { _setBalance(account, newBalance); tokenHoldersMap.set(account, newBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } processAccount(account, true); } function process(uint256 gas) public returns (uint256, uint256, uint256) { uint256 numberOfTokenHolders = tokenHoldersMap.keys.length; if (numberOfTokenHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while (gasUsed < gas && iterations < numberOfTokenHolders) { _lastProcessedIndex++; if (_lastProcessedIndex >= tokenHoldersMap.keys.length) { _lastProcessedIndex = 0; } address account = tokenHoldersMap.keys[_lastProcessedIndex]; if (canAutoClaim(lastClaimTimes[account])) { if (processAccount(payable(account), true)) { claims++; } } iterations++; uint256 newGasLeft = gasleft(); if (gasLeft > newGasLeft) { gasUsed = gasUsed.add(gasLeft.sub(newGasLeft)); } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, lastProcessedIndex); } function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(account); if (amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount, automatic); return true; } return false; } } contract Test is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public immutable uniswapV2Pair; bool private liquidating; EPRODividendTracker public dividendTracker; address public liquidityWallet; uint256 public constant MAX_SELL_TRANSACTION_AMOUNT = 10000000 * (10**18); uint256 public constant ETH_REWARDS_FEE = 5; uint256 public constant LIQUIDITY_FEE = 5; uint256 public constant TOTAL_FEES = ETH_REWARDS_FEE + LIQUIDITY_FEE; bool _swapEnabled = false; bool _maxBuyEnabled = true; address payable private _devWallet; // use by default 150,000 gas to process auto-claiming dividends uint256 public gasForProcessing = 150000; // liquidate tokens for ETH when the contract reaches 100k tokens by default uint256 public liquidateTokensAtAmount = 100000 * (10**18); // whether the token can already be traded bool public tradingEnabled; function activate() public onlyOwner { require(!tradingEnabled, "EPRO: Trading is already enabled"); _swapEnabled = true; tradingEnabled = true; } // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; // addresses that can make transfers before presale is over mapping (address => bool) public canTransferBeforeTradingIsEnabled; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdatedDividendTracker(address indexed newAddress, address indexed oldAddress); event UpdatedUniswapV2Router(address indexed newAddress, address indexed oldAddress); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event LiquidationThresholdUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Liquified( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapAndSendToDev( uint256 tokensSwapped, uint256 ethReceived ); event SentDividends( uint256 tokensSwapped, uint256 amount ); event ProcessedDividendTracker( uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor ); constructor(address payable devWallet) ERC20("Test", "TEST") { _devWallet = devWallet; dividendTracker = new EPRODividendTracker(); liquidityWallet = owner(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); // exclude from receiving dividends dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD)); // exclude from paying fees or having max transaction amount excludeFromFees(liquidityWallet); excludeFromFees(address(this)); // enable owner wallet to send tokens before presales are over. canTransferBeforeTradingIsEnabled[owner()] = true; /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(owner(), 1000000000 * (10**18)); } receive() external payable { } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "EPRO: The Uniswap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "EPRO: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function excludeFromFees(address account) public onlyOwner { require(!_isExcludedFromFees[account], "EPRO: Account is already excluded from fees"); _isExcludedFromFees[account] = true; } function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner { dividendTracker.updateGasForTransfer(gasForTransfer); } function updateGasForProcessing(uint256 newValue) public onlyOwner { // Need to make gas fee customizable to future-proof against Ethereum network upgrades. require(newValue != gasForProcessing, "EPRO: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; } function updateClaimWait(uint256 claimWait) external onlyOwner { dividendTracker.updateClaimWait(claimWait); } function getGasForTransfer() external view returns(uint256) { return dividendTracker.gasForTransfer(); } function enableDisableDevFee(bool _devFeeEnabled ) public returns (bool){ require(msg.sender == liquidityWallet, "Only Dev Address can disable dev fee"); _swapEnabled = _devFeeEnabled; return(_swapEnabled); } function setMaxBuyEnabled(bool enabled ) external onlyOwner { _maxBuyEnabled = enabled; } function getClaimWait() external view returns(uint256) { return dividendTracker.claimWait(); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns(uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function getAccountDividendsInfo(address account) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccountAtIndex(index); } function processDividendTracker(uint256 gas) external { (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas); emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin); } function claim() external { dividendTracker.processAccount(payable(msg.sender), false); } function getLastProcessedIndex() external view returns(uint256) { return dividendTracker.getLastProcessedIndex(); } function getNumberOfDividendTokenHolders() external view returns(uint256) { return dividendTracker.getNumberOfTokenHolders(); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); //to prevent bots both buys and sells will have a max on launch after only sells will if(from != owner() && to != owner() && _maxBuyEnabled) require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount."); bool tradingIsEnabled = tradingEnabled; // only whitelisted addresses can make transfers before trading is enabled. if (!tradingIsEnabled) { require(canTransferBeforeTradingIsEnabled[from], "EPRO: This account cannot send tokens until trading is enabled"); } if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) { //require(!antiBot.scanAddress(from, uniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop"); // require(!antiBot.scanAddress(to, uniswair, tx.origin), "Beep Beep Boop, You're a piece of poop"); } if (amount == 0) { super._transfer(from, to, 0); return; } if (!liquidating && tradingIsEnabled && automatedMarketMakerPairs[to] && // sells only by detecting transfer to automated market maker pair from != address(uniswapV2Router) && //router -> pair is removing liquidity which shouldn't have max !_isExcludedFromFees[to] //no max for those excluded from fees ) { require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT."); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= liquidateTokensAtAmount; if (tradingIsEnabled && canSwap && _swapEnabled && !liquidating && !automatedMarketMakerPairs[from] && from != liquidityWallet && to != liquidityWallet ) { liquidating = true; uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES); swapAndSendToDev(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); liquidating = false; } bool takeFee = tradingIsEnabled && !liquidating; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(TOTAL_FEES).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch { } if (!liquidating) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function swapAndSendToDev(uint256 tokens) private { uint256 tokenBalance = tokens; // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(tokenBalance); // <- breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); address payable _devAndMarketingAddress = payable(0x51a2CbFD0BEC0833c03a4b5d17731f415f725595); _devAndMarketingAddress.transfer(newBalance); emit SwapAndSendToDev(tokens, newBalance); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function swapAndSendDividends(uint256 tokens) private { swapTokensForEth(tokens); uint256 dividends = address(this).balance; (bool success,) = address(dividendTracker).call{value: dividends}(""); if (success) { emit SentDividends(tokens, dividends); } } }
use by default 150,000 gas to process auto-claiming dividends liquidate tokens for ETH when the contract reaches 100k tokens by default whether the token can already be traded
contract Test is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public immutable uniswapV2Pair; bool private liquidating; EPRODividendTracker public dividendTracker; address public liquidityWallet; uint256 public constant MAX_SELL_TRANSACTION_AMOUNT = 10000000 * (10**18); uint256 public constant ETH_REWARDS_FEE = 5; uint256 public constant LIQUIDITY_FEE = 5; uint256 public constant TOTAL_FEES = ETH_REWARDS_FEE + LIQUIDITY_FEE; bool _swapEnabled = false; bool _maxBuyEnabled = true; address payable private _devWallet; uint256 public gasForProcessing = 150000; uint256 public liquidateTokensAtAmount = 100000 * (10**18); bool public tradingEnabled; function activate() public onlyOwner { require(!tradingEnabled, "EPRO: Trading is already enabled"); _swapEnabled = true; tradingEnabled = true; } event UpdatedDividendTracker(address indexed newAddress, address indexed oldAddress); event UpdatedUniswapV2Router(address indexed newAddress, address indexed oldAddress); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event LiquidationThresholdUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Liquified( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapAndSendToDev( uint256 tokensSwapped, uint256 ethReceived ); event SentDividends( uint256 tokensSwapped, uint256 amount ); event ProcessedDividendTracker( uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor ); mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public canTransferBeforeTradingIsEnabled; mapping (address => bool) public automatedMarketMakerPairs; constructor(address payable devWallet) ERC20("Test", "TEST") { _devWallet = devWallet; dividendTracker = new EPRODividendTracker(); liquidityWallet = owner(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD)); excludeFromFees(liquidityWallet); excludeFromFees(address(this)); canTransferBeforeTradingIsEnabled[owner()] = true; _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(owner(), 1000000000 * (10**18)); } receive() external payable { } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "EPRO: The Uniswap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "EPRO: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "EPRO: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function excludeFromFees(address account) public onlyOwner { require(!_isExcludedFromFees[account], "EPRO: Account is already excluded from fees"); _isExcludedFromFees[account] = true; } function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner { dividendTracker.updateGasForTransfer(gasForTransfer); } function updateGasForProcessing(uint256 newValue) public onlyOwner { require(newValue != gasForProcessing, "EPRO: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; } function updateClaimWait(uint256 claimWait) external onlyOwner { dividendTracker.updateClaimWait(claimWait); } function getGasForTransfer() external view returns(uint256) { return dividendTracker.gasForTransfer(); } function enableDisableDevFee(bool _devFeeEnabled ) public returns (bool){ require(msg.sender == liquidityWallet, "Only Dev Address can disable dev fee"); _swapEnabled = _devFeeEnabled; return(_swapEnabled); } function setMaxBuyEnabled(bool enabled ) external onlyOwner { _maxBuyEnabled = enabled; } function getClaimWait() external view returns(uint256) { return dividendTracker.claimWait(); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns(uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function getAccountDividendsInfo(address account) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccountAtIndex(index); } function processDividendTracker(uint256 gas) external { (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas); emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin); } function claim() external { dividendTracker.processAccount(payable(msg.sender), false); } function getLastProcessedIndex() external view returns(uint256) { return dividendTracker.getLastProcessedIndex(); } function getNumberOfDividendTokenHolders() external view returns(uint256) { return dividendTracker.getNumberOfTokenHolders(); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(from != owner() && to != owner() && _maxBuyEnabled) require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount."); bool tradingIsEnabled = tradingEnabled; if (!tradingIsEnabled) { require(canTransferBeforeTradingIsEnabled[from], "EPRO: This account cannot send tokens until trading is enabled"); } if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) { } if (amount == 0) { super._transfer(from, to, 0); return; } if (!liquidating && tradingIsEnabled && ) { require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT."); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= liquidateTokensAtAmount; if (tradingIsEnabled && canSwap && _swapEnabled && !liquidating && !automatedMarketMakerPairs[from] && from != liquidityWallet && to != liquidityWallet ) { liquidating = true; uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES); swapAndSendToDev(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); liquidating = false; } bool takeFee = tradingIsEnabled && !liquidating; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(TOTAL_FEES).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(from != owner() && to != owner() && _maxBuyEnabled) require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount."); bool tradingIsEnabled = tradingEnabled; if (!tradingIsEnabled) { require(canTransferBeforeTradingIsEnabled[from], "EPRO: This account cannot send tokens until trading is enabled"); } if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) { } if (amount == 0) { super._transfer(from, to, 0); return; } if (!liquidating && tradingIsEnabled && ) { require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT."); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= liquidateTokensAtAmount; if (tradingIsEnabled && canSwap && _swapEnabled && !liquidating && !automatedMarketMakerPairs[from] && from != liquidityWallet && to != liquidityWallet ) { liquidating = true; uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES); swapAndSendToDev(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); liquidating = false; } bool takeFee = tradingIsEnabled && !liquidating; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(TOTAL_FEES).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(from != owner() && to != owner() && _maxBuyEnabled) require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount."); bool tradingIsEnabled = tradingEnabled; if (!tradingIsEnabled) { require(canTransferBeforeTradingIsEnabled[from], "EPRO: This account cannot send tokens until trading is enabled"); } if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) { } if (amount == 0) { super._transfer(from, to, 0); return; } if (!liquidating && tradingIsEnabled && ) { require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT."); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= liquidateTokensAtAmount; if (tradingIsEnabled && canSwap && _swapEnabled && !liquidating && !automatedMarketMakerPairs[from] && from != liquidityWallet && to != liquidityWallet ) { liquidating = true; uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES); swapAndSendToDev(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); liquidating = false; } bool takeFee = tradingIsEnabled && !liquidating; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(TOTAL_FEES).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(from != owner() && to != owner() && _maxBuyEnabled) require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount."); bool tradingIsEnabled = tradingEnabled; if (!tradingIsEnabled) { require(canTransferBeforeTradingIsEnabled[from], "EPRO: This account cannot send tokens until trading is enabled"); } if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) { } if (amount == 0) { super._transfer(from, to, 0); return; } if (!liquidating && tradingIsEnabled && ) { require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT."); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= liquidateTokensAtAmount; if (tradingIsEnabled && canSwap && _swapEnabled && !liquidating && !automatedMarketMakerPairs[from] && from != liquidityWallet && to != liquidityWallet ) { liquidating = true; uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES); swapAndSendToDev(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); liquidating = false; } bool takeFee = tradingIsEnabled && !liquidating; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(TOTAL_FEES).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(from != owner() && to != owner() && _maxBuyEnabled) require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount."); bool tradingIsEnabled = tradingEnabled; if (!tradingIsEnabled) { require(canTransferBeforeTradingIsEnabled[from], "EPRO: This account cannot send tokens until trading is enabled"); } if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) { } if (amount == 0) { super._transfer(from, to, 0); return; } if (!liquidating && tradingIsEnabled && ) { require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT."); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= liquidateTokensAtAmount; if (tradingIsEnabled && canSwap && _swapEnabled && !liquidating && !automatedMarketMakerPairs[from] && from != liquidityWallet && to != liquidityWallet ) { liquidating = true; uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES); swapAndSendToDev(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); liquidating = false; } bool takeFee = tradingIsEnabled && !liquidating; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(TOTAL_FEES).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(from != owner() && to != owner() && _maxBuyEnabled) require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount."); bool tradingIsEnabled = tradingEnabled; if (!tradingIsEnabled) { require(canTransferBeforeTradingIsEnabled[from], "EPRO: This account cannot send tokens until trading is enabled"); } if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) { } if (amount == 0) { super._transfer(from, to, 0); return; } if (!liquidating && tradingIsEnabled && ) { require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT."); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= liquidateTokensAtAmount; if (tradingIsEnabled && canSwap && _swapEnabled && !liquidating && !automatedMarketMakerPairs[from] && from != liquidityWallet && to != liquidityWallet ) { liquidating = true; uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES); swapAndSendToDev(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); liquidating = false; } bool takeFee = tradingIsEnabled && !liquidating; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(TOTAL_FEES).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(from != owner() && to != owner() && _maxBuyEnabled) require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount."); bool tradingIsEnabled = tradingEnabled; if (!tradingIsEnabled) { require(canTransferBeforeTradingIsEnabled[from], "EPRO: This account cannot send tokens until trading is enabled"); } if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) { } if (amount == 0) { super._transfer(from, to, 0); return; } if (!liquidating && tradingIsEnabled && ) { require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT."); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= liquidateTokensAtAmount; if (tradingIsEnabled && canSwap && _swapEnabled && !liquidating && !automatedMarketMakerPairs[from] && from != liquidityWallet && to != liquidityWallet ) { liquidating = true; uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES); swapAndSendToDev(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); liquidating = false; } bool takeFee = tradingIsEnabled && !liquidating; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(TOTAL_FEES).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(from != owner() && to != owner() && _maxBuyEnabled) require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount."); bool tradingIsEnabled = tradingEnabled; if (!tradingIsEnabled) { require(canTransferBeforeTradingIsEnabled[from], "EPRO: This account cannot send tokens until trading is enabled"); } if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) { } if (amount == 0) { super._transfer(from, to, 0); return; } if (!liquidating && tradingIsEnabled && ) { require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT."); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= liquidateTokensAtAmount; if (tradingIsEnabled && canSwap && _swapEnabled && !liquidating && !automatedMarketMakerPairs[from] && from != liquidityWallet && to != liquidityWallet ) { liquidating = true; uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES); swapAndSendToDev(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); liquidating = false; } bool takeFee = tradingIsEnabled && !liquidating; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(TOTAL_FEES).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); } try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch { if (!liquidating) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } } if (!liquidating) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } } } catch { }
2,059,072
[ 1, 1202, 635, 805, 18478, 16, 3784, 16189, 358, 1207, 3656, 17, 14784, 310, 3739, 350, 5839, 4501, 26595, 340, 2430, 364, 512, 2455, 1347, 326, 6835, 30093, 2130, 79, 2430, 635, 805, 2856, 326, 1147, 848, 1818, 506, 1284, 785, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7766, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 565, 1426, 3238, 4501, 26595, 1776, 31, 203, 203, 282, 512, 8025, 1212, 427, 26746, 8135, 1071, 31945, 8135, 31, 203, 203, 565, 1758, 1071, 4501, 372, 24237, 16936, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 1090, 4503, 67, 22364, 67, 2192, 51, 5321, 273, 2130, 11706, 380, 261, 2163, 636, 2643, 1769, 203, 203, 565, 2254, 5034, 1071, 5381, 512, 2455, 67, 862, 16777, 3948, 67, 8090, 41, 273, 1381, 31, 203, 565, 2254, 5034, 1071, 5381, 8961, 53, 3060, 4107, 67, 8090, 41, 273, 1381, 31, 203, 565, 2254, 5034, 1071, 5381, 399, 19851, 67, 8090, 3991, 273, 512, 2455, 67, 862, 16777, 3948, 67, 8090, 41, 397, 8961, 53, 3060, 4107, 67, 8090, 41, 31, 203, 565, 1426, 389, 22270, 1526, 273, 629, 31, 203, 565, 1426, 389, 1896, 38, 9835, 1526, 273, 638, 31, 203, 377, 203, 565, 1758, 8843, 429, 3238, 389, 5206, 16936, 31, 203, 203, 565, 2254, 5034, 1071, 16189, 1290, 7798, 273, 4711, 2787, 31, 203, 203, 565, 2254, 5034, 1071, 4501, 26595, 340, 5157, 861, 6275, 273, 25259, 380, 261, 2163, 636, 2643, 1769, 203, 203, 565, 1426, 1071, 1284, 7459, 1526, 31, 203, 203, 565, 445, 2 ]
./full_match/3/0xf6C7CEfcABA4d62C5301c6cA49D630C5C99Cc7B2/sources/browser/raspberry.sol
* @dev Tokens can be moved only after if transfer enabled or if you are an approved operator./
modifier canTransfer(address from) { require( _transferEnabled || hasRole(OPERATOR_ROLE, from), "RaspberryToken: transfer is not enabled or from does not have the OPERATOR role" ); _; } string memory name, string memory symbol, uint8 decimals, uint256 cap, uint256 initialSupply, bool transferEnabled, bool mintingFinished ) public ERC20Capped(cap) ERC1363(name, symbol)
14,262,026
[ 1, 5157, 848, 506, 10456, 1338, 1839, 309, 7412, 3696, 578, 309, 1846, 854, 392, 20412, 3726, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 848, 5912, 12, 2867, 628, 13, 288, 203, 3639, 2583, 12, 203, 5411, 389, 13866, 1526, 747, 28335, 12, 26110, 67, 16256, 16, 628, 3631, 203, 5411, 315, 54, 345, 5733, 21938, 1345, 30, 7412, 353, 486, 3696, 578, 628, 1552, 486, 1240, 326, 25500, 2478, 6, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 2254, 28, 15105, 16, 203, 3639, 2254, 5034, 3523, 16, 203, 3639, 2254, 5034, 2172, 3088, 1283, 16, 203, 3639, 1426, 7412, 1526, 16, 203, 3639, 1426, 312, 474, 310, 10577, 203, 565, 262, 203, 3639, 1071, 203, 3639, 4232, 39, 3462, 4664, 1845, 12, 5909, 13, 203, 3639, 4232, 39, 3437, 4449, 12, 529, 16, 3273, 13, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x4804d971b1B92930aA46bd3Fd4A262E9d197f4f6/sources/browser/contracts/Faucet.sol
Our first contract is a faucet! Give out ether to anyone who asks
contract Faucet { pragma solidity >=0.7.0 <0.8.0; function withdraw(uint withdraw_amount) public { require( withdraw_amount <= 1e8 gwei ); msg.sender.transfer( withdraw_amount ); } receive() external payable {} }
8,099,865
[ 1, 51, 295, 1122, 6835, 353, 279, 11087, 5286, 278, 5, 22374, 596, 225, 2437, 358, 1281, 476, 10354, 6827, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 478, 69, 5286, 278, 288, 203, 683, 9454, 18035, 560, 1545, 20, 18, 27, 18, 20, 411, 20, 18, 28, 18, 20, 31, 203, 915, 598, 9446, 12, 11890, 598, 9446, 67, 8949, 13, 1071, 288, 203, 6528, 12, 598, 9446, 67, 8949, 1648, 404, 73, 28, 314, 1814, 77, 11272, 203, 3576, 18, 15330, 18, 13866, 12, 598, 9446, 67, 8949, 11272, 203, 97, 203, 18149, 1435, 3903, 8843, 429, 2618, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; import '../token/ERC233Token.sol'; import 'zeppelin-solidity/contracts/token/MintableToken.sol'; import 'zeppelin-solidity/contracts/token/BurnableToken.sol'; import 'zeppelin-solidity/contracts/token/DetailedERC20.sol'; /** * @title FuturesToken * @dev FuturesToken is a token, used for InteractiveCrowdsale * * FuturesToken represents the right of owner to receive ICO tokens when it will start, * or exhange them back to Ether before the InteractiveCrowdsale finalized. * * @author DAO Ready <[email protected]> */ contract FuturesToken is ERC233Token, MintableToken, BurnableToken, DetailedERC20 { function FuturesToken(string _name, string _symbol) DetailedERC20( _name, _symbol, 18) public { } }
* @title FuturesToken @dev FuturesToken is a token, used for InteractiveCrowdsale FuturesToken represents the right of owner to receive ICO tokens when it will start, or exhange them back to Ether before the InteractiveCrowdsale finalized. @author DAO Ready <[email protected]>/
contract FuturesToken is ERC233Token, MintableToken, BurnableToken, DetailedERC20 { function FuturesToken(string _name, string _symbol) DetailedERC20( _name, _symbol, 18) public { } }
12,544,425
[ 1, 28732, 1345, 225, 478, 10945, 1345, 353, 279, 1147, 16, 1399, 364, 5294, 3535, 39, 492, 2377, 5349, 478, 10945, 1345, 8686, 326, 2145, 434, 3410, 358, 6798, 467, 3865, 2430, 1347, 518, 903, 787, 16, 578, 431, 76, 726, 2182, 1473, 358, 512, 1136, 1865, 326, 5294, 3535, 39, 492, 2377, 5349, 727, 1235, 18, 225, 463, 20463, 26732, 411, 1376, 36, 2414, 479, 361, 93, 18, 832, 16893, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 478, 10945, 1345, 353, 4232, 39, 31026, 1345, 16, 490, 474, 429, 1345, 16, 605, 321, 429, 1345, 16, 463, 6372, 654, 39, 3462, 288, 203, 203, 565, 445, 478, 10945, 1345, 12, 1080, 389, 529, 16, 533, 389, 7175, 13, 203, 3639, 463, 6372, 654, 39, 3462, 12, 389, 529, 16, 389, 7175, 16, 6549, 13, 1071, 288, 203, 565, 289, 203, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x0D0677caDC47e338fB222ca44708Ed398E108488/sources/_superfluid-finance/ethereum-contracts/contracts/apps/CFAv1Library.sol
* @dev Deletes a flow as an operator with userData @param cfaLibrary The cfaLibrary storage variable @param sender The sender of the flow @param receiver The receiver of the flow @param token The token to flow @param userData The user provided data/
function deleteFlowByOperator( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token, bytes memory userData ) internal returns (bytes memory newCtx) { return cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.deleteFlowByOperator, ( token, sender, receiver, new bytes(0) ) ), userData ); }
5,642,057
[ 1, 7551, 279, 4693, 487, 392, 3726, 598, 13530, 225, 276, 507, 9313, 1021, 276, 507, 9313, 2502, 2190, 225, 5793, 1021, 5793, 434, 326, 4693, 225, 5971, 1021, 5971, 434, 326, 4693, 225, 1147, 1021, 1147, 358, 4693, 225, 13530, 1021, 729, 2112, 501, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1430, 5249, 858, 5592, 12, 203, 3639, 4378, 751, 2502, 276, 507, 9313, 16, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 5971, 16, 203, 3639, 467, 8051, 2242, 1911, 1345, 1147, 16, 203, 3639, 1731, 3778, 13530, 203, 565, 262, 2713, 1135, 261, 3890, 3778, 394, 6442, 13, 288, 203, 3639, 327, 276, 507, 9313, 18, 2564, 18, 1991, 17420, 12, 203, 5411, 276, 507, 9313, 18, 71, 507, 16, 203, 5411, 24126, 18, 3015, 1477, 12, 203, 7734, 276, 507, 9313, 18, 71, 507, 18, 3733, 5249, 858, 5592, 16, 203, 7734, 261, 203, 10792, 1147, 16, 203, 10792, 5793, 16, 203, 10792, 5971, 16, 203, 10792, 394, 1731, 12, 20, 13, 203, 7734, 262, 203, 5411, 262, 16, 203, 5411, 13530, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/5/0x6D1Ba393ED7e26F4934746B3e82202F0eDf9563D/sources/contracts/mixins/roles/CreatorApproverRole.sol
* @notice Defines a role for managing the CreatorRole. @dev This role is managed by the AdminRole./
abstract contract CreatorApproverRole is Initializable, AccessControlUpgradeable { bytes32 public constant CREATOR_APPROVER_ROLE = keccak256("CREATOR_APPROVER_ROLE"); modifier onlyCreatorApprover() { require(hasRole(CREATOR_APPROVER_ROLE, msg.sender), "CreatorApproverRole: caller does not have the Approver role"); _; } function isCreatorApprover(address account) public view returns (bool) { return hasRole(CREATOR_APPROVER_ROLE, account); } function grantCreatorApprover(address account) public { grantRole(CREATOR_APPROVER_ROLE, account); } function revokeCreatorApprover(address account) public { revokeRole(CREATOR_APPROVER_ROLE, account); } uint256[1000] private __gap; }
16,848,400
[ 1, 15109, 279, 2478, 364, 30632, 326, 29525, 2996, 18, 225, 1220, 2478, 353, 7016, 635, 326, 7807, 2996, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 29525, 12053, 502, 2996, 353, 10188, 6934, 16, 24349, 10784, 429, 288, 203, 225, 1731, 1578, 1071, 5381, 9666, 3575, 67, 2203, 3373, 2204, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 5458, 3575, 67, 2203, 3373, 2204, 67, 16256, 8863, 203, 203, 203, 225, 9606, 1338, 10636, 12053, 502, 1435, 288, 203, 565, 2583, 12, 5332, 2996, 12, 5458, 3575, 67, 2203, 3373, 2204, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 10636, 12053, 502, 2996, 30, 4894, 1552, 486, 1240, 326, 1716, 685, 502, 2478, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 353, 10636, 12053, 502, 12, 2867, 2236, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 28335, 12, 5458, 3575, 67, 2203, 3373, 2204, 67, 16256, 16, 2236, 1769, 203, 225, 289, 203, 203, 225, 445, 7936, 10636, 12053, 502, 12, 2867, 2236, 13, 1071, 288, 203, 203, 565, 7936, 2996, 12, 5458, 3575, 67, 2203, 3373, 2204, 67, 16256, 16, 2236, 1769, 203, 225, 289, 203, 203, 225, 445, 18007, 10636, 12053, 502, 12, 2867, 2236, 13, 1071, 288, 203, 203, 565, 18007, 2996, 12, 5458, 3575, 67, 2203, 3373, 2204, 67, 16256, 16, 2236, 1769, 203, 225, 289, 203, 203, 225, 2254, 5034, 63, 18088, 65, 3238, 1001, 14048, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x8281f2bECfF37326Eb6cBE33527434611558B031/sources/PolicyController.sol
solhint-disable-line
application.updatedAt = block.timestamp;
4,153,734
[ 1, 18281, 11317, 17, 8394, 17, 1369, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 2521, 18, 7007, 861, 273, 1203, 18, 5508, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.0; contract TrustlessGambling { uint8 public constant NBR_OF_SLOTS =3; uint8 public constant PAYOUT_BLOCK_OFFSET =1; uint public constant EXPECTED_POT_AMOUNT=1000;// wei string public _message; uint public _blockNumberOnPayout; uint public _blockHashAsInteger; uint public nbrOfParticipants; // saves how many player have payed the exact amount address[NBR_OF_SLOTS] public depositAddresses; // the addresses where the player money is comming from address[NBR_OF_SLOTS] public payoutAddresses; uint public closingBlockNumber; // set when the last player enters the pot uint public payoutBlockNumber; bytes32 public payoutBlockHash; uint public winner; // 0 -> NBR_OF_SLOTS-1 bool public potClosed; // if no one uses the checkPayout function and the cotract cannot determin who won because of missing past blockhash data uint public nbrOfMissedPayouts; function TrustlessGambling() public { nbrOfParticipants = 0; potClosed = false; nbrOfMissedPayouts = 0; } // Events allow light clients to react on // changes efficiently. event Deposit(address from, address to, uint amount); event Payout(address to, uint amount); function deposit() payable public { deposit(msg.sender); } function deposit(address _payout) payable public { assert(msg.value == EXPECTED_POT_AMOUNT); assert(!potClosed); _message = "new deposit";//msg.value; depositAddresses[nbrOfParticipants] = msg.sender; payoutAddresses[nbrOfParticipants] = _payout; nbrOfParticipants++; Deposit(msg.sender, _payout, msg.value); if (nbrOfParticipants == NBR_OF_SLOTS){ closingBlockNumber = block.number; payoutBlockNumber = closingBlockNumber + PAYOUT_BLOCK_OFFSET; potClosed = true; } } function payout() public{ assert(potClosed); //pot not full yet assert(block.number>payoutBlockNumber); // block for to select the winner not mined yet. _blockNumberOnPayout = block.number; payoutBlockHash = block.blockhash(payoutBlockNumber); // get the blockhash if(payoutBlockHash == 0){ _message = "Can not payout because checkPayout-function was triggered too late. Funds are added to new pot."; nbrOfMissedPayouts++; }else{ _message = "Payout triggered!"; _blockHashAsInteger = uint(payoutBlockHash); winner = uint(payoutBlockHash) % NBR_OF_SLOTS; address winnerAddress = payoutAddresses[winner]; uint amount= EXPECTED_POT_AMOUNT*NBR_OF_SLOTS; // pot amount amount += EXPECTED_POT_AMOUNT*NBR_OF_SLOTS*nbrOfMissedPayouts; // add missed out pot amounts winnerAddress.transfer(amount); // send pot amount to winner nbrOfMissedPayouts = 0; // all funds are out } potClosed = false; // contains serious bug. nbrOfParticipants=0; //start next round } }
Events allow light clients to react on changes efficiently.
event Deposit(address from, address to, uint amount);
7,230,408
[ 1, 3783, 1699, 9052, 7712, 358, 13417, 603, 3478, 14382, 715, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 4019, 538, 305, 12, 2867, 628, 16, 1758, 358, 16, 2254, 3844, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xaebf76CC6A6792662D8D9fE1bF5917C989871c82/sources/Token.sol
* @dev transfer token for a specified address @param _to The address to transfer to. @param _value The amount to be transferred./
function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
3,641,678
[ 1, 13866, 1147, 364, 279, 1269, 1758, 225, 389, 869, 1021, 1758, 358, 7412, 358, 18, 225, 389, 1132, 1021, 3844, 358, 506, 906, 4193, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 2216, 13, 203, 565, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 24899, 1132, 1648, 324, 26488, 63, 3576, 18, 15330, 19226, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 3639, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function sub0(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a - b : 0; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } contract Governable is Initializable { // bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1) bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; address public governor; event GovernorshipTransferred(address indexed previousGovernor, address indexed newGovernor); /** * @dev Contract initializer. * called once by the factory at time of deployment */ function __Governable_init_unchained(address governor_) virtual public initializer { governor = governor_; emit GovernorshipTransferred(address(0), governor); } function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } modifier governance() { require(msg.sender == governor || msg.sender == _admin()); _; } /** * @dev Allows the current governor to relinquish control of the contract. * @notice Renouncing to governorship will leave the contract without an governor. * It will not be possible to call the functions with the `governance` * modifier anymore. */ function renounceGovernorship() public governance { emit GovernorshipTransferred(governor, address(0)); governor = address(0); } /** * @dev Allows the current governor to transfer control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function transferGovernorship(address newGovernor) public governance { _transferGovernorship(newGovernor); } /** * @dev Transfers control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function _transferGovernorship(address newGovernor) internal { require(newGovernor != address(0)); emit GovernorshipTransferred(governor, newGovernor); governor = newGovernor; } } contract Configurable is Governable { mapping (bytes32 => uint) internal config; function getConfig(bytes32 key) public view returns (uint) { return config[key]; } function getConfigI(bytes32 key, uint index) public view returns (uint) { return config[bytes32(uint(key) ^ index)]; } function getConfigA(bytes32 key, address addr) public view returns (uint) { return config[bytes32(uint(key) ^ uint(addr))]; } function _setConfig(bytes32 key, uint value) internal { if(config[key] != value) config[key] = value; } function _setConfig(bytes32 key, uint index, uint value) internal { _setConfig(bytes32(uint(key) ^ index), value); } function _setConfig(bytes32 key, address addr, uint value) internal { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } function setConfig(bytes32 key, uint value) external governance { _setConfig(key, value); } function setConfigI(bytes32 key, uint index, uint value) external governance { _setConfig(bytes32(uint(key) ^ index), value); } function setConfigA(bytes32 key, address addr, uint value) public governance { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } } contract RewardsDistributor is Configurable { using SafeERC20 for IERC20; address public rewardsToken; function __RewardsDistributor_init(address governor, address _rewardsToken) public initializer { __Governable_init_unchained(governor); __RewardsDistributor_init_unchained(_rewardsToken); } function __RewardsDistributor_init_unchained(address _rewardsToken) public governance { rewardsToken = _rewardsToken; } function approvePool(address pool, uint amount) public governance { //IERC20(rewardsToken).safeApprove(pool, amount); IERC20(rewardsToken).approve(pool, amount); // GT do not support safeApprove } } // Inheritancea interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewards(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } abstract contract DodoPool { function rewardTokenInfos(uint256 i) public view virtual returns(address rewardToken, uint256 startBlock, uint256 endBlock, address rewardVault, uint256 rewardPerBlock, uint256 accRewardPerShare, uint256 lastRewardBlock); /*mapping(address => uint256) memory userRewardPerSharePaid, mapping(address => uint256) memory userRewards);*/ function getPendingReward(address user, uint256 i) external view virtual returns (uint256); function getPendingRewardByToken(address user, address rewardToken) external view virtual returns (uint256); function totalSupply() public view virtual returns (uint256); function balanceOf(address user) public view virtual returns (uint256); function getRewardTokenById(uint256 i) external view virtual returns (address); function getIdByRewardToken(address rewardToken) external view virtual returns(uint256); function getRewardNum() external view virtual returns(uint256); // ============ Claim ============ function deposit(uint256 amount) external virtual; function withdraw(uint256 amount) external virtual; function claimReward(uint256 i) external virtual; function claimAllRewards() external virtual; } abstract contract RewardsDistributionRecipient { address public rewardsDistribution; function notifyRewardAmount(uint256 reward) virtual external; modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "Caller is not RewardsDistribution contract"); _; } } contract StakingRewards is IStakingRewards, RewardsDistributionRecipient, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; // obsoleted uint256 public rewardsDuration = 60 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) override public rewards; uint256 internal _totalSupply; mapping(address => uint256) internal _balances; /* ========== CONSTRUCTOR ========== */ //constructor( function __StakingRewards_init( address _rewardsDistribution, address _rewardsToken, address _stakingToken ) public initializer { __ReentrancyGuard_init_unchained(); __StakingRewards_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken); } function __StakingRewards_init_unchained( address _rewardsDistribution, address _rewardsToken, address _stakingToken ) public initializer { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); rewardsDistribution = _rewardsDistribution; } /* ========== VIEWS ========== */ function totalSupply() override external view returns (uint256) { return _totalSupply; } function balanceOf(address account) override external view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() override public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() virtual override public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply) ); } function earned(address account) virtual override public view returns (uint256) { return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); } function getRewardForDuration() virtual override external view returns (uint256) { return rewardRate.mul(rewardsDuration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stakeWithPermit(uint256 amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); // permit IPermit(address(stakingToken)).permit(msg.sender, address(this), amount, deadline, v, r, s); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function stake(uint256 amount) virtual override public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) virtual override public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() virtual override public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() virtual override public { withdraw(_balances[msg.sender]); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward) override external onlyRewardsDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint balance = rewardsToken.balanceOf(address(this)); require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) virtual { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); } interface IPermit { function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } contract StakingPool is Configurable, StakingRewards { using Address for address payable; bytes32 internal constant _ecoAddr_ = 'ecoAddr'; bytes32 internal constant _ecoRatio_ = 'ecoRatio'; bytes32 internal constant _allowContract_ = 'allowContract'; bytes32 internal constant _allowlist_ = 'allowlist'; bytes32 internal constant _blocklist_ = 'blocklist'; uint public lep; // 1: linear, 2: exponential, 3: power uint public period; uint public begin; function __StakingPool_init(address _governor, address _rewardsDistribution, address _rewardsToken, address _stakingToken, address _ecoAddr ) public initializer { __Governable_init_unchained(_governor); __ReentrancyGuard_init_unchained(); __StakingRewards_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken); __StakingPool_init_unchained(_ecoAddr); } function __StakingPool_init_unchained(address _ecoAddr) public governance { config[_ecoAddr_] = uint(_ecoAddr); config[_ecoRatio_] = 0.181818181818181818 ether; } function notifyRewardBegin(uint _lep, uint _period, uint _span, uint _begin) virtual public governance updateReward(address(0)) { lep = _lep; // 1: linear, 2: exponential, 3: power period = _period; rewardsDuration = _span; begin = _begin; periodFinish = _begin.add(_span); } function rewardDelta() public view returns (uint amt) { if(begin == 0 || begin >= now || lastUpdateTime >= now) return 0; amt = Math.min(rewardsToken.allowance(rewardsDistribution, address(this)), rewardsToken.balanceOf(rewardsDistribution)).sub0(rewards[address(0)]); // calc rewardDelta in period if(lep == 3) { // power uint y = period.mul(1 ether).div(lastUpdateTime.add(rewardsDuration).sub(begin)); uint amt1 = amt.mul(1 ether).div(y); uint amt2 = amt1.mul(period).div(now.add(rewardsDuration).sub(begin)); amt = amt.sub(amt2); } else if(lep == 2) { // exponential if(now.sub(lastUpdateTime) < rewardsDuration) amt = amt.mul(now.sub(lastUpdateTime)).div(rewardsDuration); }else if(now < periodFinish) // linear amt = amt.mul(now.sub(lastUpdateTime)).div(periodFinish.sub(lastUpdateTime)); else if(lastUpdateTime >= periodFinish) amt = 0; if(config[_ecoAddr_] != 0) amt = amt.mul(uint(1e18).sub(config[_ecoRatio_])).div(1 ether); } function rewardPerToken() override public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( rewardDelta().mul(1e18).div(_totalSupply) ); } function earned(address account) virtual override public view returns (uint256) { return Math.min(Math.min(super.earned(account), rewardsToken.allowance(rewardsDistribution, address(this))), rewardsToken.balanceOf(rewardsDistribution)); } modifier updateReward(address account) override { rewardPerTokenStored = rewardPerToken(); uint delta = rewardDelta(); { address addr = address(config[_ecoAddr_]); uint ratio = config[_ecoRatio_]; if(addr != address(0) && ratio != 0) { uint d = delta.mul(ratio).div(uint(1e18).sub(ratio)); rewards[addr] = rewards[addr].add(d); delta = delta.add(d); } } rewards[address(0)] = rewards[address(0)].add(delta); lastUpdateTime = now; if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function getReward() override public nonReentrant updateReward(msg.sender) { require(getConfigA(_blocklist_, msg.sender) == 0, 'In blocklist'); bool isContract = msg.sender.isContract(); require(!isContract || config[_allowContract_] != 0 || getConfigA(_allowlist_, msg.sender) != 0, 'No allowContract'); uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewards[address(0)] = rewards[address(0)].sub0(reward); rewardsToken.safeTransferFrom(rewardsDistribution, msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function stakeAndCompound(uint amount) virtual public { stake(amount); compound(); } function compound() virtual public nonReentrant updateReward(msg.sender) { // only for pool3 require(getConfigA(_blocklist_, msg.sender) == 0, 'In blocklist'); bool isContract = msg.sender.isContract(); require(!isContract || config[_allowContract_] != 0 || getConfigA(_allowlist_, msg.sender) != 0, 'No allowContract'); require(stakingToken == rewardsToken, 'not pool3'); uint reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewards[address(0)] = rewards[address(0)].sub0(reward); rewardsToken.safeTransferFrom(rewardsDistribution, address(this), reward); emit RewardPaid(msg.sender, reward); _totalSupply = _totalSupply.add(reward); _balances[msg.sender] = _balances[msg.sender].add(reward); emit Staked(msg.sender, reward); } } function getRewardForDuration() override external view returns (uint256) { return rewardsToken.allowance(rewardsDistribution, address(this)).sub0(rewards[address(0)]); } } contract DoublePool is StakingPool { IStakingRewards public stakingPool2; IERC20 public rewardsToken2; mapping(address => uint256) public userRewardPerTokenPaid2; mapping(address => uint256) public rewards2; function __DoublePool_init(address _governor, address _rewardsDistribution, address _rewardsToken, address _stakingToken, address _ecoAddr, address _stakingPool2, address _rewardsToken2) public initializer { __Governable_init_unchained(_governor); __ReentrancyGuard_init_unchained(); __StakingRewards_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken); __StakingPool_init_unchained(_ecoAddr); __DoublePool_init_unchained(_stakingPool2, _rewardsToken2); } function __DoublePool_init_unchained(address _stakingPool2, address _rewardsToken2) public governance { stakingPool2 = IStakingRewards(_stakingPool2); rewardsToken2 = IERC20(_rewardsToken2); } function notifyRewardBegin(uint _lep, uint _period, uint _span, uint _begin) virtual override public governance updateReward2(address(0)) { super.notifyRewardBegin(_lep, _period, _span, _begin); } function stake(uint amount) virtual override public updateReward2(msg.sender) { super.stake(amount); stakingToken.safeApprove(address(stakingPool2), amount); stakingPool2.stake(amount); } function withdraw(uint amount) virtual override public updateReward2(msg.sender) { stakingPool2.withdraw(amount); super.withdraw(amount); } function getReward2() virtual public nonReentrant updateReward2(msg.sender) { uint256 reward2 = rewards2[msg.sender]; if (reward2 > 0) { rewards2[msg.sender] = 0; stakingPool2.getReward(); rewardsToken2.safeTransfer(msg.sender, reward2); emit RewardPaid2(msg.sender, reward2); } } event RewardPaid2(address indexed user, uint256 reward2); function getDoubleReward() virtual public { getReward(); getReward2(); } function exit() override public { super.exit(); getReward2(); } function rewardPerToken2() virtual public view returns (uint256) { return stakingPool2.rewardPerToken(); } function earned2(address account) virtual public view returns (uint256) { return _balances[account].mul(rewardPerToken2().sub(userRewardPerTokenPaid2[account])).div(1e18).add(rewards2[account]); } modifier updateReward2(address account) virtual { if (account != address(0)) { rewards2[account] = earned2(account); userRewardPerTokenPaid2[account] = rewardPerToken2(); } _; } } contract DoublePoolDodo is StakingPool { using SafeMath for uint256; struct RewardTokenInfo { address rewardToken; uint256 startBlock; uint256 endBlock; address rewardVault; uint256 rewardPerBlock; uint256 accRewardPerShare; uint256 lastRewardBlock; mapping(address => uint256) userRewardPerSharePaid; mapping(address => uint256) userRewards; } DodoPool public dodoPool2; IERC20 public rewardsToken2; mapping(address => uint256) public userRewardPerTokenPaid2; mapping(address => uint256) public rewards2; function __DoublePool_init(address _governor, address _rewardsDistribution, address _rewardsToken, address _stakingToken, address _ecoAddr, address _dodoPool2, address _rewardsToken2) public initializer { __Governable_init_unchained(_governor); __ReentrancyGuard_init_unchained(); __StakingRewards_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken); __StakingPool_init_unchained(_ecoAddr); __DoublePool_init_unchained(_dodoPool2, _rewardsToken2); } function __DoublePool_init_unchained(address _dodoPool2, address _rewardsToken2) public governance { dodoPool2 = DodoPool(_dodoPool2); rewardsToken2 = IERC20(_rewardsToken2); } function notifyRewardBegin(uint _lep, uint _period, uint _span, uint _begin) virtual override public governance updateReward2(address(0)){ super.notifyRewardBegin(_lep, _period, _span, _begin); } function stake(uint amount) virtual override public updateReward2(msg.sender) { super.stake(amount); stakingToken.safeApprove(address(dodoPool2), amount); dodoPool2.deposit(amount); } function withdraw(uint amount) virtual override public updateReward2(msg.sender) { dodoPool2.withdraw(amount); super.withdraw(amount); } function getReward2() virtual public nonReentrant updateReward2(msg.sender) { uint256 reward2 = rewards2[msg.sender]; if(reward2>0){ rewards2[msg.sender] = 0; dodoPool2.claimReward(0); rewardsToken2.safeTransfer(msg.sender, reward2); emit RewardPaid2(msg.sender, reward2); } } event RewardPaid2(address indexed user, uint256 reward2); function getDoubleReward() virtual public { getReward(); getReward2(); } function exit() override public { super.exit(); getReward2(); } function rewardPerToken2() virtual public view returns (uint256) { return getAccRewardPerShare(0); } function earned2(address account) virtual public view returns (uint256) { //return dodoPool2.getPendingReward(account,0); return _balances[account].mul(rewardPerToken2().sub(userRewardPerTokenPaid2[account])).div(1e18).add(rewards2[account]); } modifier updateReward2(address account) virtual { if (account != address(0)) { rewards2[account] = earned2(account); userRewardPerTokenPaid2[account] = rewardPerToken2(); } _; } function _getUnrewardBlockNum(uint256 i) internal view returns (uint256) { RewardTokenInfo memory rt; (rt.rewardToken,rt.startBlock,rt.endBlock,rt.rewardVault,rt.rewardPerBlock,rt.accRewardPerShare,rt.lastRewardBlock) = dodoPool2.rewardTokenInfos(i); if (block.number < rt.startBlock || rt.lastRewardBlock > rt.endBlock) { return 0; } uint256 start = rt.lastRewardBlock < rt.startBlock ? rt.startBlock : rt.lastRewardBlock; uint256 end = rt.endBlock < block.number ? rt.endBlock : block.number; return end.sub(start); } function getAccRewardPerShare(uint256 i) public view returns (uint256) { RewardTokenInfo memory rt; (rt.rewardToken,rt.startBlock,rt.endBlock,rt.rewardVault,rt.rewardPerBlock,rt.accRewardPerShare,rt.lastRewardBlock) = dodoPool2.rewardTokenInfos(i); if (dodoPool2.totalSupply() == 0) { return rt.accRewardPerShare; } return rt.accRewardPerShare.add(divFloor(_getUnrewardBlockNum(i).mul(rt.rewardPerBlock), dodoPool2.totalSupply())); } function divFloor(uint256 target, uint256 d) internal pure returns (uint256) { return target.mul(10**18).div(d); } } interface IMasterChef { function poolInfo(uint pid) external view returns (address lpToken, uint allocPoint, uint lastRewardBlock, uint accCakePerShare); function userInfo(uint pid, address user) external view returns (uint amount, uint rewardDebt); function pending(uint pid, address user) external view returns (uint); function pendingCake(uint pid, address user) external view returns (uint); function deposit(uint pid, uint amount) external; function withdraw(uint pid, uint amount) external; } contract NestMasterChef is StakingPool { IERC20 internal constant Cake = IERC20(0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82); IMasterChef public stakingPool2; IERC20 public rewardsToken2; mapping(address => uint256) public userRewardPerTokenPaid2; mapping(address => uint256) public rewards2; uint public pid2; uint internal _rewardPerToken2; function __NestMasterChef_init(address _governor, address _rewardsDistribution, address _rewardsToken, address _stakingToken, address _ecoAddr, address _stakingPool2, address _rewardsToken2, uint _pid2) public initializer { __Governable_init_unchained(_governor); __ReentrancyGuard_init_unchained(); __StakingRewards_init_unchained(_rewardsDistribution, _rewardsToken, _stakingToken); __StakingPool_init_unchained(_ecoAddr); __NestMasterChef_init_unchained(_stakingPool2, _rewardsToken2, _pid2); } function __NestMasterChef_init_unchained(address _stakingPool2, address _rewardsToken2, uint _pid2) public governance { stakingPool2 = IMasterChef(_stakingPool2); rewardsToken2 = IERC20(_rewardsToken2); pid2 = _pid2; } function notifyRewardBegin(uint _lep, uint _period, uint _span, uint _begin) virtual override public governance updateReward2(address(0)) { super.notifyRewardBegin(_lep, _period, _span, _begin); } function migrate() virtual public governance updateReward2(address(0)) { uint total = stakingToken.balanceOf(address(this)); stakingToken.approve(address(stakingPool2), total); stakingPool2.deposit(pid2, total); } function stake(uint amount) virtual override public updateReward2(msg.sender) { super.stake(amount); stakingToken.approve(address(stakingPool2), amount); stakingPool2.deposit(pid2, amount); } function withdraw(uint amount) virtual override public updateReward2(msg.sender) { stakingPool2.withdraw(pid2, amount); super.withdraw(amount); } function getReward2() virtual public nonReentrant updateReward2(msg.sender) { uint256 reward2 = rewards2[msg.sender]; if (reward2 > 0) { rewards2[msg.sender] = 0; rewardsToken2.safeTransfer(msg.sender, reward2); emit RewardPaid2(msg.sender, reward2); } } event RewardPaid2(address indexed user, uint256 reward2); function getDoubleReward() virtual public { getReward(); getReward2(); } function exit() virtual override public { super.exit(); getReward2(); } function rewardPerToken2() virtual public view returns (uint256) { if(_totalSupply == 0) return _rewardPerToken2; else if(rewardsToken2 == Cake) return stakingPool2.pendingCake(pid2, address(this)).mul(1e18).div(_totalSupply).add(_rewardPerToken2); else return stakingPool2.pending(pid2, address(this)).mul(1e18).div(_totalSupply).add(_rewardPerToken2); } function earned2(address account) virtual public view returns (uint256) { return _balances[account].mul(rewardPerToken2().sub(userRewardPerTokenPaid2[account])).div(1e18).add(rewards2[account]); } modifier updateReward2(address account) virtual { if(_totalSupply > 0) { uint delta = rewardsToken2.balanceOf(address(this)); stakingPool2.deposit(pid2, 0); delta = rewardsToken2.balanceOf(address(this)).sub(delta); _rewardPerToken2 = delta.mul(1e18).div(_totalSupply).add(_rewardPerToken2); } if (account != address(0)) { rewards2[account] = earned2(account); userRewardPerTokenPaid2[account] = _rewardPerToken2; } _; } uint256[50] private __gap; } contract IioPool is StakingPool { address internal constant HelmetAddress = 0x948d2a81086A075b3130BAc19e4c6DEe1D2E3fE8; address internal constant BurnAddress = 0x000000000000000000000000000000000000dEaD; uint public lastUpdateTime3; IERC20 public rewardsToken3; mapping(IERC20 => uint) public totalSupply3; // rewardsToken3 => totalSupply3 mapping(IERC20 => uint) internal _rewardPerToken3; // rewardsToken3 => _rewardPerToken3 mapping(IERC20 => uint) public begin3; // rewardsToken3 => begin3 mapping(IERC20 => uint) public end3; // rewardsToken3 => end3 mapping(IERC20 => uint) public claimTime3; // rewardsToken3 => claimTime3 mapping(IERC20 => uint) public ticketVol3; // rewardsToken3 => ticketVol3 mapping(IERC20 => IERC20) public ticketToken3; // rewardsToken3 => ticketToken3 mapping(IERC20 => address) public ticketRecipient3; // rewardsToken3 => ticketRecipient3 mapping(IERC20 => mapping(address => bool)) public applied3; // rewardsToken3 => acct => applied3 mapping(IERC20 => mapping(address => uint)) public userRewardPerTokenPaid3; // rewardsToken3 => acct => paid3 mapping(IERC20 => mapping(address => uint)) public rewards3; // rewardsToken3 => acct => rewards3 function setReward3BurnHelmet(IERC20 rewardsToken3_, uint begin3_, uint end3_, uint claimTime3_, uint ticketVol3_) virtual external { setReward3(rewardsToken3_, begin3_, end3_, claimTime3_, ticketVol3_, IERC20(HelmetAddress), BurnAddress); } function setReward3(IERC20 rewardsToken3_, uint begin3_, uint end3_, uint claimTime3_, uint ticketVol3_, IERC20 ticketToken3_, address ticketRecipient3_) virtual public governance { lastUpdateTime3 = begin3_; rewardsToken3 = rewardsToken3_; begin3 [rewardsToken3_] = begin3_; end3 [rewardsToken3_] = end3_; claimTime3 [rewardsToken3_] = claimTime3_; ticketVol3 [rewardsToken3_] = ticketVol3_; ticketToken3 [rewardsToken3_] = ticketToken3_; ticketRecipient3 [rewardsToken3_] = ticketRecipient3_; emit SetReward3(rewardsToken3_, begin3_, end3_, claimTime3_, ticketVol3_, ticketToken3_, ticketRecipient3_); } event SetReward3(IERC20 indexed rewardsToken3_, uint begin3_, uint end3_, uint claimTime3_, uint ticketVol3_, IERC20 indexed ticketToken3_, address indexed ticketRecipient3_); function applyReward3() virtual public updateReward3(msg.sender) { IERC20 rewardsToken3_ = rewardsToken3; // save gas require(!applied3[rewardsToken3_][msg.sender], 'applied already'); require(now < end3[rewardsToken3_], 'expired'); IERC20 ticketToken3_ = ticketToken3[rewardsToken3_]; // save gas if(address(ticketToken3_) != address(0)) ticketToken3_.safeTransferFrom(msg.sender, ticketRecipient3[rewardsToken3_], ticketVol3[rewardsToken3_]); applied3[rewardsToken3_][msg.sender] = true; userRewardPerTokenPaid3[rewardsToken3_][msg.sender] = _rewardPerToken3[rewardsToken3_]; totalSupply3[rewardsToken3_] = totalSupply3[rewardsToken3_].add(_balances[msg.sender]); emit ApplyReward3(msg.sender, rewardsToken3_); } event ApplyReward3(address indexed acct, IERC20 indexed rewardsToken3); function rewardDelta3() virtual public view returns (uint amt) { IERC20 rewardsToken3_ = rewardsToken3; // save gas uint lastUpdateTime3_ = lastUpdateTime3; // save gas if(begin3[rewardsToken3_] == 0 || begin3[rewardsToken3_] >= now || lastUpdateTime3_ >= now) return 0; amt = Math.min(rewardsToken3_.allowance(rewardsDistribution, address(this)), rewardsToken3_.balanceOf(rewardsDistribution)).sub0(rewards3[rewardsToken3_][address(0)]); uint end3_ = end3[rewardsToken3_]; // save gas if(now < end3_) amt = amt.mul(now.sub(lastUpdateTime3_)).div(end3_.sub(lastUpdateTime3_)); else if(lastUpdateTime3_ >= end3_) amt = 0; } function rewardPerToken3() virtual public view returns (uint) { if (totalSupply3[rewardsToken3] == 0) { return _rewardPerToken3[rewardsToken3]; } return _rewardPerToken3[rewardsToken3].add( rewardDelta3().mul(1e18).div(totalSupply3[rewardsToken3]) ); } function earned3(address account) virtual public view returns (uint) { if(!applied3[rewardsToken3][account]) return 0; return Math.min(rewardsToken3.balanceOf(rewardsDistribution), _balances[account].mul(rewardPerToken3().sub(userRewardPerTokenPaid3[rewardsToken3][account])).div(1e18).add(rewards3[rewardsToken3][account])); } modifier updateReward3(address account) virtual { IERC20 rewardsToken3_ = rewardsToken3; // save gas bool applied3_ = applied3[rewardsToken3_][account]; // save gas if(account == address(0) || applied3_) { _rewardPerToken3[rewardsToken3_] = rewardPerToken3(); rewards3[rewardsToken3_][address(0)] = rewards3[rewardsToken3_][address(0)].add(rewardDelta3()); lastUpdateTime3 = Math.max(begin3[rewardsToken3_], Math.min(now, end3[rewardsToken3_])); } if (account != address(0) && applied3_) { uint amt = rewards3[rewardsToken3_][account]; rewards3[rewardsToken3_][account] = earned3(account); userRewardPerTokenPaid3[rewardsToken3_][account] = _rewardPerToken3[rewardsToken3_]; amt = rewards3[rewardsToken3_][account].sub0(amt); address addr = address(config[_ecoAddr_]); uint ratio = config[_ecoRatio_]; if(addr != address(0) && addr != account && ratio != 0) { uint a = amt.mul(ratio).div(1 ether); rewards3[rewardsToken3_][addr] = rewards3[rewardsToken3_][addr].add(a); rewards3[rewardsToken3_][address(0)] = rewards3[rewardsToken3_][address(0)].add(a); } } _; } function stake(uint amount) virtual override public updateReward3(msg.sender) { super.stake(amount); IERC20 rewardsToken3_ = rewardsToken3; // save gas if(applied3[rewardsToken3_][msg.sender]) totalSupply3[rewardsToken3_] = totalSupply3[rewardsToken3_].add(amount); } function withdraw(uint amount) virtual override public updateReward3(msg.sender) { IERC20 rewardsToken3_ = rewardsToken3; // save gas if(applied3[rewardsToken3_][msg.sender]) totalSupply3[rewardsToken3_] = totalSupply3[rewardsToken3_].sub(amount); super.withdraw(amount); } function getReward3() virtual public nonReentrant updateReward3(msg.sender) { require(getConfigA(_blocklist_, msg.sender) == 0, 'In blocklist'); bool isContract = msg.sender.isContract(); require(!isContract || config[_allowContract_] != 0 || getConfigA(_allowlist_, msg.sender) != 0, 'No allowContract'); IERC20 rewardsToken3_ = rewardsToken3; // save gas require(now >= claimTime3[rewardsToken3_], "it's not time yet"); uint256 reward3 = rewards3[rewardsToken3_][msg.sender]; if (reward3 > 0) { rewards3[rewardsToken3_][msg.sender] = 0; rewards3[rewardsToken3_][address(0)] = rewards3[rewardsToken3_][address(0)].sub0(reward3); rewardsToken3_.safeTransferFrom(rewardsDistribution, msg.sender, reward3); emit RewardPaid3(msg.sender, rewardsToken3_, reward3); } } event RewardPaid3(address indexed user, IERC20 indexed rewardsToken3_, uint256 reward3); uint[50] private __gap; } contract NestMasterChefIio is NestMasterChef, IioPool { function notifyRewardBegin(uint _lep, uint _period, uint _span, uint _begin) virtual override(StakingPool, NestMasterChef) public { NestMasterChef.notifyRewardBegin(_lep, _period, _span, _begin); } function stake(uint amount) virtual override(NestMasterChef, IioPool) public { super.stake(amount); } function withdraw(uint amount) virtual override(NestMasterChef, IioPool) public { super.withdraw(amount); } function exit() virtual override(StakingRewards, NestMasterChef) public { NestMasterChef.exit(); } uint[50] private __gap; } contract IioPoolV2 is StakingPool { // support multi IIO at the same time address internal constant HelmetAddress = 0x948d2a81086A075b3130BAc19e4c6DEe1D2E3fE8; address internal constant BurnAddress = 0x000000000000000000000000000000000000dEaD; bytes32 internal constant _ecoRatio3_ = 'ecoRatio3'; uint private __lastUpdateTime3; // obsolete IERC20 private __rewardsToken3; // obsolete mapping(IERC20 => uint) public totalSupply3; // rewardsToken3 => totalSupply3 mapping(IERC20 => uint) internal _rewardPerToken3; // rewardsToken3 => _rewardPerToken3 mapping(IERC20 => uint) public begin3; // rewardsToken3 => begin3 mapping(IERC20 => uint) public end3; // rewardsToken3 => end3 mapping(IERC20 => uint) public claimTime3; // rewardsToken3 => claimTime3 mapping(IERC20 => uint) public ticketVol3; // rewardsToken3 => ticketVol3 mapping(IERC20 => IERC20) public ticketToken3; // rewardsToken3 => ticketToken3 mapping(IERC20 => address) public ticketRecipient3; // rewardsToken3 => ticketRecipient3 mapping(IERC20 => mapping(address => bool)) public applied3; // rewardsToken3 => acct => applied3 mapping(IERC20 => mapping(address => uint)) public userRewardPerTokenPaid3; // rewardsToken3 => acct => paid3 mapping(IERC20 => mapping(address => uint)) public rewards3; // rewardsToken3 => acct => rewards3 mapping(IERC20 => uint) public lastUpdateTime3; // rewardsToken3 => lastUpdateTime3 IERC20[] public all; // all rewardsToken3 IERC20[] public active; // active rewardsToken3 function setReward3BurnHelmet(IERC20 rewardsToken3_, uint begin3_, uint end3_, uint claimTime3_, uint ticketVol3_) virtual external { setReward3(rewardsToken3_, begin3_, end3_, claimTime3_, ticketVol3_, IERC20(HelmetAddress), BurnAddress); } function setReward3(IERC20 rewardsToken3_, uint begin3_, uint end3_, uint claimTime3_, uint ticketVol3_, IERC20 ticketToken3_, address ticketRecipient3_) virtual public governance { lastUpdateTime3 [rewardsToken3_]= begin3_; //rewardsToken3 = rewardsToken3_; begin3 [rewardsToken3_] = begin3_; end3 [rewardsToken3_] = end3_; claimTime3 [rewardsToken3_] = claimTime3_; ticketVol3 [rewardsToken3_] = ticketVol3_; ticketToken3 [rewardsToken3_] = ticketToken3_; ticketRecipient3 [rewardsToken3_] = ticketRecipient3_; _setConfig(_ecoRatio3_, address(rewardsToken3_), 0.10 ether); uint i=0; for(; i<all.length; i++) if(all[i] == rewardsToken3_) break; if(i>=all.length) all.push(rewardsToken3_); i=0; for(; i<active.length; i++) if(active[i] == rewardsToken3_) break; if(i>=active.length) active.push(rewardsToken3_); emit SetReward3(rewardsToken3_, begin3_, end3_, claimTime3_, ticketVol3_, ticketToken3_, ticketRecipient3_); } event SetReward3(IERC20 indexed rewardsToken3_, uint begin3_, uint end3_, uint claimTime3_, uint ticketVol3_, IERC20 indexed ticketToken3_, address indexed ticketRecipient3_); function deactive(IERC20 rewardsToken3_) virtual public governance { for(uint i=0; i<active.length; i++) if(active[i] == rewardsToken3_) { active[i] = active[active.length-1]; active.pop(); emit Deactive(rewardsToken3_); return; } revert('not found active rewardsToken3_'); } event Deactive(IERC20 indexed rewardsToken3_); function applyReward3(IERC20 rewardsToken3_) virtual public updateReward3(rewardsToken3_, msg.sender) { //IERC20 rewardsToken3_ = rewardsToken3; // save gas require(!applied3[rewardsToken3_][msg.sender], 'applied already'); require(now < end3[rewardsToken3_], 'expired'); IERC20 ticketToken3_ = ticketToken3[rewardsToken3_]; // save gas if(address(ticketToken3_) != address(0)) ticketToken3_.safeTransferFrom(msg.sender, ticketRecipient3[rewardsToken3_], ticketVol3[rewardsToken3_]); applied3[rewardsToken3_][msg.sender] = true; userRewardPerTokenPaid3[rewardsToken3_][msg.sender] = _rewardPerToken3[rewardsToken3_]; totalSupply3[rewardsToken3_] = totalSupply3[rewardsToken3_].add(_balances[msg.sender]); emit ApplyReward3(msg.sender, rewardsToken3_); } event ApplyReward3(address indexed acct, IERC20 indexed rewardsToken3); function rewardDelta3(IERC20 rewardsToken3_) virtual public view returns (uint amt) { //IERC20 rewardsToken3_ = rewardsToken3; // save gas uint lastUpdateTime3_ = lastUpdateTime3[rewardsToken3_]; // save gas if(begin3[rewardsToken3_] == 0 || begin3[rewardsToken3_] >= now || lastUpdateTime3_ >= now) return 0; amt = Math.min(rewardsToken3_.allowance(rewardsDistribution, address(this)), rewardsToken3_.balanceOf(rewardsDistribution)).sub0(rewards3[rewardsToken3_][address(0)]); uint end3_ = end3[rewardsToken3_]; // save gas if(now < end3_) amt = amt.mul(now.sub(lastUpdateTime3_)).div(end3_.sub(lastUpdateTime3_)); else if(lastUpdateTime3_ >= end3_) amt = 0; if(config[_ecoAddr_] != 0) amt = amt.mul(uint(1e18).sub(getConfigA(_ecoRatio3_, address(rewardsToken3_)))).div(1 ether); } function rewardPerToken3(IERC20 rewardsToken3_) virtual public view returns (uint) { if (totalSupply3[rewardsToken3_] == 0) { return _rewardPerToken3[rewardsToken3_]; } return _rewardPerToken3[rewardsToken3_].add( rewardDelta3(rewardsToken3_).mul(1e18).div(totalSupply3[rewardsToken3_]) ); } function earned3(IERC20 rewardsToken3_, address account) virtual public view returns (uint) { if(!applied3[rewardsToken3_][account]) return 0; return Math.min(rewardsToken3_.balanceOf(rewardsDistribution), _balances[account].mul(rewardPerToken3(rewardsToken3_).sub(userRewardPerTokenPaid3[rewardsToken3_][account])).div(1e18).add(rewards3[rewardsToken3_][account])); } function _updateReward3(IERC20 rewardsToken3_, address account) virtual internal { bool applied3_ = applied3[rewardsToken3_][account]; // save gas if(account == address(0) || applied3_) { _rewardPerToken3[rewardsToken3_] = rewardPerToken3(rewardsToken3_); uint delta = rewardDelta3(rewardsToken3_); { address addr = address(config[_ecoAddr_]); uint ratio = getConfigA(_ecoRatio3_, address(rewardsToken3_)); if(addr != address(0) && ratio != 0) { uint d = delta.mul(ratio).div(uint(1e18).sub(ratio)); rewards3[rewardsToken3_][addr] = rewards3[rewardsToken3_][addr].add(d); delta = delta.add(d); } } rewards3[rewardsToken3_][address(0)] = rewards3[rewardsToken3_][address(0)].add(delta); lastUpdateTime3[rewardsToken3_] = Math.max(begin3[rewardsToken3_], Math.min(now, end3[rewardsToken3_])); } if (account != address(0) && applied3_) { rewards3[rewardsToken3_][account] = earned3(rewardsToken3_, account); userRewardPerTokenPaid3[rewardsToken3_][account] = _rewardPerToken3[rewardsToken3_]; } } modifier updateReward3(IERC20 rewardsToken3_, address account) virtual { _updateReward3(rewardsToken3_, account); _; emit TotalSupply3(rewardsToken3_,totalSupply3[rewardsToken3_]); } event TotalSupply3(IERC20 indexed rewardsToken3_, uint totalSupply3); function stake(uint amount) virtual override public { super.stake(amount); for(uint i=0; i<active.length; i++) { IERC20 rewardsToken3_ = active[i]; // save gas _updateReward3(rewardsToken3_, msg.sender); if(applied3[rewardsToken3_][msg.sender]) totalSupply3[rewardsToken3_] = totalSupply3[rewardsToken3_].add(amount); } } function withdraw(uint amount) virtual override public { for(uint i=0; i<active.length; i++) { IERC20 rewardsToken3_ = active[i]; // save gas _updateReward3(rewardsToken3_, msg.sender); if(applied3[rewardsToken3_][msg.sender]) totalSupply3[rewardsToken3_] = totalSupply3[rewardsToken3_].sub(amount); } super.withdraw(amount); } function getReward3(IERC20 rewardsToken3_) virtual public nonReentrant updateReward3(rewardsToken3_, msg.sender) { require(getConfigA(_blocklist_, msg.sender) == 0, 'In blocklist'); bool isContract = msg.sender.isContract(); require(!isContract || config[_allowContract_] != 0 || getConfigA(_allowlist_, msg.sender) != 0, 'No allowContract'); //IERC20 rewardsToken3_ = rewardsToken3; // save gas require(now >= claimTime3[rewardsToken3_], "it's not time yet"); uint256 reward3 = rewards3[rewardsToken3_][msg.sender]; if (reward3 > 0) { rewards3[rewardsToken3_][msg.sender] = 0; rewards3[rewardsToken3_][address(0)] = rewards3[rewardsToken3_][address(0)].sub0(reward3); rewardsToken3_.safeTransferFrom(rewardsDistribution, msg.sender, reward3); emit RewardPaid3(msg.sender, rewardsToken3_, reward3); } } event RewardPaid3(address indexed user, IERC20 indexed rewardsToken3_, uint256 reward3); uint[47] private __gap; } contract NestMasterChefIioV2 is NestMasterChef, IioPoolV2 { function notifyRewardBegin(uint _lep, uint _period, uint _span, uint _begin) virtual override(StakingPool, NestMasterChef) public { NestMasterChef.notifyRewardBegin(_lep, _period, _span, _begin); } function stake(uint amount) virtual override(NestMasterChef, IioPoolV2) public { super.stake(amount); } function withdraw(uint amount) virtual override(NestMasterChef, IioPoolV2) public { super.withdraw(amount); } function exit() virtual override(StakingRewards, NestMasterChef) public { NestMasterChef.exit(); } uint[50] private __gap; } contract BurningPool is StakingPool { address internal constant BurnAddress = 0x000000000000000000000000000000000000dEaD; function stake(uint256 amount) virtual override public { super.stake(amount); stakingToken.safeTransfer(BurnAddress, stakingToken.balanceOf(address(this))); } function withdraw(uint256) virtual override public { revert('Burned already, none to withdraw'); } } contract AirPool is StakingPool { function __AirPool_init(address _governor, address _rewardsDistribution, address _rewardsToken ) public initializer { __Governable_init_unchained(_governor); __ReentrancyGuard_init_unchained(); __StakingRewards_init_unchained(_rewardsDistribution, _rewardsToken, address(0)); __StakingPool_init_unchained(address(0)); __AirPool_init_unchained(); } function __AirPool_init_unchained() public governance { } function stake(uint256) virtual override public { revert('Air Claim, none to stake'); } function withdraw(uint256) virtual override public { revert('Air Claim, none to withdraw'); } function setQuota(address acct, uint amt) virtual external updateReward(address(0)) governance { _totalSupply = _totalSupply.add(amt).sub(_balances[acct]); _balances[acct] = amt; emit SetQuota(acct, amt); } event SetQuota(address acct, uint amt); function setQuotaN(address[] calldata accts, uint amt) virtual external updateReward(address(0)) governance { uint total = _totalSupply; for(uint i=0; i<accts.length; i++) { total = total.add(amt).sub(_balances[accts[i]]); _balances[accts[i]] = amt; } _totalSupply = total; } function setQuotaNN(address[] calldata accts, uint[] calldata amts) virtual external updateReward(address(0)) governance { require(accts.length == amts.length, 'accts.length != amts.length'); uint total = _totalSupply; for(uint i=0; i<accts.length; i++) { total = total.add(amts[i]).sub(_balances[accts[i]]); _balances[accts[i]] = amts[i]; } _totalSupply = total; } } contract Mine is Governable { using SafeERC20 for IERC20; address public reward; function __Mine_init(address governor, address reward_) public initializer { __Governable_init_unchained(governor); __Mine_init_unchained(reward_); } function __Mine_init_unchained(address reward_) public governance { reward = reward_; } function approvePool(address pool, uint amount) public governance { IERC20(reward).approve(pool, amount); } function approveToken(address token, address pool, uint amount) public governance { IERC20(token).approve(pool, amount); } }
rewardsToken3 => acct => rewards3
mapping(IERC20 => mapping(address => uint)) public rewards3;
6,471,159
[ 1, 266, 6397, 1345, 23, 516, 20774, 516, 283, 6397, 23, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 45, 654, 39, 3462, 516, 2874, 12, 2867, 516, 2254, 3719, 1071, 283, 6397, 23, 31, 5397, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only /* Bounty.sol - SKALE Manager Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./delegation/DelegationController.sol"; import "./delegation/PartialDifferences.sol"; import "./delegation/TimeHelpers.sol"; import "./delegation/ValidatorService.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; contract BountyV2 is Permissions { using PartialDifferences for PartialDifferences.Value; using PartialDifferences for PartialDifferences.Sequence; struct BountyHistory { uint month; uint bountyPaid; } uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant EPOCHS_PER_YEAR = 12; uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY; uint private _nextEpoch; uint private _epochPool; uint private _bountyWasPaidInCurrentEpoch; bool public bountyReduction; uint public nodeCreationWindowSeconds; PartialDifferences.Value private _effectiveDelegatedSum; // validatorId amount of nodes mapping (uint => uint) public nodesByValidator; // deprecated // validatorId => BountyHistory mapping (uint => BountyHistory) private _bountyHistory; function calculateBounty(uint nodeIndex) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); require( _getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now, "Transaction is sent too early" ); uint validatorId = nodes.getValidatorId(nodeIndex); if (nodesByValidator[validatorId] > 0) { delete nodesByValidator[validatorId]; } uint currentMonth = timeHelpers.getCurrentMonth(); _refillEpochPool(currentMonth, timeHelpers, constantsHolder); _prepareBountyHistory(validatorId, currentMonth); uint bounty = _calculateMaximumBountyAmount( _epochPool, _effectiveDelegatedSum.getAndUpdateValue(currentMonth), _bountyWasPaidInCurrentEpoch, nodeIndex, _bountyHistory[validatorId].bountyPaid, delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getAndUpdateDelegatedToValidatorNow(validatorId), constantsHolder, nodes ); _bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty); bounty = _reduceBounty( bounty, nodeIndex, nodes, constantsHolder ); _epochPool = _epochPool.sub(bounty); _bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty); return bounty; } function enableBountyReduction() external onlyOwner { bountyReduction = true; } function disableBountyReduction() external onlyOwner { bountyReduction = false; } function setNodeCreationWindowSeconds(uint window) external allow("Nodes") { nodeCreationWindowSeconds = window; } function handleDelegationAdd( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.addToValue(amount, month); } function handleDelegationRemoving( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.subtractFromValue(amount, month); } function populate() external onlyOwner { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); TimeHelpers timeHelpers = TimeHelpers(contractManager.getTimeHelpers()); uint currentMonth = timeHelpers.getCurrentMonth(); // clean existing data for ( uint i = _effectiveDelegatedSum.firstUnprocessedMonth; i < _effectiveDelegatedSum.lastChangedMonth.add(1); ++i ) { delete _effectiveDelegatedSum.addDiff[i]; delete _effectiveDelegatedSum.subtractDiff[i]; } delete _effectiveDelegatedSum.value; delete _effectiveDelegatedSum.lastChangedMonth; _effectiveDelegatedSum.firstUnprocessedMonth = currentMonth; uint[] memory validators = validatorService.getTrustedValidators(); for (uint i = 0; i < validators.length; ++i) { uint validatorId = validators[i]; uint currentEffectiveDelegated = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth); uint[] memory effectiveDelegated = delegationController.getEffectiveDelegatedValuesByValidator(validatorId); if (effectiveDelegated.length > 0) { assert(currentEffectiveDelegated == effectiveDelegated[0]); } uint added = 0; for (uint j = 0; j < effectiveDelegated.length; ++j) { if (effectiveDelegated[j] != added) { if (effectiveDelegated[j] > added) { _effectiveDelegatedSum.addToValue(effectiveDelegated[j].sub(added), currentMonth + j); } else { _effectiveDelegatedSum.subtractFromValue(added.sub(effectiveDelegated[j]), currentMonth + j); } added = effectiveDelegated[j]; } } delete effectiveDelegated; } } function estimateBounty(uint nodeIndex) external view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint currentMonth = timeHelpers.getCurrentMonth(); uint validatorId = nodes.getValidatorId(nodeIndex); uint stagePoolSize; (stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, _effectiveDelegatedSum.getValue(currentMonth), _nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0, nodeIndex, _getBountyPaid(validatorId, currentMonth), delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getDelegatedToValidator(validatorId, currentMonth), constantsHolder, nodes ); } function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) { return _getNextRewardTimestamp( nodeIndex, Nodes(contractManager.getContract("Nodes")), TimeHelpers(contractManager.getContract("TimeHelpers")) ); } function getEffectiveDelegatedSum() external view returns (uint[] memory) { return _effectiveDelegatedSum.getValues(); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextEpoch = 0; _epochPool = 0; _bountyWasPaidInCurrentEpoch = 0; bountyReduction = false; nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY; } // private function _calculateMaximumBountyAmount( uint epochPoolSize, uint effectiveDelegatedSum, uint bountyWasPaidInCurrentEpoch, uint nodeIndex, uint bountyPaidToTheValidator, uint effectiveDelegated, uint delegated, ConstantsHolder constantsHolder, Nodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } if (effectiveDelegatedSum == 0) { // no delegations in the system return 0; } if (constantsHolder.msr() == 0) { return 0; } uint bounty = _calculateBountyShare( epochPoolSize.add(bountyWasPaidInCurrentEpoch), effectiveDelegated, effectiveDelegatedSum, delegated.div(constantsHolder.msr()), bountyPaidToTheValidator ); return bounty; } function _calculateBountyShare( uint monthBounty, uint effectiveDelegated, uint effectiveDelegatedSum, uint maxNodesAmount, uint paidToValidator ) private pure returns (uint) { if (maxNodesAmount > 0) { uint totalBountyShare = monthBounty .mul(effectiveDelegated) .div(effectiveDelegatedSum); return _min( totalBountyShare.div(maxNodesAmount), totalBountyShare.sub(paidToValidator) ); } else { return 0; } } function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) { return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp()); } function _getEpochPool( uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint epochPool, uint nextEpoch) { epochPool = _epochPool; for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) { epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder)); } } function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private { uint epochPool; uint nextEpoch; (epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); if (_nextEpoch < nextEpoch) { (_epochPool, _nextEpoch) = (epochPool, nextEpoch); _bountyWasPaidInCurrentEpoch = 0; } } function _getEpochReward( uint epoch, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint) { uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder); if (epoch < firstEpoch) { return 0; } uint epochIndex = epoch.sub(firstEpoch); uint year = epochIndex.div(EPOCHS_PER_YEAR); if (year >= 6) { uint power = year.sub(6).div(3).add(1); if (power < 256) { return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR); } else { return 0; } } else { uint[6] memory customBounties = [ YEAR1_BOUNTY, YEAR2_BOUNTY, YEAR3_BOUNTY, YEAR4_BOUNTY, YEAR5_BOUNTY, YEAR6_BOUNTY ]; return customBounties[year].div(EPOCHS_PER_YEAR); } } function _reduceBounty( uint bounty, uint nodeIndex, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = bounty; if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _prepareBountyHistory(uint validatorId, uint currentMonth) private { if (_bountyHistory[validatorId].month < currentMonth) { _bountyHistory[validatorId].month = currentMonth; delete _bountyHistory[validatorId].bountyPaid; } } function _getBountyPaid(uint validatorId, uint month) private view returns (uint) { require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid"); if (_bountyHistory[validatorId].month == month) { return _bountyHistory[validatorId].bountyPaid; } else { return 0; } } function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) { uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex); uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp); uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth); uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart); uint currentMonth = timeHelpers.getCurrentMonth(); assert(lastRewardMonth <= currentMonth); if (lastRewardMonth == currentMonth) { uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1)); uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2)); if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) { return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS); } else { return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS)); } } else if (lastRewardMonth.add(1) == currentMonth) { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1)); return _min( currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)), currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS) ); } else { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); return currentMonthStart.add(nodeCreationWindowSeconds); } } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } function _max(uint a, uint b) private pure returns (uint) { if (a < b) { return b; } else { return a; } } } // SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimelimit; /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ function setCheckTime(uint newCheckTime) external onlyOwner { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external onlyOwner { require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyOwner { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyOwner { minimalSchainLifetime = lifetime; } function setComplaintTimelimit(uint timelimit) external onlyOwner { complaintTimelimit = timelimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimelimit = 1800; } } // SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "./utils/StringUtils.sol"; /** * @title ContractManager * @dev Contract contains the actual current mapping from contract IDs * (in the form of human-readable strings) to addresses. */ contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; string public constant BOUNTY = "Bounty"; string public constant CONSTANTS_HOLDER = "ConstantsHolder"; string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager"; string public constant PUNISHER = "Punisher"; string public constant SKALE_TOKEN = "SkaleToken"; string public constant TIME_HELPERS = "TimeHelpers"; string public constant TOKEN_LAUNCH_LOCKER = "TokenLaunchLocker"; string public constant TOKEN_STATE = "TokenState"; string public constant VALIDATOR_SERVICE = "ValidatorService"; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows the Owner to add contract to mapping of contract addresses. * * Emits a {ContractUpgraded} event. * * Requirements: * * - New address is non-zero. * - Contract is not already added. * - Contract address contains code. */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contract address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns contract address. * * Requirements: * * - Contract must exist. */ function getDelegationPeriodManager() external view returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); } function getBounty() external view returns (address) { return getContract(BOUNTY); } function getValidatorService() external view returns (address) { return getContract(VALIDATOR_SERVICE); } function getTimeHelpers() external view returns (address) { return getContract(TIME_HELPERS); } function getTokenLaunchLocker() external view returns (address) { return getContract(TOKEN_LAUNCH_LOCKER); } function getConstantsHolder() external view returns (address) { return getContract(CONSTANTS_HOLDER); } function getSkaleToken() external view returns (address) { return getContract(SKALE_TOKEN); } function getTokenState() external view returns (address) { return getContract(TOKEN_STATE); } function getPunisher() external view returns (address) { return getContract(PUNISHER); } function getContract(string memory name) public view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; if (contractAddress == address(0)) { revert(name.strConcat(" contract has not been found")); } } } // SPDX-License-Identifier: AGPL-3.0-only /* Decryption.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @title Decryption * @dev This contract performs encryption and decryption functions. * Decrypt is used by SkaleDKG contract to decrypt secret key contribution to * validate complaints during the DKG procedure. */ contract Decryption { /** * @dev Returns an encrypted text given a secret and a key. */ function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { return bytes32(secretNumber) ^ key; } /** * @dev Returns a secret given an encrypted text and a key. */ function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { return uint256(ciphertext ^ key); } } // SPDX-License-Identifier: AGPL-3.0-only /* KeyStorage.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Decryption.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 schainId) external allow("SkaleDKG") { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); delete _schainsPublicKeys[schainId]; } function initPublicKeyInProgress(bytes32 schainId) external allow("SkaleDKG") { _publicKeysInProgress[schainId] = G2Operations.getG2Zero(); } function adding(bytes32 schainId, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[schainId] = value.addG2(_publicKeysInProgress[schainId]); } function finalizePublicKey(bytes32 schainId) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(schainId)) { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); } _schainsPublicKeys[schainId] = _publicKeysInProgress[schainId]; delete _publicKeysInProgress[schainId]; } function getCommonPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[schainId]; } function getPreviousPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[schainId].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[schainId][length - 1]; } function getAllPreviousPublicKeys(bytes32 schainId) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[schainId]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) { return _schainsPublicKeys[schainId].x.a == 0 && _schainsPublicKeys[schainId].x.b == 0 && _schainsPublicKeys[schainId].y.a == 0 && _schainsPublicKeys[schainId].y.b == 0; } function _getData() private view returns (BroadcastedData memory) { return _data[keccak256(abi.encodePacked("UnusedFunction"))][0]; } function _getNodesPublicKey() private view returns (G2Operations.G2Point memory) { return _schainsNodesPublicKeys[keccak256(abi.encodePacked("UnusedFunction"))][0]; } } // SPDX-License-Identifier: AGPL-3.0-only /* NodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Strings.sol"; import "./Permissions.sol"; import "./ConstantsHolder.sol"; import "./SchainsInternal.sol"; import "./Schains.sol"; import "./Nodes.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title NodeRotation * @dev This contract handles all node rotation functionality. */ contract NodeRotation is Permissions { using StringUtils for string; using StringUtils for uint; using Strings for uint; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); require(_checkRotation(schainId), "No free Nodes available for rotating"); rotateNode(nodeIndex, schainId, true); return schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false; } /** * @dev Allows SkaleManager contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex); for (uint i = 0; i < schains.length; i++) { Rotation memory rotation = rotations[schains[i]]; if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) { continue; } string memory schainName = schainsInternal.getSchainName(schains[i]); string memory revertMessage = "Node cannot rotate on Schain "; revertMessage = revertMessage.strConcat(schainName); revertMessage = revertMessage.strConcat(", occupied by Node "); revertMessage = revertMessage.strConcat(rotation.nodeIndex.toString()); string memory dkgRevert = "DKG process did not finish on schain "; ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require( skaleDKG.isLastDKGSuccessful(keccak256(abi.encodePacked(schainName))), dkgRevert.strConcat(schainName)); require(rotation.freezeUntil < now, revertMessage); _startRotation(schains[i], nodeIndex); } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainIndex) external onlyOwner { rotations[schainIndex].freezeUntil = now; } /** * @dev Returns rotation details for a given schain. */ function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { return rotations[schainIndex]; } /** * @dev Returns leaving history for a given node. */ function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainIndex) external view returns (bool) { return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an * schain. */ function rotateNode( uint nodeIndex, bytes32 schainId, bool shouldDelay ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Schains schains = Schains(contractManager.getContract("Schains")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); newNode = selectNodeToGroup(schainId); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); schains.addSpace(nodeIndex, space); _finishRotation(schainId, nodeIndex, newNode, shouldDelay); } /** * @dev Allows SkaleManager, Schains, and SkaleDKG contracts to * pseudo-randomly select a new Node for an Schain. * * Requirements: * * - Schain is active. * - A free node already exists. * - Free space can be allocated from the node. */ function selectNodeToGroup(bytes32 schainId) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainId), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); uint[] memory possibleNodes = schainsInternal.isEnoughNodes(schainId); require(possibleNodes.length > 0, "No free Nodes available for rotation"); uint nodeIndex; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), schainId))); do { uint index = random % possibleNodes.length; nodeIndex = possibleNodes[index]; random = uint(keccak256(abi.encodePacked(random, nodeIndex))); } while (schainsInternal.checkException(schainId, nodeIndex)); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); return nodeIndex; } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].newNodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); waitForNewNode[schainIndex] = true; } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); leavingHistory[nodeIndex].push( LeavingHistory(schainIndex, shouldDelay ? now.add(constants.rotationDelay()) : now) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } /** * @dev Checks whether a rotation can be performed. * * Requirements: * * - Schain must exist. */ function _checkRotation(bytes32 schainId ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainId); } } // SPDX-License-Identifier: AGPL-3.0-only /* Nodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol"; import "./delegation/DelegationController.sol"; import "./delegation/ValidatorService.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./Permissions.sol"; /** * @title Nodes * @dev This contract contains all logic to manage SKALE Network nodes states, * space availability, stake requirement checks, and exit functions. * * Nodes may be in one of several states: * * - Active: Node is registered and is in network operation. * - Leaving: Node has begun exiting from the network. * - Left: Node has left the network. * - In_Maintenance: Node is temporarily offline or undergoing infrastructure * maintenance * * Note: Online nodes contain both Active and Leaving states. */ contract Nodes is Permissions { using SafeCast for uint; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; string domainName; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName, uint time, uint gasSpend ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { require(nodeIndex < nodes.length, "Node with such index does not exist"); _; } modifier onlyNodeOrAdmin(uint nodeIndex) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( isNodeExist(msg.sender, nodeIndex) || _isAdmin(msg.sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(msg.sender), "Sender is not permitted to call this function" ); _; } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allow("Schains") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") // returns (uint nodeIndex) { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered"); require(params.port > 0, "Port is zero"); require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); // adds Node to Nodes contract uint nodeIndex = _addNode( from, params.name, params.ip, params.publicIp, params.port, params.publicKey, params.domainName, validatorId); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, params.domainName, block.timestamp, gasleft()); } /** * @dev Allows SkaleManager contract to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); emit ExitInitialized( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); _deleteNode(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); require( validatorNodes.length.add(1).mul(msr) <= delegationsTotal, "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); return position.add(1).mul(msr) <= delegationsTotal; } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); _setNodeInMaintenance(nodeIndex); } /** * @dev Allows Node to remove In_Maintenance status. * * Requirements: * * - Node must already be In Maintenance. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); _setNodeActive(nodeIndex); } function setDomainName(uint nodeIndex, string memory domainName) external onlyNodeOrAdmin(nodeIndex) { nodes[nodeIndex].domainName = domainName; } /** * @dev Returns nodes with space availability. */ function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace)); uint cursor = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns domain name of a given node. * * Requirements: * * - Node must exist. */ function getNodeDomainName(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (string memory) { return nodes[nodeIndex].domainName; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } /** * @dev Returns an address of a given node. */ function getNodeAddress(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (address) { return _publicKeyToAddress(nodes[nodeIndex].publicKey); } /** * @dev Returns the finish exit time of a given node. */ function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev Returns IPs of active nodes. */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev Returns active nodes linked to the `msg.sender` (validator address). */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeExist(msg.sender, indexOfNodes) && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); count = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { count = count.add(spaceToNodes[i].length); } } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].pop(); } else { spaceToNodes[previousSpace].pop(); } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1); } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev Adds node to array. */ function _addNode( address from, string memory name, bytes4 ip, bytes4 publicIP, uint16 port, bytes32[2] memory publicKey, string memory domainName, uint validatorId ) private returns (uint nodeIndex) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId, domainName: domainName })); nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(), indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length })); spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex); numberOfActiveNodes++; } /** * @dev Deletes node from array. */ function _deleteNode(uint nodeIndex) private { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length.sub(1)) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].pop(); } else { spaceToNodes[space].pop(); } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "./ContractManager.sol"; /** * @title Permissions * @dev Contract is connected module for Upgradeable approach, knows ContractManager */ contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* Schains.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./ConstantsHolder.sol"; import "./KeyStorage.sol"; import "./SkaleVerifier.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title Schains * @dev Contains functions to manage Schains such as Schain creation, * deletion, and rotation. */ contract Schains is Permissions { using StringUtils for string; using StringUtils for uint; struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainId, uint time, uint gasSpend ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainId ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainId, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainId, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainId, uint[] nodesInGroup, uint time, uint gasSpend ); bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev Allows SkaleManager contract to create an Schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type is valid. * - There is sufficient deposit to create type of schain. */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name ) external { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); _addSchain(msg.sender, 0, schainParameters); } /** * @dev Allows SkaleManager to remove an schain from the network. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Executed by schain owner. */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not the owner of the Schain" ); address nodesAddress = contractManager.getContract("Nodes"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); if (!Nodes(nodesAddress).isNodeLeft(nodesInGroup[i])) { this.addSpace(nodesInGroup[i], partOfNode); } } schainsInternal.deleteGroup(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @dev Allows SkaleManager to delete any Schain. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Schain exists. */ function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); this.addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainId); address from = schainsInternal.getSchainOwner(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @dev Allows SkaleManager contract to restart schain creation by forming a * new schain group. Executed when DKG procedure fails and becomes stuck. * * Emits a {NodeAdded} event. * * Requirements: * * - Previous DKG procedure must have failed. * - DKG failure got stuck because there were no free nodes to rotate in. * - A free node must be released in the network. */ function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccessful(schainId), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes for new group formation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId); skaleDKG.openChannel(schainId); emit NodeAdded(schainId, newNodeIndex); } /** * @dev addSpace - return occupied space to Node * @param nodeIndex - index of Node at common array of Nodes * @param partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev Checks whether schain group signature is valid. */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Returns the current price in SKL tokens for given Schain type and lifetime. */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (numberOfNodes, divisor) = getNodesDataFromTypeOfSchain(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev Returns the number of Nodes and resource divisor that is needed for a * given Schain type. */ function getNodesDataFromTypeOfSchain(uint typeOfSchain) public view returns (uint numberOfNodes, uint8 partOfNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_SCHAIN(); if (typeOfSchain == 1) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.SMALL_DIVISOR(); } else if (typeOfSchain == 2) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_DIVISOR(); } else if (typeOfSchain == 3) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.LARGE_DIVISOR(); } else if (typeOfSchain == 4) { partOfNode = 0; numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_TEST_SCHAIN(); } else if (typeOfSchain == 5) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_TEST_DIVISOR(); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN(); } else { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); (partOfNode, numberOfNodes) = schainsInternal.schainTypes(typeOfSchain); if (numberOfNodes == 0) { revert("Bad schain type"); } } } /** * @dev Initializes an schain in the SchainsInternal contract. * * Requirements: * * - Schain name is not already in use. */ function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime) private { address dataAddress = contractManager.getContract("SchainsInternal"); require(SchainsInternal(dataAddress).isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain SchainsInternal(dataAddress).initializeSchain( name, from, lifetime, deposit); SchainsInternal(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev Converts data from bytes to normal schain parameters of lifetime, * type, nonce, and name. */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev Allows creation of node group for Schain. * * Emits an {SchainNodes} event. */ function _createGroupForSchain( string memory schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId); emit SchainNodes( schainName, schainId, nodesInGroup, block.timestamp, gasleft()); } /** * @dev Creates an schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type must be valid. */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { uint numberOfNodes; uint8 partOfNode; SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainParameters.typeOfSchain <= schainsInternal.numberOfSchainTypes(), "Invalid type of Schain"); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime); // create a group for Schain (numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternal.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title SchainsInternal * @dev Contract contains all functionality logic to internally manage Schains. */ contract SchainsInternal is Permissions { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; mapping (uint => SchainType) public schainTypes; uint public numberOfSchainTypes; // schain hash => node index => index of place // index of place is a number from 1 to max number of slots on node(128) mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode; /** * @dev Allows Schain contract to initialize an schain. */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = block.timestamp; schains[schainId].startBlock = block.number; schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; isSchainActive[schainId] = true; numberOfSchains++; schainsAtSystem.push(schainId); usedSchainNames[schainId] = true; } /** * @dev Allows Schain contract to create a node group for an schain. */ function createGroupForSchain( bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainId, numberOfNodes); } /** * @dev Allows Schains contract to set index in owner list. */ function setSchainIndex(bytes32 schainId, address from) external allow("Schains") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev Allows Schains contract to change the Schain lifetime through * an additional SKL token deposit. */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") { schains[schainId].deposit = schains[schainId].deposit.add(deposit); schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime); } /** * @dev Allows Schains contract to remove an schain from the network. * Generally schains are not removed from the system; instead they are * simply allowed to expire. */ function removeSchain(bytes32 schainId, address from) external allow("Schains") { isSchainActive[schainId] = false; uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainId = schainIndexes[from][length.sub(1)]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainId]; numberOfSchains--; } /** * @dev Allows Schains and SkaleDKG contracts to remove a node from an * schain for node rotation or DKG failure. */ function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external allowThree("NodeRotation", "SkaleDKG", "Schains") { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length.sub(1); if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash); removeSchainForNode(nodeIndex, schainIndexOnNode); delete placeOfSchainOnNode[schainHash][nodeIndex]; } /** * @dev Allows Schains contract to remove node from exceptions */ function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external allow("Schains") { _exceptionsForGroups[schainHash][nodeIndex] = false; } /** * @dev Allows Schains contract to delete a group of schains */ function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; skaleDKG.deleteChannel(schainId); } /** * @dev Allows Schain and NodeRotation contracts to set a Node like * exception for a given schain and nodeIndex. */ function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _exceptionsForGroups[schainId][nodeIndex] = true; } /** * @dev Allows Schains and NodeRotation contracts to add node to an schain * group. */ function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainId].length == 0) { schainsGroups[schainId].push(nodeIndex); } else { schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainId].length; i++) { if (min > holesForSchains[schainId][i]) { min = holesForSchains[schainId][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainId]; } else { holesForSchains[schainId][0] = min; holesForSchains[schainId][index] = holesForSchains[schainId][holesForSchains[schainId].length - 1]; holesForSchains[schainId].pop(); } } } /** * @dev Allows Schains contract to remove holes for schains */ function removeHolesForSchain(bytes32 schainHash) external allow("Schains") { delete holesForSchains[schainHash]; } /** * @dev Allows Admin to add schain type */ function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlyAdmin { schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode; schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes; numberOfSchainTypes++; } /** * @dev Allows Admin to remove schain type */ function removeSchainType(uint typeOfSchain) external onlyAdmin { delete schainTypes[typeOfSchain].partOfNode; delete schainTypes[typeOfSchain].numberOfNodes; } /** * @dev Allows Admin to set number of schain types */ function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlyAdmin { numberOfSchainTypes = newNumberOfSchainTypes; } /** * @dev Allows Admin to move schain to placeOfSchainOnNode map */ function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyAdmin { for (uint i = 0; i < schainsGroups[schainHash].length; i++) { uint nodeIndex = schainsGroups[schainHash][i]; for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) { if (schainsForNodes[nodeIndex][j] == schainHash) { placeOfSchainOnNode[schainHash][nodeIndex] = j + 1; } } } } /** * @dev Returns all Schains in the network. */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev Returns all occupied resources on one node for an Schain. */ function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) { return schains[schainId].partOfNode; } /** * @dev Returns number of schains by schain owner. */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns the owner of an schain. */ function getSchainOwner(bytes32 schainId) external view returns (address) { return schains[schainId].owner; } /** * @dev Checks whether schain name is available. * TODO Need to delete - copy of web3.utils.soliditySha3 */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0) && !usedSchainNames[schainId] && keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet")); } /** * @dev Checks whether schain lifetime has expired. */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp; } /** * @dev Checks whether address is owner of schain. */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } /** * @dev Checks whether schain exists. */ function isSchainExist(bytes32 schainId) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked("")); } /** * @dev Returns schain name. */ function getSchainName(bytes32 schainId) external view returns (string memory) { return schains[schainId].name; } /** * @dev Returns last active schain of a node. */ function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } /** * @dev Returns active schains of a node. */ function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev Returns number of nodes in an schain group. */ function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) { return schainsGroups[schainId].length; } /** * @dev Returns nodes in an schain group. */ function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) { return schainsGroups[schainId]; } /** * @dev Checks whether sender is a node address from a given schain group. */ function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < schainsGroups[schainId].length; i++) { if (nodes.getNodeAddress(schainsGroups[schainId][i]) == sender) { return true; } } return false; } /** * @dev Returns node index in schain group. */ function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainId].length; index++) { if (schainsGroups[schainId][index] == nodeId) { return index; } } return schainsGroups[schainId].length; } /** * @dev Checks whether there are any nodes with free resources for given * schain. */ function isAnyFreeNode(bytes32 schainId) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { return true; } } return false; } /** * @dev Returns whether any exceptions exist for node in a schain group. */ function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainId][nodeIndex]; } function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } /** * @dev Returns number of Schains on a node. */ function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) { return schainsForNodes[nodeIndex].length; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; numberOfSchainTypes = 5; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. */ function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); placeOfSchainOnNode[schainId][nodeIndex] = schainsForNodes[nodeIndex].length; } else { uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; schainsForNodes[nodeIndex][lastHoleOfNode] = schainId; placeOfSchainOnNode[schainId][nodeIndex] = lastHoleOfNode + 1; holesForNodes[nodeIndex].pop(); } } /** * @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an * schain from a node. */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length.sub(1)) { schainsForNodes[nodeIndex].pop(); } else { schainsForNodes[nodeIndex][schainIndex] = bytes32(0); if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Returns index of Schain in list of schains for a given node. */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { if (placeOfSchainOnNode[schainId][nodeIndex] == 0) return schainsForNodes[nodeIndex].length; return placeOfSchainOnNode[schainId][nodeIndex] - 1; } function isEnoughNodes(bytes32 schainId) public view returns (uint[] memory result) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); uint counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (!_isCorrespond(schainId, nodesWithFreeSpace[i])) { counter++; } } if (counter < nodesWithFreeSpace.length) { result = new uint[](nodesWithFreeSpace.length.sub(counter)); counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { result[counter] = nodesWithFreeSpace[i]; counter++; } } } } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); uint[] memory possibleNodes = isEnoughNodes(schainId); require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain"); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (possibleNodes.length.sub(ignoringTail)); uint node = possibleNodes[index]; nodesInGroup[i] = node; _swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; _exceptionsForGroups[schainId][node] = true; addSchainForNode(node, schainId); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; } function _isCorrespond(bytes32 schainId, uint nodeIndex) private view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); return !_exceptionsForGroups[schainId][nodeIndex] && nodes.isNodeActive(nodeIndex); } /** * @dev Swaps one index for another in an array. */ function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } /** * @dev Returns local index of node in schain group. */ function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainId]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleVerifier.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; /** * @title SkaleVerifier * @dev Contains verify function to perform BLS signature verification. */ contract SkaleVerifier is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; /** * @dev Verifies a BLS signature. * * Requirements: * * - Signature is in G1. * - Hash is in G1. * - G2.one in G2. * - Public Key in G2. */ function verify( Fp2Operations.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, G2Operations.G2Point calldata publicKey ) external view returns (bool) { require(G1Operations.checkRange(signature), "Signature is not valid"); if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB = G1Operations.negate(signature.b); require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { if (counter > 100) { return false; } uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord.add(counter)) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationController.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../BountyV2.sol"; import "../Nodes.sol"; import "../Permissions.sol"; import "../utils/FractionUtils.sol"; import "../utils/MathUtils.sol"; import "./DelegationPeriodManager.sol"; import "./PartialDifferences.sol"; import "./Punisher.sol"; import "./TokenLaunchLocker.sol"; import "./TokenState.sol"; import "./ValidatorService.sol"; /** * @title Delegation Controller * @dev This contract performs all delegation functions including delegation * requests, and undelegation, etc. * * Delegators and validators may both perform delegations. Validators who perform * delegations to themselves are effectively self-delegating or self-bonding. * * IMPORTANT: Undelegation may be requested at any time, but undelegation is only * performed at the completion of the current delegation period. * * Delegated tokens may be in one of several states: * * - PROPOSED: token holder proposes tokens to delegate to a validator. * - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation. * - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator. * - REJECTED: token proposal expires at the UTC start of the next month. * - DELEGATED: accepted delegations are delegated at the UTC start of the month. * - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator. * - COMPLETED: undelegation request is completed at the end of the delegation period. */ contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } /** * @dev Update and return a validator's delegations. */ function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } /** * @dev Update and return the amount delegated. */ function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } /** * @dev Update and return the effective amount delegated (minus slash) for * the given month. */ function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * Emits a {DelegationProposed} event. * * Requirements: * * - Holder must have sufficient delegatable tokens. * - Delegation must be above the validator's minimum delegation amount. * - Delegation period must be allowed. * - Validator must be authorized if trusted list is enabled. * - Validator must be accepting new delegation requests. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { require( _getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); _getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender); uint forbiddenForDelegation = TokenState(contractManager.getTokenState()) .getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows token holder to cancel a delegation proposal. * * Emits a {DelegationRequestCanceledByUser} event. * * Requirements: * * - `msg.sender` must be the token holder of the delegation proposal. * - Delegation state must be PROPOSED. */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a {DelegationAccepted} event. * * Requirements: * * - Validator must be recipient of proposal. * - Delegation state must be PROPOSED. */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require( _getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _accept(delegationId); } /** * @dev Allows delegator to undelegate a specific delegation. * * Emits UndelegationRequested event. * * Requirements: * * - `msg.sender` must be the delegator. * - Delegation state must be DELEGATED. */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = _getValidatorService(); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); require( now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS) < _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished), "Undelegation requests must be sent 3 days before the end of delegation period" ); _subtractFromAllStatistics(delegationId); emit UndelegationRequested(delegationId); } /** * @dev Allows Punisher contract to slash an `amount` of stake from * a validator. This slashes an amount of delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manager to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } } /** * @dev Allows Distributor contract to return and update the effective * amount delegated (minus slash) to a validator for a given month. */ function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } /** * @dev Return and update the amount delegated to a validator for the * current month. */ function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) { return _effectiveDelegatedToValidator[validatorId].getValuesInSequence(); } function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month); } function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _delegatedToValidator[validatorId].getValue(month); } /** * @dev Return Delegation struct. */ function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } /** * @dev Returns the first delegation month. */ function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } /** * @dev Returns a validator's total number of delegations. */ function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } /** * @dev Returns a holder's total number of delegations. */ function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } /** * @dev Process slashes up to the given limit. */ function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } /** * @dev Process all slashes. */ function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } /** * @dev Returns the amount of tokens in PENDING delegation state. */ function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } /** * @dev Checks whether there are any unprocessed slashes. */ function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private /** * @dev Allows Nodes contract to get and update the amount delegated * to validator for a given month. */ function _getAndUpdateDelegatedToValidator(uint validatorId, uint month) private returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } /** * @dev Adds a new delegation proposal. */ function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } /** * @dev Returns the month when a delegation ends. */ function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { return _getTimeHelpers().getCurrentMonth(); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } /** * @dev Checks whether the holder has performed a delegation. */ function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } /** * @dev Returns the delegated amount after a slashing event. */ function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getPunisher()); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _subtractFromAllStatistics(uint delegationId) private { uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _getTokenLaunchLocker().handleDelegationRemoving( delegations[delegationId].holder, delegationId, delegations[delegationId].finished); _getBounty().handleDelegationRemoving( effectiveAmount, delegations[delegationId].finished); } /** * @dev Checks whether delegation to a validator is allowed. * * Requirements: * * - Delegator must not have reached the validator limit. * - Delegation must be made in or after the first delegation month. */ function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) { return DelegationPeriodManager(contractManager.getDelegationPeriodManager()); } function _getBounty() private view returns (BountyV2) { return BountyV2(contractManager.getBounty()); } function _getValidatorService() private view returns (ValidatorService) { return ValidatorService(contractManager.getValidatorService()); } function _getTimeHelpers() private view returns (TimeHelpers) { return TimeHelpers(contractManager.getTimeHelpers()); } function _getTokenLaunchLocker() private view returns (TokenLaunchLocker) { return TokenLaunchLocker(contractManager.getTokenLaunchLocker()); } function _getConstantsHolder() private view returns (ConstantsHolder) { return ConstantsHolder(contractManager.getConstantsHolder()); } function _accept(uint delegationId) private { _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); uint amount = delegations[delegationId].amount; _getTokenLaunchLocker().handleDelegationAdd( delegations[delegationId].holder, delegationId, amount, delegations[delegationId].started ); uint effectiveAmount = amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod) ); _getBounty().handleDelegationAdd( effectiveAmount, delegations[delegationId].started ); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationPeriodManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; /** * @title Delegation Period Manager * @dev This contract handles all delegation offerings. Delegations are held for * a specified period (months), and different durations can have different * returns or `stakeMultiplier`. Currently, only delegation periods can be added. */ contract DelegationPeriodManager is Permissions { mapping (uint => uint) public stakeMultipliers; /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); /** * @dev Allows the Owner to create a new available delegation period and * stake multiplier in the network. * * Emits a {DelegationPeriodWasSet} event. */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner { require(stakeMultipliers[monthsCount] == 0, "Delegation perios is already set"); stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[2] = 100; // 2 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferences.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; import "../utils/FractionUtils.sol"; /** * @title Partial Differences Library * @dev This library contains functions to manage Partial Differences data * structure. Partial Differences is an array of value differences over time. * * For example: assuming an array [3, 6, 3, 1, 2], partial differences can * represent this array as [_, 3, -3, -2, 1]. * * This data structure allows adding values on an open interval with O(1) * complexity. * * For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3), * instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows * performing [_, 3, -3+5, -2, 1]. The original array can be restored by * adding values from partial differences. */ library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value[month]; } } function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value != value) { sequence.value = value; } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function getValue(Value storage sequence, uint month) internal view returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value; } } function getValues(Value storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Punisher.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ILocker.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; /** * @title Punisher * @dev This contract handles all slashing and forgiving operations. */ contract Punisher is Permissions, ILocker { // holder => tokens mapping (address => uint) private _locked; /** * @dev Emitted upon slashing condition. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted upon forgive condition. */ event Forgive( address wallet, uint amount ); /** * @dev Allows SkaleDKG contract to execute slashing on a validator and * validator's delegations by an `amount` of tokens. * * Emits a {Slash} event. * * Requirements: * * - Validator must exist. */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Admin to forgive a slashing condition. * * Emits a {Forgive} event. * * Requirements: * * - All slashes must have been processed. */ function forgive(address holder, uint amount) external onlyAdmin { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows DelegationController contract to execute slashing of * delegations. */ function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpers.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol"; /** * @title TimeHelpers * @dev The contract performs time operations. * * These functions are used to calculate monthly and Proof of Use epochs. */ contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } // SPDX-License-Identifier: AGPL-3.0-only /* TokenLaunchLocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ILocker.sol"; import "../ConstantsHolder.sol"; import "../utils/MathUtils.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; import "./PartialDifferences.sol"; /** * @title TokenLaunchLocker * @dev This contract manages lockers applied to the launch process. */ contract TokenLaunchLocker is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Value; /** * @dev Emitted when an `amount` is unlocked. */ event Unlocked( address holder, uint amount ); /** * @dev Emitted when an `amount` is locked. */ event Locked( address holder, uint amount ); struct DelegatedAmountAndMonth { uint delegated; uint month; } // holder => tokens mapping (address => uint) private _locked; // holder => tokens mapping (address => PartialDifferences.Value) private _delegatedAmount; mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount; // delegationId => tokens mapping (uint => uint) private _delegationAmount; /** * @dev Allows TokenLaunchManager contract to lock an amount of tokens in a * holder wallet. * * Emits a {Locked} event. */ function lock(address holder, uint amount) external allow("TokenLaunchManager") { _locked[holder] = _locked[holder].add(amount); emit Locked(holder, amount); } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new delegations. */ function handleDelegationAdd( address holder, uint delegationId, uint amount, uint month) external allow("DelegationController") { if (_locked[holder] > 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint fromLocked = amount; uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth)); if (fromLocked > locked) { fromLocked = locked; } if (fromLocked > 0) { require(_delegationAmount[delegationId] == 0, "Delegation was already added"); _addToDelegatedAmount(holder, fromLocked, month); _addToTotalDelegatedAmount(holder, fromLocked, month); _delegationAmount[delegationId] = fromLocked; } } } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new undelegation requests. */ function handleDelegationRemoving( address holder, uint delegationId, uint month) external allow("DelegationController") { if (_delegationAmount[delegationId] > 0) { if (_locked[holder] > 0) { _removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month); } delete _delegationAmount[delegationId]; } } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { if (_locked[wallet] > 0) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint currentMonth = timeHelpers.getCurrentMonth(); if (_totalDelegatedSatisfiesProofOfUseCondition(wallet) && timeHelpers.calculateProofOfUseLockEndTime( _totalDelegatedAmount[wallet].month, constantsHolder.proofOfUseLockUpPeriodDays() ) <= now) { _unlock(wallet); return 0; } else { uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth) .add(delegationController.getLockedInPendingDelegations(wallet)); if (_locked[wallet] > lockedByDelegationController) { return _locked[wallet].boundedSub(lockedByDelegationController); } else { return 0; } } } else { return 0; } } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 0; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev Returns and updates the current delegated amount. */ function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) { return _delegatedAmount[holder].getAndUpdateValue(currentMonth); } /** * @dev Adds a delegated amount to the given month. */ function _addToDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].addToValue(amount, month); } /** * @dev Removes a delegated amount from the given month. */ function _removeFromDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].subtractFromValue(amount, month); } /** * @dev Adds the amount to the total delegated for the given month. */ function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private { require( _totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month, "Cannot add to total delegated in the past"); // do not update counter if it is big enough // because it will override month value if (!_totalDelegatedSatisfiesProofOfUseCondition(holder)) { _totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount); _totalDelegatedAmount[holder].month = month; } } /** * @dev Unlocks tokens. * * Emits an {Unlocked} event. */ function _unlock(address holder) private { emit Unlocked(holder, _locked[holder]); delete _locked[holder]; _deleteDelegatedAmount(holder); _deleteTotalDelegatedAmount(holder); } /** * @dev Deletes the delegated amount. */ function _deleteDelegatedAmount(address holder) private { _delegatedAmount[holder].clear(); } /** * @dev Deletes the total delegated amount. */ function _deleteTotalDelegatedAmount(address holder) private { delete _totalDelegatedAmount[holder].delegated; delete _totalDelegatedAmount[holder].month; } /** * @dev Checks whether total delegated satisfies Proof-of-Use. */ function _totalDelegatedSatisfiesProofOfUseCondition(address holder) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return _totalDelegatedAmount[holder].delegated.mul(100) >= _locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage()); } } // SPDX-License-Identifier: AGPL-3.0-only /* TokenState.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../interfaces/delegation/ILocker.sol"; import "../Permissions.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title Token State * @dev This contract manages lockers to control token transferability. * * The SKALE Network has three types of locked tokens: * * - Tokens that are transferrable but are currently locked into delegation with * a validator. * * - Tokens that are not transferable from one address to another, but may be * delegated to a validator `getAndUpdateLockedAmount`. This lock enforces * Proof-of-Use requirements. * * - Tokens that are neither transferable nor delegatable * `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing. */ contract TokenState is Permissions, ILocker { string[] private _lockers; DelegationController private _delegationController; /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { if (address(_delegationController) == address(0)) { _delegationController = DelegationController(contractManager.getContract("DelegationController")); } uint locked = 0; if (_delegationController.getDelegationsByHolderLength(holder) > 0) { // the holder ever delegated for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } } return locked; } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a {LockerWasRemoved} event. */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); addLocker("TokenLaunchLocker"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } // SPDX-License-Identifier: AGPL-3.0-only /* ValidatorService.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title ValidatorService * @dev This contract handles all validator operations including registration, * node management, validator-specific delegation parameters, and more. * * TIP: For more information see our main instructions * https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ]. * * Validators register an address, and use this address to accept delegations and * register nodes. */ contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator ID that includes a validator name, description, * commission or fee rate, and a minimum delegation amount accepted by the validator. * * Emits a {ValidatorRegistered} event. * * Requirements: * * - Sender must not already have registered a validator ID. * - Fee rate must be between 0 - 1000‰. Note: in per mille. */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate <= 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } /** * @dev Allows Admin to enable a validator by adding their ID to the * trusted list. * * Emits a {ValidatorWasEnabled} event. * * Requirements: * * - Validator must not already be enabled. */ function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } /** * @dev Allows Admin to disable a validator by removing their ID from * the trusted list. * * Emits a {ValidatorWasDisabled} event. * * Requirements: * * - Validator must not already be disabled. */ function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the trusted validator list. Once turned off, the * trusted list cannot be re-enabled. */ function disableWhitelist() external onlyOwner { useWhitelist = false; } /** * @dev Allows `msg.sender` to request a new address. * * Requirements: * * - `msg.sender` must already be a validator. * - New address must not be null. * - New address must not be already registered as a validator. */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } /** * @dev Allows msg.sender to confirm an address change. * * Emits a {ValidatorAddressChanged} event. * * Requirements: * * - Must be owner of new address. */ function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a node address to validator ID. Validator must present * the node signature of the validator ID. * * Requirements: * * - Signature must be valid. * - Address must not be assigned to a validator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a node address from a validator. * * Emits a {NodeAddressWasRemoved} event. */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); this.removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } /** * @dev Allows a validator to set a minimum delegation amount. */ function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - Must not have already enabled accepting new requests. */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - Must not have already stopped accepting new requests. */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } /** * @dev Returns the amount of validator bond (self-delegation). */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } /** * @dev Returns node addresses linked to the msg.sender. */ function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns the list of trusted validators. */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } /** * @dev Checks whether the validator ID is linked to the validator address. */ function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } /** * @dev Returns the validator ID linked to a node address. * * Requirements: * * - Node address must be linked to a validator. */ function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view { require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); require( validators[validatorId].minimumDelegationAmount <= amount, "Amount does not meet the validator's minimum delegation amount" ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } /** * @dev Returns a validator's node addresses. */ function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } /** * @dev Checks whether validator ID exists. */ function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } /** * @dev Checks whether validator address exists. */ function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } /** * @dev Checks whether validator address exists. */ function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator address does not exist"); } /** * @dev Returns the Validator struct. */ function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } /** * @dev Returns the validator ID for the given validator address. */ function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } /** * @dev Checks whether the validator is currently accepting new delegation requests. */ function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } // private /** * @dev Links a validator address to a validator ID. * * Requirements: * * - Address is not already in use by another validator. */ function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } /** * @dev Links a node address to a validator ID. * * Requirements: * * - Node address must not be already linked to a validator. */ function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } // SPDX-License-Identifier: AGPL-3.0-only /* ISkaleDKG.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface to {SkaleDKG}. */ interface ISkaleDKG { /** * @dev See {SkaleDKG-openChannel}. */ function openChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-deleteChannel}. */ function deleteChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-isLastDKGSuccessful}. */ function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool); /** * @dev See {SkaleDKG-isChannelOpened}. */ function isChannelOpened(bytes32 schainId) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* ILocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the Locker functions. */ interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // SPDX-License-Identifier: GPL-3.0-or-later /* Modifications Copyright (C) 2018 SKALE Labs ec.sol by @jbaylina under GPL-3.0 License */ /** @file ECDH.sol * @author Jordi Baylina (@jbaylina) * @date 2016 */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title ECDH * @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to * support the DKG process. */ contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { require(a > 0 && a < _N, "Input is incorrect"); uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; // we use (0 0 1) as zero point, z always equal 1 if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } // we use (0 0 1) as zero point, z always equal 1 if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } // SPDX-License-Identifier: AGPL-3.0-only /* FieldOperations.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Precompiled.sol"; library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - subtracted.a, p); } else { difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - subtracted.b, p); } else { difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = (p - addmod(t2, p - t0, p)).mod(p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = (p - mulmod(value.b, t3, p)).mod(p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G1Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return point.a < Fp2Operations.P && point.b < Fp2Operations.P; } function negate(uint y) internal pure returns (uint) { return Fp2Operations.P.sub(y).mod(Fp2Operations.P); } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2Generator() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = (p - sum.y.a).mod(p); sum.y.b = (p - sum.y.b).mod(p); } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = (p - result.y.a).mod(p); result.y.b = (p - result.y.b).mod(p); } } } // SPDX-License-Identifier: AGPL-3.0-only /* FractionUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } // numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1 function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library MathUtils { uint constant private _EPS = 1e6; event UnderflowError( uint a, uint b ); function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Precompiled.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } }
* @dev Allows Distributor contract to return and update the effective amount delegated (minus slash) to a validator for a given month./
function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); }
401,335
[ 1, 19132, 3035, 19293, 6835, 358, 327, 471, 1089, 326, 11448, 3844, 30055, 261, 19601, 9026, 13, 358, 279, 4213, 364, 279, 864, 3138, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22909, 1891, 28531, 15608, 690, 774, 5126, 12, 11890, 4213, 548, 16, 2254, 3138, 13, 203, 3639, 3903, 1699, 11710, 2932, 38, 592, 93, 3113, 315, 1669, 19293, 7923, 1135, 261, 11890, 13, 203, 565, 288, 203, 3639, 327, 389, 28894, 15608, 690, 774, 5126, 63, 7357, 548, 8009, 588, 1876, 1891, 620, 382, 4021, 12, 7496, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; // import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // ****************** // this is for staking lp tokens and getting back $pet tokens // We can use this "MasterChef.sol" conract introduced by SuhiSwap, they do exactly what we need and the code is already used by many smart contracts and battle tested with $100s of millions staked in sushiswap // ******************* // @TODO maybe lets add the roles library to this also to have more then one wallet being able to run this /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require( hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant" ); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require( hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke" ); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require( account == _msgSender(), "AccessControl: can only renounce roles for self" ); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/access/Roles.sol pragma solidity ^0.6.0; contract Roles is AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR"); constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); } modifier onlyMinter() { require( hasRole(MINTER_ROLE, _msgSender()), "Roles: caller does not have the MINTER role" ); _; } modifier onlyOperator() { require( hasRole(OPERATOR_ROLE, _msgSender()), "Roles: caller does not have the OPERATOR role" ); _; } } interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to SushiSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // Interface for our erc20 token interface IMuseToken { function totalSupply() external view returns (uint256); function balanceOf(address tokenOwner) external view returns (uint256 balance); function allowance(address tokenOwner, address spender) external view returns (uint256 remaining); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom( address from, address to, uint256 tokens ) external returns (bool success); function mint(address to, uint256 amount) external; } // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SUSHI is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable, Roles { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SUSHIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below. } // The Muse TOKEN! IMuseToken public museToken; // adding this just in case of nobody using the game but degens hacking the farming bool devFee = false; // Dev address. address public devaddr; // Block number when bonus SUSHI period ends. uint256 public bonusEndBlock; // SUSHI tokens created per block. uint256 public sushiPerBlock; // Bonus muliplier for early sushi makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SUSHI mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( IMuseToken _museToken, // address _devaddr, uint256 _sushiPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { museToken = _museToken; devaddr = msg.sender; sushiPerBlock = _sushiPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } function allowDevFee(bool _allow) public onlyOperator { devFee = _allow; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOperator { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 }) ); } // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOperator { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 sushiReward = multiplier .mul(sushiPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accSushiPerShare = accSushiPerShare.add( sushiReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier .mul(sushiPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); //no dev fee as of now if (devFee) { museToken.mint(devaddr, sushiReward.div(10)); } museToken.mint(address(this), sushiReward); pool.accSushiPerShare = pool.accSushiPerShare.add( sushiReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SUSHI allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accSushiPerShare) .div(1e12) .sub(user.rewardDebt); safeSushiTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub( user.rewardDebt ); safeSushiTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs. function safeSushiTransfer(address _to, uint256 _amount) internal { uint256 sushiBal = museToken.balanceOf(address(this)); if (_amount > sushiBal) { museToken.transfer(_to, sushiBal); } else { museToken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol"; contract MuseToken is ERC20PresetMinterPauser { // Cap at 1 million uint256 internal _cap = 1000000 * 10**18; constructor() public ERC20PresetMinterPauser("Muse", "MUSE") {} /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } // change cap in case of decided by the community function changeCap(uint256 _newCap) external { require( hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint" ); _cap = _newCap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20PresetMinterPauser) { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require( totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded" ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../access/AccessControl.sol"; import "../GSN/Context.sol"; import "../token/ERC20/ERC20.sol"; import "../token/ERC20/ERC20Burnable.sol"; import "../token/ERC20/ERC20Pausable.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) public ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./ERC20.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } pragma solidity ^0.6.2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "./VNFT.sol"; contract PetAirdrop { event Claimed(uint256 index, address owner); VNFT public immutable petMinter; bytes32 public immutable merkleRoot; // This is a packed array of booleans. mapping(uint256 => uint256) private claimedBitMap; constructor(VNFT pet_minter_, bytes32 merkleRoot_) public { petMinter = pet_minter_; merkleRoot = merkleRoot_; } function isClaimed(uint256 index) public view returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } function _setClaimed(uint256 index) private { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } function claim(uint256 index, bytes32[] calldata merkleProof) external { require(!isClaimed(index), "MerkleDistributor: Drop already claimed."); // console.logBytes(abi.encodePacked(index)); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(bytes32(index))); // console.logBytes32(node); require( MerkleProof.verify(merkleProof, merkleRoot, node), "MerkleDistributor: Invalid proof." ); // Mark it claimed and send the token. _setClaimed(index); petMinter.mint(msg.sender); emit Claimed(index, msg.sender); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Burnable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/presets/ERC721PresetMinterPauserAutoId.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; contract TokenRecover is Ownable { /** * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } // Interface for our erc20 token interface IMuseToken { function totalSupply() external view returns (uint256); function balanceOf(address tokenOwner) external view returns (uint256 balance); function allowance(address tokenOwner, address spender) external view returns (uint256 remaining); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom( address from, address to, uint256 tokens ) external returns (bool success); function mintingFinished() external view returns (bool); function mint(address to, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; } /* * Deployment checklist:: * 1. Deploy all contracts * 2. Give minter role to the claiming contract * 3. Add objects (most basic cost 5 and give 1 day and 1 score) * 4. */ // ERC721, contract VNFT is Ownable, ERC721PresetMinterPauserAutoId, TokenRecover, ERC1155Holder { bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); IMuseToken public muse; struct VNFTObj { address token; uint256 id; uint256 standard; //the type } // Mapping from token ID to NFT struct details mapping(uint256 => VNFTObj) public vnftDetails; // max dev allocation is 10% of total supply uint256 public maxDevAllocation = 100000 * 10**18; uint256 public devAllocation = 0; // External NFTs struct NFTInfo { address token; // Address of LP token contract. bool active; uint256 standard; //the nft standard ERC721 || ERC1155 } NFTInfo[] public supportedNfts; using Counters for Counters.Counter; Counters.Counter private _tokenIds; Counters.Counter private _itemIds; // how many tokens to burn every time the VNFT is given an accessory, the remaining goes to the community and devs uint256 public burnPercentage = 90; uint256 public giveLifePrice = 5 * 10**18; bool public gameStopped = false; // mining tokens mapping(uint256 => uint256) public lastTimeMined; // VNFT properties mapping(uint256 => uint256) public timeUntilStarving; mapping(uint256 => uint256) public vnftScore; mapping(uint256 => uint256) public timeVnftBorn; // items/benefits for the VNFT could be anything in the future. mapping(uint256 => uint256) public itemPrice; mapping(uint256 => uint256) public itemPoints; mapping(uint256 => string) public itemName; mapping(uint256 => uint256) public itemTimeExtension; // mapping(uint256 => address) public careTaker; mapping(uint256 => mapping(address => address)) public careTaker; event BurnPercentageChanged(uint256 percentage); event ClaimedMiningRewards(uint256 who, address owner, uint256 amount); event VnftConsumed(uint256 nftId, address giver, uint256 itemId); event VnftMinted(address to); event VnftFatalized(uint256 nftId, address killer); event ItemCreated(uint256 id, string name, uint256 price, uint256 points); event LifeGiven(address forSupportedNFT, uint256 id); event Unwrapped(uint256 nftId); event CareTakerAdded(uint256 nftId, address _to); event CareTakerRemoved(uint256 nftId); constructor(address _museToken) public ERC721PresetMinterPauserAutoId( "VNFT", "VNFT", "https://gallery.verynify.io/api/" ) { _setupRole(OPERATOR_ROLE, _msgSender()); muse = IMuseToken(_museToken); } modifier notPaused() { require(!gameStopped, "Contract is paused"); _; } modifier onlyOperator() { require( hasRole(OPERATOR_ROLE, _msgSender()), "Roles: caller does not have the OPERATOR role" ); _; } modifier onlyMinter() { require( hasRole(MINTER_ROLE, _msgSender()), "Roles: caller does not have the MINTER role" ); _; } function contractURI() public pure returns (string memory) { return "https://gallery.verynifty.io/api"; } // in case a bug happens or we upgrade to another smart contract function pauseGame(bool _pause) external onlyOperator { gameStopped = _pause; } // change how much to burn on each buy and how much goes to community. function changeBurnPercentage(uint256 percentage) external onlyOperator { require(percentage <= 100); burnPercentage = burnPercentage; emit BurnPercentageChanged(burnPercentage); } function changeGiveLifePrice(uint256 _newPrice) external onlyOperator { giveLifePrice = _newPrice * 10**18; } function changeMaxDevAllocation(uint256 amount) external onlyOperator { maxDevAllocation = amount; } function itemExists(uint256 itemId) public view returns (bool) { if (bytes(itemName[itemId]).length > 0) { return true; } } // check that VNFT didn't starve function isVnftAlive(uint256 _nftId) public view returns (bool) { uint256 _timeUntilStarving = timeUntilStarving[_nftId]; if (_timeUntilStarving != 0 && _timeUntilStarving >= block.timestamp) { return true; } } function getVnftScore(uint256 _nftId) public view returns (uint256) { return vnftScore[_nftId]; } function getItemInfo(uint256 _itemId) public view returns ( string memory _name, uint256 _price, uint256 _points, uint256 _timeExtension ) { _name = itemName[_itemId]; _price = itemPrice[_itemId]; _timeExtension = itemTimeExtension[_itemId]; _points = itemPoints[_itemId]; } function getVnftInfo(uint256 _nftId) public view returns ( uint256 _vNFT, bool _isAlive, uint256 _score, uint256 _level, uint256 _expectedReward, uint256 _timeUntilStarving, uint256 _lastTimeMined, uint256 _timeVnftBorn, address _owner, address _token, uint256 _tokenId, uint256 _fatalityReward ) { _vNFT = _nftId; _isAlive = this.isVnftAlive(_nftId); _score = this.getVnftScore(_nftId); _level = this.level(_nftId); _expectedReward = this.getRewards(_nftId); _timeUntilStarving = timeUntilStarving[_nftId]; _lastTimeMined = lastTimeMined[_nftId]; _timeVnftBorn = timeVnftBorn[_nftId]; _owner = this.ownerOf(_nftId); _token = vnftDetails[_nftId].token; _tokenId = vnftDetails[_nftId].id; _fatalityReward = getFatalityReward(_nftId); } function editCurves( uint256 _la, uint256 _lb, uint256 _ra, uint256 _rb ) external onlyOperator { la = _la; lb = _lb; ra = _ra; lb = _rb; } uint256 la = 2; uint256 lb = 2; uint256 ra = 6; uint256 rb = 7; // get the level the vNFT is on to calculate points function level(uint256 tokenId) external view returns (uint256) { // This is the formula L(x) = 2 * sqrt(x * 2) uint256 _score = vnftScore[tokenId].div(100); if (_score == 0) { return 1; } uint256 _level = sqrtu(_score.mul(la)); return (_level.mul(lb)); } // get the level the vNFT is on to calculate the token reward function getRewards(uint256 tokenId) external view returns (uint256) { // This is the formula to get token rewards R(level)=(level)*6/7+6 uint256 _level = this.level(tokenId); if (_level == 1) { return 6 ether; } _level = _level.mul(1 ether).mul(ra).div(rb); return (_level.add(5 ether)); } // edit specific item in case token goes up in value and the price for items gets to expensive for normal users. function editItem( uint256 _id, uint256 _price, uint256 _points, string calldata _name, uint256 _timeExtension ) external onlyOperator { itemPrice[_id] = _price; itemPoints[_id] = _points; itemName[_id] = _name; itemTimeExtension[_id] = _timeExtension; } //can mine once every 24 hours per token. function claimMiningRewards(uint256 nftId) external notPaused { require(isVnftAlive(nftId), "Your vNFT is dead, you can't mine"); require( block.timestamp >= lastTimeMined[nftId].add(1 minutes) || lastTimeMined[nftId] == 0, "Current timestamp is over the limit to claim the tokens" ); require( ownerOf(nftId) == msg.sender || careTaker[nftId][ownerOf(nftId)] == msg.sender, "You must own the vNFT to claim rewards" ); //reset last start mined so can't remine and cheat lastTimeMined[nftId] = block.timestamp; uint256 _reward = this.getRewards(nftId); muse.mint(msg.sender, _reward); emit ClaimedMiningRewards(nftId, msg.sender, _reward); } // Buy accesory to the VNFT function buyAccesory(uint256 nftId, uint256 itemId) external notPaused { require(itemExists(itemId), "This item doesn't exist"); uint256 amount = itemPrice[itemId]; require( ownerOf(nftId) == msg.sender || careTaker[nftId][ownerOf(nftId)] == msg.sender, "You must own the vNFT or be a care taker to buy items" ); // require(isVnftAlive(nftId), "Your vNFT is dead"); uint256 amountToBurn = amount.mul(burnPercentage).div(100); if (!isVnftAlive(nftId)) { vnftScore[nftId] = itemPoints[itemId]; timeUntilStarving[nftId] = block.timestamp.add( itemTimeExtension[itemId] ); } else { //recalculate timeUntilStarving. timeUntilStarving[nftId] = block.timestamp.add( itemTimeExtension[itemId] ); vnftScore[nftId] = vnftScore[nftId].add(itemPoints[itemId]); } // burn 90% so they go back to community mining and staking, and send 10% to devs if (devAllocation <= maxDevAllocation) { devAllocation = devAllocation.add(amount.sub(amountToBurn)); muse.transferFrom(msg.sender, address(this), amount); // burn 90% of token, 10% stay for dev and community fund muse.burn(amountToBurn); } else { muse.burnFrom(msg.sender, amount); } emit VnftConsumed(nftId, msg.sender, itemId); } function setBaseURI(string memory baseURI_) public onlyOperator { _setBaseURI(baseURI_); } function mint(address player) public override onlyMinter { //pet minted has 3 days until it starves at first timeUntilStarving[_tokenIds.current()] = block.timestamp.add(3 days); timeVnftBorn[_tokenIds.current()] = block.timestamp; vnftDetails[_tokenIds.current()] = VNFTObj( address(this), _tokenIds.current(), 721 ); super._mint(player, _tokenIds.current()); _tokenIds.increment(); emit VnftMinted(msg.sender); } // kill starverd NFT and get 10% of his points. function fatality(uint256 _deadId, uint256 _tokenId) external notPaused { require( !isVnftAlive(_deadId), "The vNFT has to be starved to claim his points" ); vnftScore[_tokenId] = vnftScore[_tokenId].add( (vnftScore[_deadId].mul(60).div(100)) ); // delete vnftDetails[_deadId]; _burn(_deadId); emit VnftFatalized(_deadId, msg.sender); } // Check how much score you'll get by fatality someone. function getFatalityReward(uint256 _deadId) public view returns (uint256) { if (isVnftAlive(_deadId)) { return 0; } else { return (vnftScore[_deadId].mul(50).div(100)); } } // add items/accessories function createItem( string calldata name, uint256 price, uint256 points, uint256 timeExtension ) external onlyOperator returns (bool) { _itemIds.increment(); uint256 newItemId = _itemIds.current(); itemName[newItemId] = name; itemPrice[newItemId] = price * 10**18; itemPoints[newItemId] = points; itemTimeExtension[newItemId] = timeExtension; emit ItemCreated(newItemId, name, price, points); } // ***************************** // LOGIC FOR EXTERNAL NFTS // **************************** // support an external nft to mine rewards and play function addNft(address _nftToken, uint256 _type) public onlyOperator { supportedNfts.push( NFTInfo({token: _nftToken, active: true, standard: _type}) ); } function supportedNftLength() external view returns (uint256) { return supportedNfts.length; } function updateSupportedNFT( uint256 index, bool _active, address _address ) public onlyOperator { supportedNfts[index].active = _active; supportedNfts[index].token = _address; } // aka WRAP: lets give life to your erc721 token and make it fun to mint $muse! function giveLife( uint256 index, uint256 _id, uint256 nftType ) external notPaused { uint256 amountToBurn = giveLifePrice.mul(burnPercentage).div(100); if (devAllocation <= maxDevAllocation) { devAllocation = devAllocation.add(giveLifePrice.sub(amountToBurn)); muse.transferFrom(msg.sender, address(this), giveLifePrice); // burn 90% of token, 10% stay for dev and community fund muse.burn(amountToBurn); } else { muse.burnFrom(msg.sender, giveLifePrice); } if (nftType == 721) { IERC721(supportedNfts[index].token).transferFrom( msg.sender, address(this), _id ); } else if (nftType == 1155) { IERC1155(supportedNfts[index].token).safeTransferFrom( msg.sender, address(this), _id, 1, //the amount of tokens to transfer which always be 1 "0x0" ); } // mint a vNFT vnftDetails[_tokenIds.current()] = VNFTObj( supportedNfts[index].token, _id, nftType ); timeUntilStarving[_tokenIds.current()] = block.timestamp.add(3 days); timeVnftBorn[_tokenIds.current()] = block.timestamp; super._mint(msg.sender, _tokenIds.current()); _tokenIds.increment(); emit LifeGiven(supportedNfts[index].token, _id); } // unwrap your vNFT if it is not dead, and get back your original NFT function unwrap(uint256 _vnftId) external { require(isVnftAlive(_vnftId), "Your vNFT is dead, you can't unwrap it"); transferFrom(msg.sender, address(this), _vnftId); VNFTObj memory details = vnftDetails[_vnftId]; timeUntilStarving[_vnftId] = 1; vnftScore[_vnftId] = 0; emit Unwrapped(_vnftId); _withdraw(details.id, details.token, msg.sender, details.standard); } // withdraw dead wrapped NFTs or send them to the burn address. function withdraw( uint256 _id, address _contractAddr, address _to, uint256 _type ) external onlyOperator { _withdraw(_id, _contractAddr, _to, _type); } function _withdraw( uint256 _id, address _contractAddr, address _to, uint256 _type ) internal { if (_type == 1155) { IERC1155(_contractAddr).safeTransferFrom( address(this), _to, _id, 1, "" ); } else if (_type == 721) { IERC721(_contractAddr).transferFrom(address(this), _to, _id); } } // add care taker so in the future if vNFTs are sent to tokenizing platforms like niftex we can whitelist and the previous owner could still mine and do interesting stuff. function addCareTaker(uint256 _tokenId, address _careTaker) external { require( hasRole(OPERATOR_ROLE, _msgSender()) || ownerOf(_tokenId) == msg.sender, "Roles: caller does not have the OPERATOR role" ); careTaker[_tokenId][msg.sender] = _careTaker; emit CareTakerAdded(_tokenId, _careTaker); } function clearCareTaker(uint256 _tokenId) external { require( hasRole(OPERATOR_ROLE, _msgSender()) || ownerOf(_tokenId) == msg.sender, "Roles: caller does not have the OPERATOR role" ); delete careTaker[_tokenId][msg.sender]; emit CareTakerRemoved(_tokenId); } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu(uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128(r < r1 ? r : r1); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC1155Receiver.sol"; import "../../introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() public { _registerInterface( ERC1155Receiver(0).onERC1155Received.selector ^ ERC1155Receiver(0).onERC1155BatchReceived.selector ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../introspection/IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./ERC721.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../access/AccessControl.sol"; import "../GSN/Context.sol"; import "../utils/Counters.sol"; import "../token/ERC721/ERC721.sol"; import "../token/ERC721/ERC721Burnable.sol"; import "../token/ERC721/ERC721Pausable.sol"; /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC721PresetMinterPauserAutoId is Context, AccessControl, ERC721Burnable, ERC721Pausable { using Counters for Counters.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); Counters.Counter private _tokenIdTracker; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ constructor(string memory name, string memory symbol, string memory baseURI) public ERC721(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setBaseURI(baseURI); } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint"); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _mint(to, _tokenIdTracker.current()); _tokenIdTracker.increment(); } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./ERC721.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } pragma solidity ^0.6.2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/introspection/IERC165.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; contract Roles is AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR"); constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); } modifier onlyMinter() { require( hasRole(MINTER_ROLE, _msgSender()), "Roles: caller does not have the MINTER role" ); _; } modifier onlyOperator() { require( hasRole(OPERATOR_ROLE, _msgSender()), "Roles: caller does not have the OPERATOR role" ); _; } } interface IERC721 is IERC165 { event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; function mint(address to) external; } // Stake to get vnfts contract StakeForVnfts is Roles { using SafeMath for uint256; IERC20 public museToken; IERC721 public vNFT; // min $muse amount required to stake uint256 public minStake = 5 * 10**18; // amount of points needed to redeem a vnft, roughly 1 point is given each day; uint256 public vnftPrice = 5 * 10**18; uint256 public totalStaked; mapping(address => uint256) public balance; mapping(address => uint256) public lastUpdateTime; mapping(address => uint256) public points; event Staked(address who, uint256 amount); event Withdrawal(address who, uint256 amount); event VnftMinted(address to); event StakeReqChanged(uint256 newAmount); event PriceOfvnftChanged(uint256 newAmount); constructor(address _vNFT, address _museToken) public { vNFT = IERC721(_vNFT); museToken = IERC20(_museToken); } // changes stake requirement function changeStakeReq(uint256 _newAmount) external onlyOperator { minStake = _newAmount; emit StakeReqChanged(_newAmount); } function changePriceOfNFT(uint256 _newAmount) external onlyOperator { vnftPrice = _newAmount; emit PriceOfvnftChanged(_newAmount); } modifier updateReward(address account) { if (account != address(0)) { points[account] = earned(account); lastUpdateTime[account] = block.timestamp; } _; } //calculate how many points earned so far, this needs to give roughly 1 point a day per 5 tokens staked?. function earned(address account) public view returns (uint256) { uint256 blockTime = block.timestamp; return balance[account] .mul(blockTime.sub(lastUpdateTime[account]).mul(2314814814000)) .div(1e18) .add(points[account]); } function stake(uint256 _amount) external updateReward(msg.sender) { require( _amount >= minStake, "You need to stake at least the min $muse" ); // transfer tokens to this address to stake them totalStaked = totalStaked.add(_amount); balance[msg.sender] = balance[msg.sender].add(_amount); museToken.transferFrom(msg.sender, address(this), _amount); emit Staked(msg.sender, _amount); } // withdraw part of your stake function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Amount can't be 0"); require(totalStaked >= amount); balance[msg.sender] = balance[msg.sender].sub(amount); totalStaked = totalStaked.sub(amount); // transfer erc20 back from the contract to the user museToken.transfer(msg.sender, amount); emit Withdrawal(msg.sender, amount); } // withdraw all your amount staked function exit() external { withdraw(balance[msg.sender]); } //redeem a vNFT based on a set points price function redeem() public updateReward(msg.sender) { require( points[msg.sender] >= vnftPrice, "Not enough points to redeem vNFT" ); points[msg.sender] = points[msg.sender].sub(vnftPrice); vNFT.mint(msg.sender); emit VnftMinted(msg.sender); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/presets/ERC1155PresetMinterPauser.sol"; contract TestERC1155 is ERC1155PresetMinterPauser { constructor(string memory uri) public ERC1155PresetMinterPauser(uri) {} } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../access/AccessControl.sol"; import "../GSN/Context.sol"; import "../token/ERC1155/ERC1155.sol"; import "../token/ERC1155/ERC1155Burnable.sol"; import "../token/ERC1155/ERC1155Pausable.sol"; /** * @dev {ERC1155} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC1155PresetMinterPauser is Context, AccessControl, ERC1155Burnable, ERC1155Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that * deploys the contract. */ constructor(string memory uri) public ERC1155(uri) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`, of token type `id`. * * See {ERC1155-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 id, uint256 amount, bytes memory data) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); _mint(to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}. */ function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); _mintBatch(to, ids, amounts, data); } /** * @dev Pauses all token transfers. * * See {ERC1155Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC1155Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Pausable) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC1155.sol"; import "./IERC1155MetadataURI.sol"; import "./IERC1155Receiver.sol"; import "../../GSN/Context.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri) public { _setURI(uri); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) external view override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address"); batchBalances[i] = _balances[ids[i]][accounts[i]]; } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./ERC1155.sol"; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn(address account, uint256 id, uint256 value) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch(address account, uint256[] memory ids, uint256[] memory values) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./ERC1155.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC1155 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. * * _Available since v3.1._ */ abstract contract ERC1155Pausable is ERC1155, Pausable { /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!paused(), "ERC1155Pausable: token transfer while paused"); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/presets/ERC721PresetMinterPauserAutoId.sol"; contract TestERC721 is ERC721PresetMinterPauserAutoId { constructor() public ERC721PresetMinterPauserAutoId("test721", "t721", "google.com") {} }
in case a bug happens or we upgrade to another smart contract
function pauseGame(bool _pause) external onlyOperator { gameStopped = _pause; }
2,553,137
[ 1, 267, 648, 279, 7934, 10555, 578, 732, 8400, 358, 4042, 13706, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11722, 12496, 12, 6430, 389, 19476, 13, 3903, 1338, 5592, 288, 203, 3639, 7920, 15294, 273, 389, 19476, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]